forked from romariox/SimpleOMRPHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleOMRPHP.php
357 lines (314 loc) · 9.66 KB
/
SimpleOMRPHP.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
<?php
/**
*
* @author Romário Rodrigues Ramos <[email protected]>
* @version 1.0.0
* @license http://escolhaumalicenca.com.br/licencas/mit/ MIT
*
* SimpleOMRPHP verifica as marcações de um formulário atraves de um mapa
* É necessário a instalação do Imagick, ImageMagick e GhostScript
*
* Antes de passar a imagem, verifique se ela já está na resolução(px) certa e, se possível, preto e branco
*
* É recomendado primeiro fazer um teste, com o debug ligado e usar a imagem do debug para fazer a anotação da posição das marcações em arquivos PDF
*/
class SimpleOMRPHP
{
private $map;
private $imagepath;
private $mappath;
private $tolerance;
private $result = [];
private $imagick;
private $draw;
private $debugmode = false;
/**
* Construtor, ira receber tudo que for necessário e irá jogar o resultado em $result, use getResult().
* Se o caminho do $debugimagepath não existir, ele irá tentar criar um diretório 0777, é melhor você se certificar que o caminho existe.
*
* @param string $mappath
* @param string $imagepath
* @param int $tolerance
* @param bool $debugimagepath
* @param bool $debugfilename
*
* @uses Imagick
* @uses ImagickDraw
*
*
* @throws InvalidToleranceException
* @throws JsonDecodeException
* @throws FileNotFoundException
*
*/
public function __construct($mappath, $imagepath, $tolerance = 35, $debugimagepath = false, $debugfilename = false){
try{
if(!is_int($tolerance)){
throw new InvalidToleranceException('Tolerância passada não é um número inteiro válido');
}
if(!@$file = file_get_contents($mappath)){
throw new FileNotFoundException('Não foi possivel encontrar o arquivo de mapa');
}
if(!$json = json_decode($file,true)){
throw new JsonDecodeException('Erro ao decodificar o arquivo json passado');
}
if($debugimagepath != false && $debugfilename != false){
$this->createFolder($debugimagepath);
$this->setDebugMode(true);
$this->prepareDraw();
}
$this->setTolerance($tolerance);
$this->setMap($json);
$this->prepareImage($imagepath);
$this->setResult($this->generateResult());
if($this->isDebugMode()){
$imagick = $this->getImagick();
$draw = $this->getDraw();
$imagick->drawImage($draw);
$imagick->writeImage ($debugimagepath.DIRECTORY_SEPARATOR.$debugfilename);
}
}catch (Exception $e){
echo $e->getMessage();
}
}
/**
* @return array
*/
private function generateResult(){
$map = $this->getMap();
$result = [];
foreach ($map['groups'] as $groupvalue){
$result[]= $this->groupAnalytics($groupvalue);
}
return $result;
}
/**
* @param $group
* @return array
* @throws InvalidTargetTypeException
*/
private function groupAnalytics($group){
$analyticsresults = ['groupname' => $group['groupname']];
$markedtargets = '';
$targetresult = '';
foreach ($group['grouptargets'] as $target){
if($target['type'] == 'rectangle'){
$targetresult[] = array_merge(['id' => $target['id']],$this->rectangleMark($target['x'],$target['y'],$target['width'],$target['height']));
}else{
throw new InvalidTargetTypeException('Tipo não suportado: ',$target['type']);
}
}
foreach ($targetresult as $row){
if($row['ismarked'] == "true"){
$markedtargets .= ($markedtargets == '')? $row['id'] : ','.$row['id'];
}
}
$analyticsresults['markedtargets'] = $markedtargets;
$analyticsresults['targets'] = $targetresult;
return $analyticsresults;
}
/**
* @param $x
* @param $y
* @param $width
* @param $height
* @return array
*/
private function rectangleMark($x, $y, $width, $height){
$blackpixels = 0;
$whidepixels = 0;
$ismarked = false;
$imagick = $this->getImagick();
$pixels = $imagick->exportImagePixels($x,$y,$width,$height,"I", Imagick::PIXEL_CHAR);
$counts = array_count_values($pixels);
foreach($counts as $color => $qtd){
if($color == 255)
$whidepixels += $qtd;
else
$blackpixels += $qtd;
}
$percentblack = ((100 * $blackpixels) / count($pixels));
$ismarked = ($percentblack >= $this->getTolerance()) ? true : false;
if($this->isDebugMode()){
$color = ($ismarked == 'true')? '#00ff00' : '#0000CC';
$this->drawRectangle($x,$y,$width,$height,$color);
}
return ['ismarked' => $ismarked,'percentblack' => $percentblack];
}
/**
* @param $imagepath
*
* @throws UnexpectedResolutionException
*/
private function prepareImage($imagepath){
$imagick = new Imagick();
$map = $this->getMap();
$imagick->readImage($imagepath.'[0]');
$imagick->modulateImage(100, 0, 100);
$imagick->posterizeimage(2, false);
$imagick->thresholdImage(0.5);
// Depreciado, mas não encontrei outra solução
@$imagick->medianFilterImage(5);
$imagick->setImageCompression(imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality(100);
if($imagick->getImageWidth() != $map['expectedwidth'] || $imagick->getImageHeight() != $map['expectedheight']){
throw new UnexpectedResolutionException('A resolução esperada não é igual a resolução final. expectedwidth = '.$map['expectedwidth'].' finalwidth = '.$imagick->getImageWidth().' expectedheight = '. $map['expectedheight'].' finalheight = '.$imagick->getImageHeight());
}
$this->setImagick($imagick);
}
/**
*
*/
private function prepareDraw(){
$draw = new ImagickDraw();
$draw->setStrokeOpacity(1);
$draw->setFillOpacity(0);
$draw->setStrokeWidth(1);
$this->setDraw($draw);
}
/**
* @param $x
* @param $y
* @param $width
* @param $height
* @param $color
*/
private function drawRectangle($x, $y, $width, $height, $color = '#0000CC'){
$this->draw->setStrokeColor($color);
$this->draw->rectangle($x, $y, ($x+$width), ($y+$height));
}
/**
* @param $path
* @return bool
* @throws Exception
*/
private function createFolder($path){
$path = utf8_decode($path);
if (!file_exists($path)) {
if (mkdir($path, 0777, true) == false) {
throw new Exception('Não foi possivel criar o diretório: ' . utf8_encode($path));
}
}
if (!file_exists($path)) {
throw new Exception('Verificação falou, não foi possivel criar o diretório: ' . utf8_encode($path));
}
return true;
}
/**
* @return mixed
*/
private function getImagick()
{
return $this->imagick;
}
/**
* @param mixed $imagick
*/
private function setImagick($imagick)
{
$this->imagick = $imagick;
}
/**
* @return int
*/
private function getTolerance()
{
return $this->tolerance;
}
/**
* @param int $tolerance
*/
private function setTolerance($tolerance)
{
$this->tolerance = $tolerance;
}
/**
* @return boolean
*/
private function isDebugMode()
{
return $this->debugmode;
}
/**
* @param boolean $debugenable
*/
private function setDebugMode($debugenable)
{
$this->debugmode = $debugenable;
}
/**
* @return mixed
*/
private function getMap()
{
return $this->map;
}
/**
* @param mixed $map
*/
private function setMap($map)
{
$this->map = $map;
}
/**
* @return mixed
*/
private function getImagepath()
{
return $this->imagepath;
}
/**
* @param mixed $imagepath
*/
private function setImagepath($imagepath)
{
$this->imagepath = $imagepath;
}
/**
* @return mixed
*/
private function getMappath()
{
return $this->mappath;
}
/**
* @param mixed $mappath
*/
private function setMappath($mappath)
{
$this->mappath = $mappath;
}
/**
* @return mixed
*/
public function getResult()
{
return $this->result;
}
/**
* @param mixed $result
*/
private function setResult($result)
{
$this->result = $result;
}
/**
* @return mixed
*/
private function getDraw()
{
return $this->draw;
}
/**
* @param mixed $draw
*/
private function setDraw($draw)
{
$this->draw = $draw;
}
}
class FileNotFoundException extends Exception{}
class JsonDecodeException extends Exception{}
class InvalidToleranceException extends Exception{}
class InvalidTargetTypeException extends Exception{}
class UnexpectedResolutionException extends Exception{}