|
| 1 | +<?php |
| 2 | +namespace FuncAI\Models; |
| 3 | + |
| 4 | +use FuncAI\Config; |
| 5 | +use FuncAI\Tensorflow\TensorFlow; |
| 6 | + |
| 7 | +class Stylization extends AbstractModel |
| 8 | +{ |
| 9 | + /** |
| 10 | + * @var int |
| 11 | + */ |
| 12 | + private $width; |
| 13 | + /** |
| 14 | + * @var int |
| 15 | + */ |
| 16 | + private $height; |
| 17 | + |
| 18 | + public function getModelPath() |
| 19 | + { |
| 20 | + return Config::getModelBasePath() . '/arbitrary-image-stylization'; |
| 21 | + } |
| 22 | + |
| 23 | + public function getOutputTensor() |
| 24 | + { |
| 25 | + $output = $this->tf->getDefaultGraph()->operation('StatefulPartitionedCall')->output(0); |
| 26 | + |
| 27 | + return $output; |
| 28 | + } |
| 29 | + |
| 30 | + public function getInputData($input) |
| 31 | + { |
| 32 | + return [ |
| 33 | + 'serving_default_placeholder' => $this->toImageTensor($input[0], true), |
| 34 | + 'serving_default_placeholder_1' => $this->toImageTensor($input[1], true), |
| 35 | + ]; |
| 36 | + } |
| 37 | + |
| 38 | + private function toImageTensor($path, $resize = false) |
| 39 | + { |
| 40 | + $img = imagecreatefromjpeg($path); |
| 41 | + if($resize) { |
| 42 | + $img = imagescale($img, 256, 256); |
| 43 | + } |
| 44 | + $this->width = imagesx($img); |
| 45 | + $this->height = imagesy($img); |
| 46 | + $ret = $this->tf->tensor(null, TensorFlow::FLOAT, [1, $this->width, $this->height, 3]); |
| 47 | + $data = $ret->data(); |
| 48 | + |
| 49 | + // Convert the image data into a flat array |
| 50 | + for ($y = 0; $y < $this->height; $y++) { |
| 51 | + for ($x = 0; $x < $this->width; $x++) { |
| 52 | + $rgb = imagecolorat($img, $x, $y); |
| 53 | + $r = ($rgb >> 16) & 0xFF; |
| 54 | + $g = ($rgb >> 8) & 0xFF; |
| 55 | + $b = $rgb & 0xFF; |
| 56 | + $idx = ($y * $this->width * 3) + ($x * 3); |
| 57 | + $data[$idx] = (float)($r/255); |
| 58 | + $data[$idx + 1] = (float)($g/255); |
| 59 | + $data[$idx + 2] = (float)($b/255); |
| 60 | + } |
| 61 | + } |
| 62 | + return $ret; |
| 63 | + } |
| 64 | + |
| 65 | + public function getInputLayer() |
| 66 | + { |
| 67 | + return 'serving_default_input_0'; |
| 68 | + } |
| 69 | + |
| 70 | + protected function transformResult($result) |
| 71 | + { |
| 72 | + return $this->saveImage($result); |
| 73 | + } |
| 74 | + |
| 75 | + private function saveImage($imageData) |
| 76 | + { |
| 77 | + $imageData = $imageData[0]; |
| 78 | + $w = count($imageData); |
| 79 | + $h = count($imageData[0]); |
| 80 | + $img = imagecreatetruecolor($w, $h); |
| 81 | + foreach($imageData as $y => $row) { |
| 82 | + foreach($row as $x => $color) { |
| 83 | + $color = array_map(function($c) { |
| 84 | + $c *= 255; |
| 85 | + return min(255,max(0,$c)); |
| 86 | + }, $color); |
| 87 | + $c = imagecolorallocate($img, $color[0], $color[1], $color[2]); |
| 88 | + imagesetpixel($img, $x, $y, $c); |
| 89 | + } |
| 90 | + } |
| 91 | + imagejpeg($img, 'out.jpg'); |
| 92 | + } |
| 93 | +} |
0 commit comments