-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvolution.php
More file actions
112 lines (95 loc) · 3.37 KB
/
Copy pathConvolution.php
File metadata and controls
112 lines (95 loc) · 3.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
class convolution {
public $kernel = [];
private $img;
private $img_w;
private $img_h;
public $r_array = [];
public $g_array = [];
public $b_array = [];
public $a_array = [];
public $colors_array = [];
private function getPixelColors($x, $y){
$rgb = imagecolorat($this->img, $x,$y);
$colors = imagecolorsforindex($this->img, $rgb);
// $red = ($rgb >> 16) & 255;
// $green = ($rgb >> 8) & 255;
// $blue = $rgb & 255;
return $colors;
}
public function getColorArray(){
$color_array = [];
for($x = 0; $x < $this->img_w; $x++){
for($y = 0; $y < $this->img_h; $y++){
$pixel = $this->getPixelColors($x, $y);
$color_array[$x][$y] = $pixel;
$this->r_array[$x][$y] = $pixel["red"];
$this->g_array[$x][$y] = $pixel["green"];
$this->b_array[$x][$y] = $pixel["blue"];
$this->a_array[$x][$y] = $pixel["alpha"];
}
}
return $color_array;
}
public function createImage($result,$red_arr, $g_arr, $b_arr, $a_array){
$w = count($red_arr);
$h = count($red_arr[0]);
$img=imagecreatetruecolor($w,$h);
imagesavealpha($img,true);
imagealphablending($img,false);
for($x = 0; $x<=$w; $x++){
for($y = 0; $y<=$h; $y++){
$r = $red_arr[$x][$y];
if($r > 255)
$r = 255;
if($r < 1)
$r = 0;
$g = $g_arr[$x][$y];
if($g > 255)
$g = 255;
if($g < 1)
$g = 0;
$b = $b_arr[$x][$y];
if($b > 255)
$b = 255;
if($b < 1)
$b = 0;
$alpha = $a_array[$x][$y];
$color = imagecolorallocatealpha($img,$r,$g,$b,$alpha);
imagesetpixel($img,$x,$y,$color);
}
}
imagepng($img,$result);
}
function convolution($image) {
$imageWidth = count($image[0]);
$imageHeight = count($image);
$kernelWidth = count($this->kernel[0]);
$kernelHeight = count($this->kernel);
$output = array();
for ($y = 0; $y < $imageHeight - $kernelHeight + 1; $y++) {
for ($x = 0; $x < $imageWidth - $kernelWidth + 1; $x++) {
$sum = 0;
$p_count=0;
for ($ky = 0; $ky < $kernelHeight; $ky++) {
for ($kx = 0; $kx < $kernelWidth; $kx++) {
$sum += $image[$y + $ky][$x + $kx] * $this->kernel[$ky][$kx];
if($image[$y + $ky][$x + $kx] * $this->kernel[$ky][$kx] != 0){
$p_count++;
}
}
}
$output[$y][$x] = ($sum) ? round($sum/$p_count+1) : 0;
}
}
return $output;
}
public function __construct($img_path, $kernel){
$this->kernel = $kernel;
$img = imagecreatefrompng($img_path);
$this->img = $img;
$this->img_w = imagesx($this->img);
$this->img_h = imagesy($this->img);
$this->colors_array = $this->getColorArray();
}
}