-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.php
474 lines (407 loc) · 13.8 KB
/
index.php
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('xdebug.var_display_max_children', -1);
require 'algs.php';
class I{
/** @var \Imagick изображение */
private $_i;
/** @var int ширина */
private $_w;
/** @var int высота */
private $_h;
/** @var array Бинарная матрица, упакованная в int'ы */
private $_mPacked;
/** Коэффициенты границ яркости для строк */
const k1 = .05;
const k2 = .05;
/** Коэффициенты границ яркости для слов */
const k3 = .1;
const k4 = .1;
/** Коэффициент границ яркости для символов */
const k5 = .1;
/** Коэффициент отношения ширины символа к высоте для шрифта */
const FONT_KOEF = 0.6;
const k6 = 0.15;
const TOP_BLUR = 4;
// const TOP_BLUR = 0;
const BOTTOM_BLUR = 2;
// const BOTTOM_BLUR = 0;
const LEFT_BLUR = 1;
const RIGHT_BLUR = 1;
/**
* @param $path
*/
public function __construct($path){
$begin = new Imagick($path);
$this->_w = 1392;
$this->_h = $begin->getimageheight();
$this->_i = $im = $begin->getimageregion($this->_w, $this->_h, 0 ,0);
// $this->_mPacked = $this->_imageToMatrix($im, true);
}
/**
* Полный анализ изображения
*/
public function analyze(){
//выделяем строки
$edges = $this->getEdges();
// $this->drawEdges($edges); die;
$lines = $this->getLines($edges); /** @var Imagick[] $lines */
//выделяем слова
$line2words = [];
$wordEdges = [];
$fromLine = 0;
$toLine = 10; //count($lines);
set_time_limit(300);
for($i = $fromLine; $i < $toLine; ++$i){
$wordEdges[$i] = $this->getWordEdges($lines[$i], $edges[$i]);
$words = $this->getWords($wordEdges[$i], $lines[$i]);
$line2words[$i] = $words;
}
// $stacked = new Imagick();
for($j = $fromLine; $j < $toLine; ++$j){
for($i = 0; $i < count($line2words[$j]); ++$i){
$word = $line2words[$j][$i];
$letterEdges = $this->getLetterEdges($word);
// $shifted = array_map(function($v) use($wordEdges, $i, $j) {
// return $v + $wordEdges[$j][$i]['left'];
// }, $letterEdges);
// $this->drawVerticalEdges($shifted, $lines[$j], false, true);
$this->_saveLetters($word, $letterEdges);
}
// $stacked->addimage($lines[$j]);
}
echo 'ok';
// $stacked->resetiterator();
// $result = $stacked->appendimages(true);
// $this->render($result);
// $this->render();
// $this->drawEdges($edges, $result);
}
private $_fileN = 0;
private function _saveLetters(Imagick $word, $edges){
$word->setimagepage(0,0,0,0);
$h = $word->getimageheight();
$first = false;
$start = $edges[0];
foreach($edges as $edge){
if(!$first){
$first = true;
continue;
}
$letter = $word->getimageregion($edge - $start, $h, $start, 0);
$letter->trimimage(0);
$letter->setImageFormat('png');
++$this->_fileN;
$letter->writeimage('letters/' . $this->_fileN . '.jpg');
$start = $edge;
}
}
public function checkLetters(){
$base = [];
$baseW = 0;
$baseH = 0;
foreach(scandir('base') as $img){
if($img == '.' || $img == '..'){
continue;
}
$im = new Imagick('base/' . $img);
$base[$img] = $im; //$this->_imageToMatrix($im);
$baseW = max($baseW, $im->getimagewidth());
$baseH = max($baseH, $im->getimageheight());
}
foreach($base as $file => &$im){ /** @var Imagick $im */
$im->scaleimage($baseW, $baseH);
}
$result = [];
foreach(scandir('letters') as $img){
if($img == '.' || $img == '..'){
continue;
}
$im = new Imagick('letters/' . $img);
$im->scaleimage($baseW, $baseH);
$maxK = 0;
foreach($base as $file => $baseIm){
$k = $im->compareimages($baseIm, Imagick::METRIC_MEANSQUAREERROR)[1];
// if($k > $maxK){
// $result[$img] = $file;
// }
$result[] = $k;
}
var_dump($k, $result); die;
}
// asort($result);
echo '<style>img { border: 1px solid gray; }</style>';
echo '<table>';
foreach($result as $img => $file){
echo "<tr><td><img src=\"letters/$img\"><img src=\"base/$file\"></td></tr>";
}
echo '</table>';
}
private function _compareLetters($one, $two){
$h1 = count($one);
$w1 = count($one[0]);
$h2 = count($two);
$w2 = count($two[0]);
$h = max($h1, $h2);
$w = max($w1, $w2);
$kh = min($h1, $h2) / $h;
$kw = min($w1, $w2) / $w;
$sum = 0;
for($i = 0; $i < $h; ++$i){
for($j = 0; $j < $w; ++$j){
$x1 = $j;
$x2 = (int)floor($kw * $j);
if($w1 < $w2){
$x = $x1;
$x1 = $x2;
$x2 = $x;
}
$y1 = $i;
$y2 = (int)floor($kh * $i);
if($h1 < $h2){
$y = $y1;
$y1 = $y2;
$y2 = $y;
}
if(!isset($one[$y1][$x1]) || !isset($two[$y2][$x2])){
var_dump($w1, $h1, $w2, $h2, $x1, $y1, $x2, $y2, $kw, $kh); die;
}
if($one[$y1][$x1] == $two[$y2][$x2]){
++$sum;
}
}
}
return round($sum / $w / $h * 100);
}
/**
* Рассчёт границ символов
* @param Imagick $word
* @return array
*/
public function getLetterEdges(Imagick $word){
$m = $this->_imageToMatrix($word);
$edges = Alg::getLetterEdges($m, self::FONT_KOEF, self::k5, self::k6);
return $edges;
}
/**
* Разбить картинку строки на картинки слов
* @param array $wordEdges
* @param Imagick $line
* @return Imagick[]
*/
public function getWords($wordEdges, Imagick $line){
$result = [];
$line->setImagePage(0, 0, 0, 0); //сбрасываем метрику для изображений
foreach($wordEdges as $one){
$result[] = $line->getimageregion($one['right'] - $one['left'], $line->getimageheight(), $one['left'], 0);
}
return $result;
}
/**
* Выделение слов из строки
* @param Imagick $line
* @return array[] col => left|right
*/
public function getWordEdges(Imagick $line){
//делаем контуры букв жирными
$copy = clone $line;
$copy->gaussianblurimage(10, 5);
$max = $copy->getQuantumRange();
$max = $max['quantumRangeLong'];
$copy->thresholdImage(0.77 * $max);
$m = $this->_imageToMatrix($copy);
unset($copy);
$edges = Alg::getWordEdges($m, self::k3, self::k4);
foreach($edges as &$edge){
$edge['left'] -= self::LEFT_BLUR;
$edge['right'] += self::RIGHT_BLUR;
}
return $edges;
}
/**
* Переводит изображение в матрицу из 0 и 1 и упаковывает в int'ы
* @param Imagick $im изображение
* @param bool $packed
* @return array
*/
private function _imageToMatrix(Imagick $im, $packed = false){
$m = [];
$it = $im->getpixeliterator();
while($row = $it->getnextiteratorrow()){ /** @var ImagickPixel[] $row */
$s = [];
foreach($row as $pixel){
$s[] = $pixel->getcolor()['r'] / 255;
}
if($packed){
//режем строку на куски по 32 цифры и упаковываем в int'ы
$m[] = array_map('bindec', str_split(implode($s), 32));
}else{
$m[] = $s;
}
}
return $m;
}
/**
* Возвращает часть матрицы и распаковывает её
* @param array $m
* @param int $fromRow
* @param int $toRow
* @param int $width
* @return array
*/
private function _getMatrix($m, $fromRow, $toRow, $width = null){
$result = [];
$lengths = [];
for($i = $fromRow; $i < $toRow; ++$i){
$s = implode(array_map('decbin', $m[$i]));
$lengths[] = strlen($s);
}
$maxLen = $width ? : max($lengths);
foreach($result as &$row){
$c = $maxLen - strlen($row);
$row = str_split(str_repeat('0', $c) . $row);
}
return $result;
}
/**
* Получить границы строк
* @return array Массив границ
*/
public function getEdges(){
$s = $this->_getS();
$s = array_map(function($v){
return 255 - $v;
}, $s);
$lines = Alg::getLines($s, self::k1, self::k2);
foreach($lines as &$line){
$line['top'] -= self::TOP_BLUR;
$line['bottom'] += self::BOTTOM_BLUR;
}
return $lines;
}
/**
* Порезать исходное изображение на изображения строк
* @param array $edges
* @return Imagick[]
*/
public function getLines($edges){
$im = $this->_i;
$result = [];
foreach($edges as $one){
$result[] = $im->getimageregion($this->_w, $one['bottom'] - $one['top'], 0, $one['top']);
}
return $result;
}
/**
* Рисование картинки с нанесёнными на неё границами строк
* @param $edges
* @param null $im
*/
public function drawEdges($edges, $im = null){
$draw = new ImagickDraw();
$draw->setstrokecolor(new ImagickPixel('green'));
foreach($edges as $one){
$level = $one['top'];
$draw->line(0, $level, $this->_w, $level);
}
$draw->setstrokecolor(new ImagickPixel('red'));
foreach($edges as $one){
$level = $one['bottom'];
$draw->line(0, $level, $this->_w, $level);
}
$im = $im ? : $this->_i;
$im->drawimage($draw);
$this->render($im);
}
/**
* Рисование картинки с нанесёнными на неё вертикальными границами слов/букв
* @param array $edges
* @param Imagick $im
* @param bool $output
* @param bool $oneColor
*/
public function drawVerticalEdges($edges, $im, $output = true, $oneColor = false){
$draw = new ImagickDraw();
$height = $im->getimageheight();
$draw->setstrokecolor(new ImagickPixel('green'));
if($oneColor){
foreach($edges as $one){
$draw->line($one, 0, $one, $height);
}
}else{
foreach($edges as $one){
$level = $one['left'];
$draw->line($level, 0, $level, $height);
}
$draw->setstrokecolor(new ImagickPixel('red'));
foreach($edges as $one){
$level = $one['right'];
$draw->line($level, 0, $level, $height);
}
}
$im->drawimage($draw);
if($output){
$this->render($im);
}
}
public function countS(){
$im = $this->_i;
$it = $im->getpixeliterator();
$a = [];
$t = microtime(true);
$i = 0;
set_time_limit(100);
while($row = $it->getnextiteratorrow()){ /** @var ImagickPixel[] $row */
$s = [];
foreach($row as $pixel){
$s[] = $pixel->getcolor()['r'];
}
$a[] = array_sum($s) / count($s);
}
$this->_saveS($a);
ini_set('xdebug.var_display_max_data', -1);
ini_set('xdebug.var_display_max_children', -1);
var_dump($a);
}
private function _saveS($a){
$f = fopen('s.txt', 'w');
fwrite($f, json_encode($a));
fclose($f);
}
private function _getS(){
$s = file_get_contents('s.txt');
return json_decode($s, true);
}
public function checkPixels(){
$im = $this->_i;
$it = $im->getpixeliterator();
$t = microtime(true);
$i = 0;
$a = [];
set_time_limit(100);
while($row = $it->getnextiteratorrow()){
foreach($row as $pixel){ /** @var ImagickPixel $pixel */
$color = $pixel->getcolorasstring();
// if(array_diff($color, [0, 1, 255])){
// if(!in_array($color, ['srgb(255,255,255)', 'srgb(0%,0%,0%)'])){
// var_dump($color);
// die;
// }
$a[] = $color;
}
$a = array_unique($a);
}
printf('Time: %s I: %s', microtime(true) - $t, $i);
var_dump($a);
}
public function render($im = null){
$im = $im ? : $this->_i;
$im->setImageFormat('png');
header('Content-Type: image/png');
echo $im;
}
}
$i = new I('p0011-sel.png');
//$i->analyze();
$i->checkLetters();