-
Notifications
You must be signed in to change notification settings - Fork 1
/
catimages.py
3879 lines (3369 loc) · 174 KB
/
catimages.py
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Image by content categorization derived from 'checkimages.py'.
Script to check uncategorized files. This script checks if a file
has some content that allows to assign it to a category.
This script runs on commons only. It needs also external libraries
(see imports and comments there) and additional configuration/data
files in order to run properly. Most of them can be checked-out at:
http://svn.toolserver.org/svnroot/drtrigon/
(some code might get compiled on-the-fly, so a GNU compiler along
with library header files is needed too)
This script understands the following command-line arguments:
-cat[:#] Use a category as recursive generator
(if no given 'Category:Media_needing_categories' is used)
-start[:#] Start after File:[:#] or if no file given start from top
(instead of resuming last run).
-limit The number of images to check (default: 80)
-noguesses If given, this option will disable all guesses (which are
less reliable than true searches).
-single:# Run for one (any) single page only.
-train Train classifiers on good (homegenous) categories.
X-sendemail Send an email after tagging.
X-untagged[:#] Use daniel's tool as generator:
X http://toolserver.org/~daniel/WikiSense/UntaggedImages.php
"""
#
# (C) Kyle/Orgullomoore, 2006-2007 (newimage.py)
# (C) Pywikipedia team, 2007-2011 (checkimages.py)
# (C) DrTrigon, 2012
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id: catimages.py 11578 2013-05-24 17:03:42Z drtrigon $'
#
# python default packages
import re, urllib2, os, locale, sys, datetime, math, shutil, mimetypes, shelve
import StringIO, json # fallback: simplejson
from subprocess import Popen, PIPE
import Image
#import ImageFilter
scriptdir = os.path.dirname(sys.argv[0])
if not os.path.isabs(scriptdir):
scriptdir = os.path.abspath(os.path.join(os.curdir, scriptdir))
# additional python packages (non-default but common)
try:
import numpy as np
from scipy import ndimage, fftpack, linalg#, signal
import cv
# TS: nonofficial cv2.so backport of the testing-version of
# python-opencv because of missing build-host, done by DaB
sys.path.append('/usr/local/lib/python2.6/')
import cv2
sys.path.remove('/usr/local/lib/python2.6/')
import pyexiv2
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
import gtk # ignore warning: "GtkWarning: could not open display"
import rsvg # gnome-python2-rsvg (binding to librsvg)
import cairo
import magic # python-magic (binding to libmagic)
except:
# either raise the ImportError later or skip it
pass
# pywikipedia framework python packages
import wikipedia as pywikibot
import pagegenerators, catlib
import checkimages
import externals # allow import from externals
# additional python packages (more exotic and problematic ones)
# modules needing compilation are imported later on request:
# (see https://jira.toolserver.org/browse/TS-1452)
# e.g. opencv, jseg, slic, pydmtx, zbar, (pyml or equivalent)
# binaries: exiftool, pdftotext/pdfimages (poppler), ffprobe (ffmpeg),
# convert/identify (ImageMagick), (ocropus)
# TODO:
# (pdfminer not used anymore/at the moment...)
# python-djvulibre or python-djvu for djvu support
externals.check_setup('colormath') # check for and install needed
externals.check_setup('jseg') # 'externals' modules
externals.check_setup('jseg/jpeg-6b') #
#externals.check_setup('_mlpy') #
externals.check_setup('_music21') #
externals.check_setup('opencv/haarcascades') #
externals.check_setup('pydmtx') # <<< !!! test OS package management here !!!
externals.check_setup('py_w3c') #
externals.check_setup('_zbar') #
import pycolorname
#import _mlpy as mlpy
from colormath.color_objects import RGBColor
from py_w3c.validators.html.validator import HTMLValidator, ValidationFault
#from pdfminer import pdfparser, pdfinterp, pdfdevice, converter, cmapdb, layout
#externals.check_setup('_ocropus')
locale.setlocale(locale.LC_ALL, '')
###############################################################################
# <--------------------------- Change only below! --------------------------->#
###############################################################################
# NOTE: in the messages used by the Bot if you put __botnick__ in the text, it
# will automatically replaced with the bot's nickname.
# Add your project (in alphabetical order) if you want that the bot start
project_inserted = [u'commons',]
# Ok, that's all. What is below, is the rest of code, now the code is fixed and it will run correctly in your project.
################################################################################
# <--------------------------- Change only above! ---------------------------> #
################################################################################
tmpl_FileContentsByBot = u"""}}
{{FileContentsByBot
| botName = ~~~
|"""
# this list is auto-generated during bot run (may be add notifcation about NEW templates)
#tmpl_available_spec = [ u'Properties', u'ColorRegions', u'Faces', u'ColorAverage' ]
tmpl_available_spec = [] # auto-generated
# global
useGuesses = True # Use guesses which are less reliable than true searches
# all detection and recognition methods - bindings to other classes, modules and libs
class FileData(object):
# .../opencv/samples/c/facedetect.cpp
# http://opencv.willowgarage.com/documentation/python/genindex.html
def _detect_Faces_CV(self):
"""Converts an image to grayscale and prints the locations of any
faces found"""
# http://python.pastebin.com/m76db1d6b
# http://creatingwithcode.com/howto/face-detection-in-static-images-with-python/
# http://opencv.willowgarage.com/documentation/python/objdetect_cascade_classification.html
# http://opencv.willowgarage.com/wiki/FaceDetection
# http://blog.jozilla.net/2008/06/27/fun-with-python-opencv-and-face-detection/
# http://www.cognotics.com/opencv/servo_2007_series/part_4/index.html
# skip file formats not supported (yet?)
if (self.image_mime[1] in ['ogg', 'pdf', 'vnd.djvu']):
return
# https://code.ros.org/trac/opencv/browser/trunk/opencv_extra/testdata/gpu/haarcascade?rev=HEAD
xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_eye_tree_eyeglasses.xml')
#xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_eye.xml')
if not os.path.exists(xml):
raise IOError(u"No such file: '%s'" % xml)
#nestedCascade = cv.Load(
nestedCascade = cv2.CascadeClassifier(xml)
# http://tutorial-haartraining.googlecode.com/svn/trunk/data/haarcascades/
xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_frontalface_alt.xml')
# MAY BE USE 'haarcascade_frontalface_alt_tree.xml' ALSO / INSTEAD...?!!
if not os.path.exists(xml):
raise IOError(u"No such file: '%s'" % xml)
#cascade = cv.Load(
cascade = cv2.CascadeClassifier(xml)
xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_profileface.xml')
if not os.path.exists(xml):
raise IOError(u"No such file: '%s'" % xml)
cascadeprofil = cv2.CascadeClassifier(xml)
xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_mcs_mouth.xml')
if not os.path.exists(xml):
raise IOError(u"No such file: '%s'" % xml)
cascademouth = cv2.CascadeClassifier(xml)
xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_mcs_nose.xml')
if not os.path.exists(xml):
raise IOError(u"No such file: '%s'" % xml)
cascadenose = cv2.CascadeClassifier(xml)
xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_lefteye_2splits.xml')
if not os.path.exists(xml):
raise IOError(u"No such file: '%s'" % xml)
cascadelefteye = cv2.CascadeClassifier(xml) # (http://yushiqi.cn/research/eyedetection)
xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_righteye_2splits.xml')
if not os.path.exists(xml):
raise IOError(u"No such file: '%s'" % xml)
cascaderighteye = cv2.CascadeClassifier(xml) # (http://yushiqi.cn/research/eyedetection)
xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_mcs_leftear.xml')
if not os.path.exists(xml):
raise IOError(u"No such file: '%s'" % xml)
cascadeleftear = cv2.CascadeClassifier(xml)
xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_mcs_rightear.xml')
if not os.path.exists(xml):
raise IOError(u"No such file: '%s'" % xml)
cascaderightear = cv2.CascadeClassifier(xml)
#self._info['Faces'] = []
scale = 1.
# So, to find an object of an unknown size in the image the scan
# procedure should be done several times at different scales.
# http://opencv.itseez.com/modules/objdetect/doc/cascade_classification.html
try:
#image = cv.LoadImage(self.image_path)
#img = cv2.imread( self.image_path, cv.CV_LOAD_IMAGE_COLOR )
img = cv2.imread( self.image_path_JPEG, cv.CV_LOAD_IMAGE_COLOR )
#image = cv.fromarray(img)
if img == None:
raise IOError
# !!! the 'scale' here IS RELEVANT FOR THE DETECTION RATE;
# how small and how many features are detected as faces (or eyes)
scale = max([1., np.average(np.array(img.shape)[0:2]/500.)])
except IOError:
pywikibot.warning(u'unknown file type [_detect_Faces_CV]')
return
except AttributeError:
pywikibot.warning(u'unknown file type [_detect_Faces_CV]')
return
#detectAndDraw( image, cascade, nestedCascade, scale );
# http://nullege.com/codes/search/cv.CvtColor
#smallImg = cv.CreateImage( (cv.Round(img.shape[0]/scale), cv.Round(img.shape[1]/scale)), cv.CV_8UC1 )
#smallImg = cv.fromarray(np.empty( (cv.Round(img.shape[0]/scale), cv.Round(img.shape[1]/scale)), dtype=np.uint8 ))
smallImg = np.empty( (cv.Round(img.shape[1]/scale), cv.Round(img.shape[0]/scale)), dtype=np.uint8 )
#cv.CvtColor( image, gray, cv.CV_BGR2GRAY )
gray = cv2.cvtColor( img, cv.CV_BGR2GRAY )
#cv.Resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR )
smallImg = cv2.resize( gray, smallImg.shape, interpolation=cv2.INTER_LINEAR )
#cv.EqualizeHist( smallImg, smallImg )
smallImg = cv2.equalizeHist( smallImg )
t = cv.GetTickCount()
faces = list(cascade.detectMultiScale( smallImg,
1.1, 2, 0
#|cv.CV_HAAR_FIND_BIGGEST_OBJECT
#|cv.CV_HAAR_DO_ROUGH_SEARCH
|cv.CV_HAAR_SCALE_IMAGE,
(30, 30) ))
#faces = cv.HaarDetectObjects(grayscale, cascade, storage, 1.2, 2,
# cv.CV_HAAR_DO_CANNY_PRUNING, (50,50))
facesprofil = list(cascadeprofil.detectMultiScale( smallImg,
1.1, 2, 0
#|cv.CV_HAAR_FIND_BIGGEST_OBJECT
#|cv.CV_HAAR_DO_ROUGH_SEARCH
|cv.CV_HAAR_SCALE_IMAGE,
(30, 30) ))
#faces = self._util_merge_Regions(faces + facesprofil)[0]
faces = self._util_merge_Regions(faces + facesprofil, overlap=True)[0]
faces = np.array(faces)
#if faces:
# self._drawRect(faces) #call to a python pil
t = cv.GetTickCount() - t
#print( "detection time = %g ms\n" % (t/(cv.GetTickFrequency()*1000.)) )
#colors = [ (0,0,255),
# (0,128,255),
# (0,255,255),
# (0,255,0),
# (255,128,0),
# (255,255,0),
# (255,0,0),
# (255,0,255) ]
result = []
for i, r in enumerate(faces):
#color = colors[i%8]
(rx, ry, rwidth, rheight) = r
#cx = cv.Round((rx + rwidth*0.5)*scale)
#cy = cv.Round((ry + rheight*0.5)*scale)
#radius = cv.Round((rwidth + rheight)*0.25*scale)
#cv2.circle( img, (cx, cy), radius, color, 3, 8, 0 )
#if nestedCascade.empty():
# continue
# Wilson, Fernandez: FACIAL FEATURE DETECTION USING HAAR CLASSIFIERS
# http://nichol.as/papers/Wilson/Facial%20feature%20detection%20using%20Haar.pdf
#dx, dy = cv.Round(rwidth*0.5), cv.Round(rheight*0.5)
dx, dy = cv.Round(rwidth/8.), cv.Round(rheight/8.)
(rx, ry, rwidth, rheight) = (max([rx-dx,0]), max([ry-dy,0]), min([rwidth+2*dx,img.shape[1]]), min([rheight+2*dy,img.shape[0]]))
#smallImgROI = smallImg
#print r, (rx, ry, rwidth, rheight)
#smallImgROI = smallImg[ry:(ry+rheight),rx:(rx+rwidth)]
smallImgROI = smallImg[ry:(ry+6*dy),rx:(rx+rwidth)] # speed up by setting instead of extracting ROI
nestedObjects = nestedCascade.detectMultiScale( smallImgROI,
1.1, 2, 0
#|CV_HAAR_FIND_BIGGEST_OBJECT
#|CV_HAAR_DO_ROUGH_SEARCH
#|CV_HAAR_DO_CANNY_PRUNING
|cv.CV_HAAR_SCALE_IMAGE,
(30, 30) )
nestedObjects = self._util_merge_Regions(list(nestedObjects), overlap=True)[0]
if len(nestedObjects) < 2:
nestedLeftEye = cascadelefteye.detectMultiScale( smallImgROI,
1.1, 2, 0
#|CV_HAAR_FIND_BIGGEST_OBJECT
#|CV_HAAR_DO_ROUGH_SEARCH
#|CV_HAAR_DO_CANNY_PRUNING
|cv.CV_HAAR_SCALE_IMAGE,
(30, 30) )
nestedRightEye = cascaderighteye.detectMultiScale( smallImgROI,
1.1, 2, 0
#|CV_HAAR_FIND_BIGGEST_OBJECT
#|CV_HAAR_DO_ROUGH_SEARCH
#|CV_HAAR_DO_CANNY_PRUNING
|cv.CV_HAAR_SCALE_IMAGE,
(30, 30) )
nestedObjects = self._util_merge_Regions(list(nestedObjects) +
list(nestedLeftEye) +
list(nestedRightEye), overlap=True)[0]
#if len(nestedObjects) > 2:
# nestedObjects = self._util_merge_Regions(list(nestedObjects), close=True)[0]
smallImgROI = smallImg[(ry+4*dy):(ry+rheight),rx:(rx+rwidth)]
nestedMouth = cascademouth.detectMultiScale( smallImgROI,
1.1, 2, 0
|cv.CV_HAAR_FIND_BIGGEST_OBJECT
|cv.CV_HAAR_DO_ROUGH_SEARCH
#|CV_HAAR_DO_CANNY_PRUNING
|cv.CV_HAAR_SCALE_IMAGE,
(30, 30) )
smallImgROI = smallImg[(ry+(5*dy)/2):(ry+5*dy+(5*dy)/2),(rx+(5*dx)/2):(rx+5*dx+(5*dx)/2)]
nestedNose = cascadenose.detectMultiScale( smallImgROI,
1.1, 2, 0
|cv.CV_HAAR_FIND_BIGGEST_OBJECT
|cv.CV_HAAR_DO_ROUGH_SEARCH
#|CV_HAAR_DO_CANNY_PRUNING
|cv.CV_HAAR_SCALE_IMAGE,
(30, 30) )
smallImgROI = smallImg[(ry+2*dy):(ry+6*dy),rx:(rx+rwidth)]
nestedEars = list(cascadeleftear.detectMultiScale( smallImgROI,
1.1, 2, 0
|cv.CV_HAAR_FIND_BIGGEST_OBJECT
|cv.CV_HAAR_DO_ROUGH_SEARCH
#|CV_HAAR_DO_CANNY_PRUNING
|cv.CV_HAAR_SCALE_IMAGE,
(30, 30) ))
nestedEars += list(cascaderightear.detectMultiScale( smallImgROI,
1.1, 2, 0
|cv.CV_HAAR_FIND_BIGGEST_OBJECT
|cv.CV_HAAR_DO_ROUGH_SEARCH
#|CV_HAAR_DO_CANNY_PRUNING
|cv.CV_HAAR_SCALE_IMAGE,
(30, 30) ))
data = { 'ID': (i+1),
'Position': tuple(np.int_(r*scale)),
'Type': u'-',
'Eyes': [],
'Mouth': (),
'Nose': (),
'Ears': [], }
data['Coverage'] = float(data['Position'][2]*data['Position'][3])/(self.image_size[0]*self.image_size[1])
#if (c >= confidence):
# eyes = nestedObjects
# if not (type(eyes) == type(tuple())):
# eyes = tuple((eyes*scale).tolist())
# result.append( {'Position': r*scale, 'eyes': eyes, 'confidence': c} )
#print {'Position': r, 'eyes': nestedObjects, 'confidence': c}
for nr in nestedObjects:
(nrx, nry, nrwidth, nrheight) = nr
cx = cv.Round((rx + nrx + nrwidth*0.5)*scale)
cy = cv.Round((ry + nry + nrheight*0.5)*scale)
radius = cv.Round((nrwidth + nrheight)*0.25*scale)
#cv2.circle( img, (cx, cy), radius, color, 3, 8, 0 )
data['Eyes'].append( (cx-radius, cy-radius, 2*radius, 2*radius) )
if len(nestedMouth):
(nrx, nry, nrwidth, nrheight) = nestedMouth[0]
cx = cv.Round((rx + nrx + nrwidth*0.5)*scale)
cy = cv.Round(((ry+4*dy) + nry + nrheight*0.5)*scale)
radius = cv.Round((nrwidth + nrheight)*0.25*scale)
#cv2.circle( img, (cx, cy), radius, color, 3, 8, 0 )
data['Mouth'] = (cx-radius, cy-radius, 2*radius, 2*radius)
if len(nestedNose):
(nrx, nry, nrwidth, nrheight) = nestedNose[0]
cx = cv.Round(((rx+(5*dx)/2) + nrx + nrwidth*0.5)*scale)
cy = cv.Round(((ry+(5*dy)/2) + nry + nrheight*0.5)*scale)
radius = cv.Round((nrwidth + nrheight)*0.25*scale)
#cv2.circle( img, (cx, cy), radius, color, 3, 8, 0 )
data['Nose'] = (cx-radius, cy-radius, 2*radius, 2*radius)
for nr in nestedEars:
(nrx, nry, nrwidth, nrheight) = nr
cx = cv.Round((rx + nrx + nrwidth*0.5)*scale)
cy = cv.Round((ry + nry + nrheight*0.5)*scale)
radius = cv.Round((nrwidth + nrheight)*0.25*scale)
#cv2.circle( img, (cx, cy), radius, color, 3, 8, 0 )
data['Ears'].append( (cx-radius, cy-radius, 2*radius, 2*radius) )
result.append( data )
## see '_drawRect'
#if result:
# #image_path_new = os.path.join(scriptdir, 'cache/0_DETECTED_' + self.image_filename)
# image_path_new = self.image_path_JPEG.replace(u"cache/", u"cache/0_DETECTED_")
# cv2.imwrite( image_path_new, img )
#return faces.tolist()
self._info['Faces'] += result
return
# https://pypi.python.org/pypi/xbob.flandmark
# http://cmp.felk.cvut.cz/~uricamic/flandmark/
def _detect_FaceLandmark_xBOB(self):
"""Prints the locations of any face landmark(s) found, respective
converts them to usual face position data"""
#self._info['Faces'] = []
scale = 1.
try:
#video = bob.io.VideoReader(self.image_path_JPEG.encode('utf-8'))
video = [cv2.imread( self.image_path_JPEG, cv.CV_LOAD_IMAGE_COLOR )]
#if img == None:
# raise IOError
# !!! the 'scale' here IS RELEVANT FOR THE DETECTION RATE;
# how small and how many features are detected as faces (or eyes)
scale = max([1., np.average(np.array(video[0].shape)[0:2]/750.)])
except IOError:
pywikibot.warning(u'unknown file type [_detect_FaceLandmark_xBOB]')
return
except AttributeError:
pywikibot.warning(u'unknown file type [_detect_FaceLandmark_xBOB]')
return
smallImg = np.empty( (cv.Round(video[0].shape[1]/scale), cv.Round(video[0].shape[0]/scale)), dtype=np.uint8 )
video = [ cv2.resize( img, smallImg.shape, interpolation=cv2.INTER_LINEAR ) for img in video ]
sys.path.append(os.path.join(scriptdir, 'dtbext'))
import _bob as bob
import xbob_flandmark as xbob
localize = xbob.flandmark.Localizer()
result = []
for frame in video: # currently ALWAYS contains ONE (1!) entry
frame = np.transpose(frame, (2,0,1))
img = np.transpose(frame, (1,2,0))
for i, flm in enumerate(localize(frame)):
#for pi, point in enumerate(flm['landmark']):
# cv2.circle(img, tuple(map(int, point)), 3, ( 0, 0, 255))
# cv2.circle(img, tuple(map(int, point)), 5, ( 0, 255, 0))
# cv2.circle(img, tuple(map(int, point)), 7, (255, 0, 0))
# cv2.putText(img, str(pi), tuple(map(int, point)), cv2.FONT_HERSHEY_PLAIN, 1.0, (0,255,0))
#cv2.rectangle(img, tuple(map(int, flm['bbox'][:2])), tuple(map(int, (flm['bbox'][0]+flm['bbox'][2], flm['bbox'][1]+flm['bbox'][3]))), (0, 255, 0))
mat = np.array([flm['landmark'][3], flm['landmark'][4]])
mi = np.min(mat, axis=0)
mouth = tuple(mi.astype(int)) + tuple((np.max(mat, axis=0)-mi).astype(int))
#cv2.rectangle(img, tuple(mi.astype(int)), tuple(np.max(mat, axis=0).astype(int)), (0, 255, 0))
mat = np.array([flm['landmark'][5], flm['landmark'][1]])
mi = np.min(mat, axis=0)
leye = tuple(mi.astype(int)) + tuple((np.max(mat, axis=0)-mi).astype(int))
#cv2.rectangle(img, tuple(mi.astype(int)), tuple(np.max(mat, axis=0).astype(int)), (0, 255, 0))
mat = np.array([flm['landmark'][2], flm['landmark'][6]])
mi = np.min(mat, axis=0)
reye = tuple(mi.astype(int)) + tuple((np.max(mat, axis=0)-mi).astype(int))
#cv2.rectangle(img, tuple(mi.astype(int)), tuple(np.max(mat, axis=0).astype(int)), (0, 255, 0))
data = { 'ID': (i+1),
'Position': flm['bbox'],
'Type': u'Landmark',
'Eyes': [leye, reye],
'Mouth': mouth,
'Nose': tuple(np.array(flm['landmark'][7]).astype(int)) + (0, 0),
'Ears': [],
'Landmark': [tuple(lm) for lm in np.array(flm['landmark']).astype(int)], }
data['Coverage'] = float(data['Position'][2]*data['Position'][3])/(self.image_size[0]*self.image_size[1])
result.append(data)
#img = img.astype('uint8')
#cv2.imshow("people detector", img)
#cv2.waitKey()
self._info['Faces'] += result
return
# .../opencv/samples/cpp/peopledetect.cpp
# + Haar/Cascade detection
def _detect_People_CV(self):
# http://stackoverflow.com/questions/10231380/graphic-recognition-of-people
# https://code.ros.org/trac/opencv/ticket/1298
# http://opencv.itseez.com/modules/gpu/doc/object_detection.html
# http://opencv.willowgarage.com/documentation/cpp/basic_structures.html
# http://www.pygtk.org/docs/pygtk/class-gdkrectangle.html
self._info['People'] = []
scale = 1.
try:
img = cv2.imread(self.image_path_JPEG, cv.CV_LOAD_IMAGE_COLOR)
if (img == None) or (min(img.shape[:2]) < 100) or (not img.data) \
or (self.image_size[0] is None):
return
# !!! the 'scale' here IS RELEVANT FOR THE DETECTION RATE;
# how small and how many features are detected
#scale = max([1., np.average(np.array(img.shape)[0:2]/500.)])
scale = max([1., np.average(np.array(img.shape)[0:2]/400.)])
#scale = max([1., np.average(np.array(img.shape)[0:2]/300.)])
except IOError:
pywikibot.warning(u'unknown file type [_detect_People_CV]')
return
except AttributeError:
pywikibot.warning(u'unknown file type [_detect_People_CV]')
return
# similar to face detection
smallImg = np.empty( (cv.Round(img.shape[1]/scale), cv.Round(img.shape[0]/scale)), dtype=np.uint8 )
#gray = cv2.cvtColor( img, cv.CV_BGR2GRAY )
gray = img
smallImg = cv2.resize( gray, smallImg.shape, interpolation=cv2.INTER_LINEAR )
#smallImg = cv2.equalizeHist( smallImg )
img = smallImg
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
#cv2.namedWindow("people detector", 1)
found = found_filtered = []
#t = time.time()
# run the detector with default parameters. to get a higher hit-rate
# (and more false alarms, respectively), decrease the hitThreshold and
# groupThreshold (set groupThreshold to 0 to turn off the grouping completely).
# detectMultiScale(img, hit_threshold=0, win_stride=Size(),
# padding=Size(), scale0=1.05, group_threshold=2)
enable_recovery() # enable recovery from hard crash
found = list(hog.detectMultiScale(img, 0.25, (8,8), (32,32), 1.05, 2))
disable_recovery() # disable since everything worked out fine
# people haar/cascaded classifier
# use 'haarcascade_fullbody.xml', ... also (like face detection)
xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_fullbody.xml')
#xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_lowerbody.xml')
#xml = os.path.join(scriptdir, 'externals/opencv/haarcascades/haarcascade_upperbody.xml')
if not os.path.exists(xml):
raise IOError(u"No such file: '%s'" % xml)
cascade = cv2.CascadeClassifier(xml)
objects = list(cascade.detectMultiScale( smallImg,
1.1, 3, 0
#|cv.CV_HAAR_FIND_BIGGEST_OBJECT
#|cv.CV_HAAR_DO_ROUGH_SEARCH
|cv.CV_HAAR_SCALE_IMAGE,
(30, 30) ))
found += objects
#t = time.time() - t
#print("tdetection time = %gms\n", t*1000.)
bbox = gtk.gdk.Rectangle(*(0,0,img.shape[1],img.shape[0]))
# exclude duplicates (see also in 'classifyFeatures()')
found_filtered = [gtk.gdk.Rectangle(*f) for f in self._util_merge_Regions(found, sub=True)[0]]
result = []
for i in range(len(found_filtered)):
r = found_filtered[i]
# the HOG detector returns slightly larger rectangles than the real objects.
# so we slightly shrink the rectangles to get a nicer output.
r.x += cv.Round(r.width*0.1)
r.width = cv.Round(r.width*0.8)
r.y += cv.Round(r.height*0.07)
r.height = cv.Round(r.height*0.8)
data = { 'ID': (i+1), }
#'Center': (int(r.x + r.width*0.5), int(r.y + r.height*0.5)), }
# crop to image size (because of the slightly bigger boxes)
r = bbox.intersect(r)
#cv2.rectangle(img, (r.x, r.y), (r.x+r.width, r.y+r.height), cv.Scalar(0,255,0), 3)
data['Position'] = tuple(np.int_(np.array(r)*scale))
data['Coverage'] = float(data['Position'][2]*data['Position'][3])/(self.image_size[0]*self.image_size[1])
result.append( data )
#cv2.imshow("people detector", img)
#c = cv2.waitKey(0) & 255
self._info['People'] = result
return
def _detect_Geometry_CV(self):
self._info['Geometry'] = []
# skip file formats not supported (yet?)
if (self.image_mime[1] in ['ogg', 'pdf', 'vnd.djvu']):
return
result = self._util_get_Geometry_CVnSCIPY()
self._info['Geometry'] = [{'Lines': result['Lines'],
'Circles': result['Circles'],
'Corners': result['Corners'],}]
return
# https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/python/houghlines.py?rev=2770
def _util_get_Geometry_CVnSCIPY(self):
# http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#cornerharris
# http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#houghcircles
# http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#houghlines
# http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#houghlinesp
if hasattr(self, '_buffer_Geometry'):
return self._buffer_Geometry
self._buffer_Geometry = {'Lines': '-', 'Circles': '-', 'Edge_Ratio': '-', 'Corners': '-',
'FFT_Peaks': '-'}
scale = 1.
try:
img = cv2.imread(self.image_path_JPEG, cv.CV_LOAD_IMAGE_COLOR)
if (img == None):
raise IOError
# !!! the 'scale' here IS RELEVANT FOR THE DETECTION RATE;
# how small and how many features are detected
scale = max([1., np.average(np.array(img.shape)[0:2]/500.)])
except IOError:
pywikibot.warning(u'unknown file type [_detect_Geometry_CV]')
return self._buffer_Geometry
except AttributeError:
pywikibot.warning(u'unknown file type [_detect_Geometry_CV]')
return self._buffer_Geometry
# similar to face or people detection
smallImg = np.empty( (cv.Round(img.shape[1]/scale), cv.Round(img.shape[0]/scale)), dtype=np.uint8 )
_gray = cv2.cvtColor( img, cv.CV_BGR2GRAY )
# smooth it, otherwise a lot of false circles may be detected
#gray = cv2.GaussianBlur( _gray, (9, 9), 2 )
gray = cv2.GaussianBlur( _gray, (5, 5), 2 )
smallImg = cv2.resize( gray, smallImg.shape, interpolation=cv2.INTER_LINEAR )
#smallImg = cv2.equalizeHist( smallImg )
src = smallImg
# https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/python/houghlines.py?rev=2770
#dst = cv2.Canny(src, 50, 200)
dst = cv2.Canny(src, 10, 10)
edges = cv2.Canny(src, 10, 10)
#color_dst = cv2.cvtColor(dst, cv.CV_GRAY2BGR)
# edges (in this sensitve form a meassure for color gradients)
data = {}
data['Edge_Ratio'] = float((edges != 0).sum())/(edges.shape[0]*edges.shape[1])
# lines
USE_STANDARD = True
if USE_STANDARD:
#lines = cv.HoughLines2(dst, storage, cv.CV_HOUGH_STANDARD, 1, pi / 180, 100, 0, 0)
#lines = cv2.HoughLines(dst, 1, math.pi / 180, 100)
lines = cv2.HoughLines(dst, 1, math.pi / 180, 200)
if (lines is not None) and len(lines):
lines = lines[0]
data['Lines'] = len(lines)
#for (rho, theta) in lines[:100]:
# a = math.cos(theta)
# b = math.sin(theta)
# x0 = a * rho
# y0 = b * rho
# pt1 = (cv.Round(x0 + 1000*(-b)), cv.Round(y0 + 1000*(a)))
# pt2 = (cv.Round(x0 - 1000*(-b)), cv.Round(y0 - 1000*(a)))
# cv2.line(color_dst, pt1, pt2, cv.RGB(255, 0, 0), 3, 8)
else:
#lines = cv.HoughLines2(dst, storage, cv.CV_HOUGH_PROBABILISTIC, 1, pi / 180, 50, 50, 10)
lines = cv2.HoughLinesP(dst, 1, math.pi / 180, 100)
#for line in lines:
# cv2.line(color_dst, line[0], line[1], cv.CV_RGB(255, 0, 0), 3, 8)
# circles
try:
#circles = cv2.HoughCircles(src, cv.CV_HOUGH_GRADIENT, 2, src.shape[0]/4)#, 200, 100 )
circles = cv2.HoughCircles(src, cv.CV_HOUGH_GRADIENT, 2, src.shape[0]/4, param2=200)
except cv2.error:
circles = None
if (circles is not None) and len(circles):
circles = circles[0]
data['Circles'] = len(circles)
#for c in circles:
# center = (cv.Round(c[0]), cv.Round(c[1]))
# radius = cv.Round(c[2])
# # draw the circle center
# cv2.circle( color_dst, center, 3, cv.CV_RGB(0,255,0), -1, 8, 0 )
# # draw the circle outline
# cv2.circle( color_dst, center, radius, cv.CV_RGB(0,0,255), 3, 8, 0 )
# corners
corner_dst = cv2.cornerHarris( edges, 2, 3, 0.04 )
# Normalizing
cv2.normalize( corner_dst, corner_dst, 0, 255, cv2.NORM_MINMAX, cv.CV_32FC1 )
#dst_norm_scaled = cv2.convertScaleAbs( corner_dst )
# Drawing a circle around corners
corner = []
for j in range(corner_dst.shape[0]):
for i in range(corner_dst.shape[1]):
if corner_dst[j,i] > 200:
#circle( dst_norm_scaled, Point( i, j ), 5, Scalar(0), 2, 8, 0 );
corner.append( (j,i) )
data['Corners'] = len(corner)
#cv2.imshow("people detector", color_dst)
#c = cv2.waitKey(0) & 255
# fft spectral/frequency/momentum analysis with svd peak detection
gray = cv2.resize( _gray, smallImg.shape, interpolation=cv2.INTER_LINEAR )
##s = (self.image_size[1], self.image_size[0])
#s = gray.shape
fft = fftpack.fftn(gray)
#fft = np.fft.fftn(gray)
#Image.fromarray(fft.real).show()
# shift quadrants so that low spatial frequencies are in the center
fft = fftpack.fftshift(fft)
#Image.fromarray(fft.real).show()
##Image.fromarray(fftpack.ifftn(fft).real).show()
##Image.fromarray(fftpack.ifftn(fftpack.ifftshift(fft)).real).show()
##Image.fromarray(fftpack.ifftn(fftpack.ifftshift(fft.real)).real).show()
try:
U, S, Vh = linalg.svd(np.matrix(fft))
ma = 0.01*max(S)
count = sum([int(c > ma) for c in S])
#SS = np.zeros(s)
#ss = min(s)
#for i in range(0, len(S)-1, max( int(len(S)/100.), 1 )): # (len(S)==ss) -> else; problem!
# #SS = np.zeros(s)
# #SS[:(ss-i),:(ss-i)] = np.diag(S[:(ss-i)])
# SS[:(i+1),:(i+1)] = np.diag(S[:(i+1)])
# #Image.fromarray((np.dot(np.dot(U, SS), Vh) - fft).real).show()
# #Image.fromarray(fftpack.ifftn(fftpack.ifftshift(np.dot(np.dot(U, SS), Vh))).real - gray).show()
# print i, ((np.dot(np.dot(U, SS), Vh) - fft).real).max()
# print i, (fftpack.ifftn(fftpack.ifftshift(np.dot(np.dot(U, SS), Vh))).real - gray).max()
# #if ((np.dot(np.dot(U, SS), Vh) - fft).max() < (255/4.)):
# # break
#data['SVD_Comp'] = float(i)/ss
#data['SVD_Min'] = S[:(i+1)].min()
data['FFT_Peaks'] = float(count)/len(S)
#pywikibot.output( u'FFT_Peaks: %s' % data['FFT_Peaks'] )
except linalg.LinAlgError:
# SVD did not converge; in fact this should NEVER happen...(?!?)
pass
# use wavelet transformation (FWT) from e.g. pywt, scipy signal or mlpy
# (may be other) in addition to FFT and compare the spectra with FFT...
# confer; "A Practical Guide to Wavelet Analysis" (http://journals.ametsoc.org/doi/pdf/10.1175/1520-0477%281998%29079%3C0061%3AAPGTWA%3E2.0.CO%3B2)
# on how to convert and adopt FFT and wavlet spectra frequency scales
if data:
self._buffer_Geometry.update(data)
return self._buffer_Geometry
# .../opencv/samples/cpp/bagofwords_classification.cpp
def _detectclassify_ObjectAll_CV(self):
"""Uses the 'The Bag of Words model' for detection and classification"""
# CAN ALSO BE USED FOR: TEXT, ...
# http://app-solut.com/blog/2011/07/the-bag-of-words-model-in-opencv-2-2/
# http://app-solut.com/blog/2011/07/using-the-normal-bayes-classifier-for-image-categorization-in-opencv/
# http://authors.library.caltech.edu/7694/
# http://www.vision.caltech.edu/Image_Datasets/Caltech256/
# http://opencv.itseez.com/modules/features2d/doc/object_categorization.html
# http://www.morethantechnical.com/2011/08/25/a-simple-object-classifier-with-bag-of-words-using-opencv-2-3-w-code/
# source: https://github.com/royshil/FoodcamClassifier
# http://app-solut.com/blog/2011/07/using-the-normal-bayes-classifier-for-image-categorization-in-opencv/
# source: http://code.google.com/p/open-cv-bow-demo/downloads/detail?name=bowdemo.tar.gz&can=2&q=
# parts of code here should/have to be placed into e.g. a own
# class in 'dtbext/opencv/__init__.py' script/module
self._info['Classify'] = []
trained = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',
'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
'horse', 'motorbike', 'person', 'pottedplant', 'sheep',
'sofa', 'train', 'tvmonitor',]
bowDescPath = os.path.join(scriptdir, 'dtbext/opencv/data/bowImageDescriptors/000000.xml.gz')
# https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/cpp/bagofwords_classification.cpp?rev=3714
# stand-alone (in shell) for training e.g. with:
# BoWclassify /data/toolserver/pywikipedia/dtbext/opencv/VOC2007 /data/toolserver/pywikipedia/dtbext/opencv/data FAST SURF BruteForce | tee run.log
# BoWclassify /data/toolserver/pywikipedia/dtbext/opencv/VOC2007 /data/toolserver/pywikipedia/dtbext/opencv/data HARRIS SIFT BruteForce | tee run.log
# http://experienceopencv.blogspot.com/2011/02/object-recognition-bag-of-keypoints.html
sys.path.append(os.path.join(scriptdir, 'dtbext'))
import opencv
if os.path.exists(bowDescPath):
os.remove(bowDescPath)
stdout = sys.stdout
sys.stdout = StringIO.StringIO()
#result = opencv.BoWclassify.main(0, '', '', '', '', '')
result = opencv.BoWclassify.main(6,
os.path.join(scriptdir, 'dtbext/opencv/VOC2007'),
os.path.join(scriptdir, 'dtbext/opencv/data'),
'HARRIS', # not important; given by training
'SIFT', # not important; given by training
'BruteForce', # not important; given by training
[str(os.path.abspath(self.image_path).encode('latin-1'))])
#out = sys.stdout.getvalue()
sys.stdout = stdout
#print out
if not result:
raise ImportError("BoW did not resolve; no results found!")
os.remove(bowDescPath)
# now make the algo working; confer also
# http://www.xrce.xerox.com/layout/set/print/content/download/18763/134049/file/2004_010.pdf
# http://people.csail.mit.edu/torralba/shortCourseRLOC/index.html
self._info['Classify'] = [dict([ (trained[i], r) for i, r in enumerate(result) ])]
return
def _detectclassify_ObjectAll_PYWT(self):
"""Uses the 'Fast Wavelet-Based Visual Classification' for detection
and classification"""
# Fast Wavelet-Based Visual Classification
# http://www.cmap.polytechnique.fr/~yu/publications/ICPR08Final.pdf
# CAN ALSO BE USED FOR: TEXT, AUDIO, (VIDEO), ...
# TODO: for audio and video (time-based) also...!!!
import pywt # python-pywt
# TODO: improve (honestly; truly apply) wavelet in a meaningful and USEFUL (correct) way/manner!
# TODO: truly apply FFT and SVD (used before)
# wavelet transformation
# https://github.com/nigma/pywt/tree/master/demo
# image_blender, dwt_signal_decomposition.py, wp_scalogram.py, dwt_multidim.py, user_filter_banks.py:
#coeffs = pywt.dwtn(gray, 'db1') # Single-level n-dimensional Discrete Wavelet Transform
coeffs = pywt.dwt2(gray, 'db1') # 2D Discrete Wavelet Transform
#coeffs = pywt.wavedec2(gray, 'db1') # Multilevel 2D Discrete Wavelet Transform
pass
result = pywt.idwt2(coeffs, 'db1') # 2D Inverse Discrete Wavelet Transform
#result = pywt.waverec2(coeffs, 'db1') # Multilevel 2D Inverse Discrete Wavelet Transform
result = result[:gray.shape[0],:gray.shape[1]]
# consider 'swt' (2D Stationary Wavelet Transform) instead of 'dwt' too
pywikibot.output(u'%s' % coeffs)
pywikibot.output(u'%s' % np.abs(result - gray).max())
#data['Wavelet_Comp'] = coeffs
# https://github.com/nigma/pywt/blob/master/demo/image_blender.py
# http://www.ncbi.nlm.nih.gov/pubmed/18713675
# https://github.com/nigma/pywt/blob/master/demo/wp_scalogram.py
# https://github.com/nigma/pywt/blob/master/demo/swt2.py
return
# a lot more paper and possible algos exist; (those with code are...)
# http://www.lix.polytechnique.fr/~schwander/python-srm/
# http://library.wolfram.com/infocenter/Demos/5725/#downloads
# http://code.google.com/p/pymeanshift/wiki/Examples
# (http://pythonvision.org/basic-tutorial, http://luispedro.org/software/mahotas, http://packages.python.org/pymorph/)
def _detect_SegmentColors_JSEGnPIL(self): # may be SLIC other other too...
self._info['ColorRegions'] = []
# skip file formats not supported (yet?)
if (self.image_mime[1] in ['ogg', 'pdf', 'vnd.djvu']):
return
try:
#im = Image.open(self.image_path).convert(mode = 'RGB')
im = Image.open(self.image_path_JPEG)
## crop 25% of the image in order to give the bot a more human eye
## (needed for categorization only and thus should be done there/later)
#scale = 0.75 # crop 25% percent (area) bounding box
#(w, h) = ( self.image_size[0]*math.sqrt(scale), self.image_size[1]*math.sqrt(scale) )
#(l, t) = ( (self.image_size[0]-w)/2, (self.image_size[1]-h)/2 )
#i = im.crop( (int(l), int(t), int(l+w), int(t+h)) )
(l, t) = (0, 0)
i = im
except IOError:
pywikibot.warning(u'unknown file type [_detect_SegmentColors_JSEGnPIL]')
return
result = []
try:
#h = i.histogram() # average over WHOLE IMAGE
(pic, scale) = self._util_detect_ColorSegments_JSEG(i) # split image into segments first
#(pic, scale) = self._util_detect_ColorSegments_SLIC(i) # split image into superpixel first
hist = self._util_get_ColorSegmentsHist_PIL(i, pic, scale) #
#pic = self._util_merge_ColorSegments(pic, hist) # iteratively in order to MERGE similar regions
#(pic, scale_) = self._util_detect_ColorSegments_JSEG(pic) # (final split)
##(pic, scale) = self._util_detect_ColorSegments_JSEG(pic) # (final split)
#hist = self._util_get_ColorSegmentsHist_PIL(i, pic, scale) #
except TypeError:
pywikibot.warning(u'unknown file type [_detect_SegmentColors_JSEGnPIL]')
return
i = 0
# (may be do an additional region merge according to same color names...)
for (h, coverage, (center, bbox)) in hist:
if (coverage < 0.05): # at least 5% coverage needed (help for debugging/log_output)
continue
data = self._util_average_Color_colormath(h)
data['Coverage'] = float(coverage)
data['ID'] = (i+1)
data['Center'] = (int(center[0]+l), int(center[1]+t))
data['Position'] = (int(bbox[0]+l), int(bbox[1]+t), int(bbox[2]), int(bbox[3]))
data['Delta_R'] = math.sqrt( (self.image_size[0]/2 - center[0])**2 + \
(self.image_size[1]/2 - center[1])**2 )
result.append( data )
i += 1
self._info['ColorRegions'] = result
return
# http://stackoverflow.com/questions/2270874/image-color-detection-using-python
# https://gist.github.com/1246268
# colormath-1.0.8/examples/delta_e.py, colormath-1.0.8/examples/conversions.py
# http://code.google.com/p/python-colormath/
# http://en.wikipedia.org/wiki/Color_difference
# http://www.farb-tabelle.de/en/table-of-color.htm
def _detect_AverageColor_PILnCV(self):
self._info['ColorAverage'] = []
# skip file formats not supported (yet?)
if (self.image_mime[1] in ['ogg', 'pdf', 'vnd.djvu']):
return
try:
# we need to have 3 channels (but e.g. grayscale 'P' has only 1)
#i = Image.open(self.image_path).convert(mode = 'RGB')
i = Image.open(self.image_path_JPEG)
h = i.histogram()
except IOError:
pywikibot.warning(u'unknown file type [_detect_AverageColor_PILnCV]')
return
result = self._util_average_Color_colormath(h)
result['Gradient'] = self._util_get_Geometry_CVnSCIPY().get('Edge_Ratio', None) or '-'
result['FFT_Peaks'] = self._util_get_Geometry_CVnSCIPY().get('FFT_Peaks', None) or '-'
self._info['ColorAverage'] = [result]
return
def _detect_Properties_PIL(self):
"""Retrieve as much file property info possible, especially the same
as commons does in order to compare if those libraries (ImageMagick,
...) are buggy (thus explicitely use other software for independence)"""
#self.image_size = (None, None)
self._info['Properties'] = [{'Format': u'-', 'Pages': 0}]
if self.image_fileext == u'.svg': # MIME: 'application/xml; charset=utf-8'
# similar to PDF page count OR use BeautifulSoup
svgcountpages = re.compile("<page>")
pc = len(svgcountpages.findall( file(self.image_path,"r").read() ))
#svg = rsvg.Handle(self.image_path)
# http://validator.w3.org/docs/api.html#libs
# http://pypi.python.org/pypi/py_w3c/
vld = HTMLValidator()
valid = u'SVG'
try:
vld.validate(self.image.fileUrl())
valid = (u'Valid SVG' if vld.result.validity == 'true' else u'Invalid SVG')
except urllib2.URLError:
pass
except ValidationFault:
pass
#print vld.errors, vld.warnings
#self.image_size = (svg.props.width, svg.props.height)
result = { 'Format': valid,
'Mode': u'-',
'Palette': u'-',
'Pages': pc, }
# may be set {{validSVG}} also or do something in bot template to
# recognize 'Format=SVG (valid)' ...
elif self.image_mime[1] == 'pdf': # MIME: 'application/pdf; charset=binary'
# http://code.activestate.com/recipes/496837-count-pdf-pages/
#rxcountpages = re.compile(r"$\s*/Type\s*/Page[/\s]", re.MULTILINE|re.DOTALL)
rxcountpages = re.compile(r"/Type\s*/Page([^s]|$)", re.MULTILINE|re.DOTALL) # PDF v. 1.3,1.4,1.5,1.6
pc = len(rxcountpages.findall( file(self.image_path,"rb").read() ))
result = { 'Format': u'PDF',
'Mode': u'-',
'Palette': u'-',
'Pages': pc, }
elif (self.image_mime[0] == 'image') and \
(self.image_mime[1] != 'vnd.djvu'): # MIME: 'image/jpeg; charset=binary', ...
try:
i = Image.open(self.image_path)
except IOError:
pywikibot.warning(u'unknown (image) file type [_detect_Properties_PIL]')
return
# http://mail.python.org/pipermail/image-sig/1999-May/000740.html
pc=0 # count number of pages
while True:
try:
i.seek(pc)
except EOFError:
break
pc+=1
i.seek(0) # restore default
# http://grokbase.com/t/python/image-sig/082psaxt6k/embedded-icc-profiles
# python-lcms (littlecms) may be freeimage library
#icc = i.app['APP2'] # jpeg
#icc = i.tag[34675] # tiff
#icc = re.sub('[^%s]'%string.printable, ' ', icc)
## more image formats and more post-processing needed...
#self.image_size = i.size