-
Notifications
You must be signed in to change notification settings - Fork 0
/
catimages.py
4571 lines (3950 loc) · 204 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$'
#
# 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#, 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 _UnknownFile(object):
def __init__(self, file_name, file_mime, *args, **kwargs):
self.file_name = file_name
self.file_mime = file_mime
self.image_size = (None, None)
# available file properties and metadata
self._properties = { 'Properties': [{'Format': u'-', 'Pages': 0}],
'Metadata': [], }
# available feature to extract
self._features = { 'ColorAverage': [],
'ColorRegions': [],
'Faces': [],
'People': [],
'OpticalCodes': [],
'Chessboard': [],
'History': [],
'Text': [],
'Streams': [],
'Audio': [],
'Legs': [],
'Hands': [],
'Torsos': [],
'Ears': [],
'Eyes': [],
'Automobiles': [],
'Classify': [], }
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
pass
def getProperties(self):
self._detect_HeaderAndMetadata() # Metadata
self._detect_Properties() # Properties
return self._properties
def getFeatures(self):
pywikibot.warning(u"File format '%s/%s' not supported (yet)!" % tuple(self.file_mime[:2]))
return self._features
def _detect_HeaderAndMetadata(self):
# check/look into the file by midnight commander (mc)
# use exif as first hint - in fact gives also image-size, streams, ...
exif = self._util_get_DataTags_EXIF()
#print exif
result = { 'Software': exif['Software'] if 'Software' in exif else u'-',
'Output_Extension': exif['Output_extension'] if 'Output_extension' in exif else u'-',
'Desc': exif['Desc'] if 'Desc' in exif else u'-',
'DescProducer': exif['DescProducer'] if 'DescProducer' in exif else u'-',
'DescCreator': exif['DescCreator'] if 'DescCreator' in exif else u'-',
'Comment': exif['Comment'] if 'Comment' in exif else u'-',
'Producer': exif['Producer'] if 'Producer' in exif else u'-',}
#'Comments': exif['Comments'] if 'Comments' in exif else u'-',
#'WorkDesc': exif['WorkDescription'] if 'WorkDescription' in exif else u'-',
##'Dimensions': tuple(map(int, exif['ImageSize'].split(u'x'))),}
#'Dimensions': tuple(exif['ImageSize'].split(u'x')) if 'ImageSize' in exif else (None, None),}
#'Mode': exif['ColorType'], }
# TODO: vvv
#* metadata template in commons has to be worked out and code adopted
#* like in 'Streams' a nice content listing of MIDI (exif or music21 - if needed at all?)
#* docu all this stuff in commons
#* docu and do all open things on "commons TODO list"
#
#
#
#(* initial audio midi support (music21))
#[TODO: docu on Commons ... / template ...]
# TODO: if '_detect_History' is not needed here, moveit back into _JpegFile !!!
#print "self._detect_History()"
#print self._detect_History()
# https://pypi.python.org/pypi/hachoir-metadata (needs 'core' and 'parser')
#
#from hachoir_core.error import HachoirError
#from hachoir_core.stream import InputStreamError
#from hachoir_parser import createParser
#import hachoir_core.config as hachoir_config
#
#from hachoir_metadata import extractMetadata
#
#hachoir_config.debug = True
#hachoir_config.verbose = True
#hachoir_config.quiet = True
#
## Create parser
#try:
# parser = createParser(self.file_name.decode('utf-8'),
# real_filename=self.file_name.encode('utf-8'),
# tags=None)
# #print [val for val in enumerate(parser.createFields())]
# desc = parser.description
# ptags = parser.getParserTags()
#except (InputStreamError, AttributeError):
# desc = u'-'
# ptags = {}
#
## Extract metadata
#try:
# # quality: 0.0 fastest, 1.0 best, and default is 0.5
# metadata = extractMetadata(parser, 0.5)
# #mtags = dict([(key, metadata.getValues(key))
# mtags = dict([(key, metadata.getValues(key)) # get, getItem, getItems, getText
# for key in metadata._Metadata__data.keys()#])
# if metadata.getValues(key)])
#except (HachoirError, AttributeError):
# mtags = {}
#
##result = {'parser_desc': desc, 'parserdata': ptags, 'metadata': mtags}
##print result
#print {'parser_desc': desc, 'parserdata': ptags, 'metadata': mtags}
#
### Display metadatas on stdout
##text = metadata.exportPlaintext(priority=None, human=False)
##if not text:
## text = [u"(no metadata, priority may be too small, try priority=999)"]
##print u'\n'.join(text)
self._properties['Metadata'] = [result]
#print self._properties['Metadata']
return
def _detect_Properties(self):
# get mime-type file-size, ...
pass
def _util_get_DataTags_EXIF(self):
# http://tilloy.net/dev/pyexiv2/tutorial.html
# (is UNFORTUNATELY NOT ABLE to handle all tags, e.g. 'FacesDetected', ...)
if hasattr(self, '_buffer_EXIF'):
return self._buffer_EXIF
res = {}
enable_recovery() # enable recovery from hard crash
try:
if hasattr(pyexiv2, 'ImageMetadata'):
metadata = pyexiv2.ImageMetadata(self.file_name)
metadata.read()
for key in metadata.exif_keys:
res[key] = metadata[key]
for key in metadata.iptc_keys:
res[key] = metadata[key]
for key in metadata.xmp_keys:
res[key] = metadata[key]
else:
image = pyexiv2.Image(self.file_name)
image.readMetadata()
for key in image.exifKeys():
res[key] = image[key]
for key in image.iptcKeys():
res[key] = image[key]
#for key in image.xmpKeys():
# res[key] = image[key]
except IOError:
pass
except RuntimeError:
pass
disable_recovery() # disable since everything worked out fine
# http://www.sno.phy.queensu.ca/~phil/exiftool/
# MIGHT BE BETTER TO USE AS PYTHON MODULE; either by wrapper or perlmodule:
# http://search.cpan.org/~gaas/pyperl-1.0/perlmodule.pod
# (or use C++ with embbedded perl to write a python module)
data = Popen("exiftool -j %s" % self.file_name,
shell=True, stdout=PIPE).stdout.read()
if not data:
raise ImportError("exiftool not found!")
try: # work-a-round for badly encoded exif data (from pywikibot/comms/http.py)
data = unicode(data, 'utf-8', errors = 'strict')
except UnicodeDecodeError:
data = unicode(data, 'utf-8', errors = 'replace')
#res = {}
data = re.sub("(?<!\")\(Binary data (?P<size>\d*) bytes\)", "\"(Binary data \g<size> bytes)\"", data) # work-a-round some issue
for item in json.loads(data):
res.update( item )
#print res
self._buffer_EXIF = res
return self._buffer_EXIF
def _detect_History(self):
res = self._util_get_DataTags_EXIF()
#a = []
#for k in res.keys():
# if 'history' in k.lower():
# a.append( k )
#for item in sorted(a):
# print item
# http://tilloy.net/dev/pyexiv2/api.html#pyexiv2.xmp.XmpTag
#print [getattr(res['Xmp.xmpMM.History'], item) for item in ['key', 'type', 'name', 'title', 'description', 'raw_value', 'value', ]]
result = []
i = 1
while (('Xmp.xmpMM.History[%i]' % i) in res):
data = { 'ID': i,
'Software': u'-',
'Timestamp': u'-',
'Action': u'-',
'Info': u'-', }
if ('Xmp.xmpMM.History[%i]/stEvt:softwareAgent'%i) in res:
data['Software'] = res['Xmp.xmpMM.History[%i]/stEvt:softwareAgent'%i].value
data['Timestamp'] = res['Xmp.xmpMM.History[%i]/stEvt:when'%i].value
data['Action'] = res['Xmp.xmpMM.History[%i]/stEvt:action'%i].value
if ('Xmp.xmpMM.History[%i]/stEvt:changed'%i) in res:
data['Info'] = res['Xmp.xmpMM.History[%i]/stEvt:changed'%i].value
#print res['Xmp.xmpMM.History[%i]/stEvt:instanceID'%i].value
result.append( data )
elif ('Xmp.xmpMM.History[%i]/stEvt:parameters'%i) in res:
data['Action'] = res['Xmp.xmpMM.History[%i]/stEvt:action'%i].value
data['Info'] = res['Xmp.xmpMM.History[%i]/stEvt:parameters'%i].value
#data['Action'] = data['Info'].split(' ')[0]
result.append( data )
else:
pass
i += 1
self._features['History'] = result
return
class _JpegFile(_UnknownFile):
# for '_detect_Trained'
cascade_files = [(u'Legs', 'haarcascade_lowerbody.xml'),
(u'Torsos', 'haarcascade_upperbody.xml'),
(u'Ears', 'haarcascade_mcs_leftear.xml'),
(u'Ears', 'haarcascade_mcs_rightear.xml'),
(u'Eyes', 'haarcascade_lefteye_2splits.xml'), # (http://yushiqi.cn/research/eyedetection)
(u'Eyes', 'haarcascade_righteye_2splits.xml'), # (http://yushiqi.cn/research/eyedetection)
#externals/opencv/haarcascades/haarcascade_mcs_lefteye.xml
#externals/opencv/haarcascades/haarcascade_mcs_righteye.xml
# (others include indifferent (left and/or right) and pair)
(u'Automobiles', 'cars3.xml'), # http://www.youtube.com/watch?v=c4LobbqeKZc
(u'Hands', '1256617233-2-haarcascade-hand.xml', 300.),] # http://www.andol.info/
# ('Hands' does not behave very well, in fact it detects any kind of skin and other things...)
#(u'Aeroplanes', 'haarcascade_aeroplane.xml'),] # e.g. for 'Category:Unidentified aircraft'
def __init__(self, file_name, file_mime, *args, **kwargs):
_UnknownFile.__init__(self, file_name, file_mime)
self.image_filename = os.path.split(self.file_name)[-1]
self.image_path = self.file_name
self.image_path_JPEG = self.image_path + '.jpg'
self._convert()
def __exit__(self, type, value, traceback):
#if os.path.exists(self.image_path):
# os.remove( self.image_path )
if os.path.exists(self.image_path_JPEG):
os.remove( self.image_path_JPEG )
#image_path_new = self.image_path_JPEG.replace(u"cache/", u"cache/0_DETECTED_")
#if os.path.exists(image_path_new):
# os.remove( image_path_new )
def getFeatures(self):
# Faces (extract EXIF data)
self._detect_Faces_EXIF()
# Faces and eyes (opencv pre-trained haar)
self._detect_Faces()
# TODO: test and use or switch off
# Face via Landmark(s)
# self._detect_FaceLandmark_xBOB()
# exclude duplicates (CV and EXIF)
faces = [item['Position'] for item in self._features['Faces']]
for i in self._util_merge_Regions(faces)[1]:
del self._features['Faces'][i]
# Segments and colors
self._detect_SegmentColors()
# Average color
self._detect_AverageColor()
# People/Pedestrian (opencv pre-trained hog and haarcascade)
self._detect_People()
# Geometric object (opencv hough line, circle, edges, corner, ...)
self._detect_Geometry()
# general (opencv pre-trained, third-party and self-trained haar
# and cascade) classification
# http://www.computer-vision-software.com/blog/2009/11/faq-opencv-haartraining/
for cf in self.cascade_files:
self._detect_Trained(*cf)
# barcode and Data Matrix recognition (libdmtx/pydmtx, zbar, gocr?)
self._recognize_OpticalCodes()
# Chessboard (opencv reference detector)
self._detect_Chessboard()
# general (self-trained) detection WITH classification
# BoW: uses feature detection (SIFT, SURF, ...) AND classification (SVM, ...)
# self._detectclassify_ObjectAll()
# Wavelet: uses wavelet transformation AND classification (machine learning)
# self._detectclassify_ObjectAll_PYWT()
# general file EXIF history information
self._detect_History()
return self._features
# supports a lot of different file types thanks to PIL
def _convert(self):
try:
im = Image.open(self.image_path) # might be png, gif etc, for instance
#im.thumbnail(size, Image.ANTIALIAS) # size is 640x480
im.convert('RGB').save(self.image_path_JPEG, "JPEG")
self.image_size = im.size
except IOError, e:
if 'image file is truncated' in str(e):
# im object has changed due to exception raised
im.convert('RGB').save(self.image_path_JPEG, "JPEG")
self.image_size = im.size
else:
try:
# since opencv might still work, try this as fall-back
img = cv2.imread( self.image_path, cv.CV_LOAD_IMAGE_COLOR )
cv2.imwrite(self.image_path_JPEG, img)
self.image_size = (img.shape[1], img.shape[0])
except:
if os.path.exists(self.image_path_JPEG):
os.remove(self.image_path_JPEG)
self.image_path_JPEG = self.image_path
except:
self.image_path_JPEG = self.image_path
# FULL TIFF support (e.g. group4)
# http://code.google.com/p/pylibtiff/
# MIME: 'image/jpeg; charset=binary', ...
def _detect_Properties(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)"""
result = {'Format': u'-', 'Pages': 0}
try:
i = Image.open(self.image_path)
except IOError:
pywikibot.warning(u'unknown file type [_JpegFile]')
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
result.update({ #'bands': i.getbands(),
#'bbox': i.getbbox(),
'Format': i.format,
'Mode': i.mode,
#'info': i.info,
#'stat': os.stat(self.image_path),
'Palette': str(len(i.palette.palette)) if i.palette else u'-',
'Pages': pc,
'Dimensions': self.image_size,
'Filesize': os.path.getsize(self.file_name),
'MIME': u'%s/%s' % tuple(self.file_mime[:2]), })
#self._properties['Properties'] = [result]
self._properties['Properties'][0].update(result)
return
# .../opencv/samples/c/facedetect.cpp
# http://opencv.willowgarage.com/documentation/python/genindex.html
def _detect_Faces(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
# 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)
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]')
return
except AttributeError:
pywikibot.warning(u'unknown file type [_detect_Faces]')
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': [],
'Pose': (), }
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) )
if data['Mouth'] and data['Nose'] and data['Eyes'] and (len(data['Eyes']) == 2):
# head model "little girl" for use in "MeshLab":
# http://www.turbosquid.com/FullPreview/Index.cfm/ID/302581
# http://meshlab.sourceforge.net/
D3points = [[ 70.0602, 109.898, 20.8234], # left eye
[ 2.37427, 110.322, 21.7776], # right eye
[ 36.8301, 78.3185, 52.0345], # nose
[ 36.6391, 51.1675, 38.5903],] # mouth
#[ 119.268, 91.3111, -69.6397], # left ear
#[-49.1328, 91.3111, -67.2481],] # right ear
D2points = [np.array(data['Eyes'][0]), np.array(data['Eyes'][1]),
np.array(data['Nose']), np.array(data['Mouth']),]
D2points = [ item[:2] + item[2:]/2. for item in D2points ]
neutral = np.array([[np.pi],[0.],[0.]])
# calculate pose
rvec, tvec, cm, err = self._util_get_Pose_solvePnP(D3points, D2points, self.image_size)
#data['Pose'] = tuple(rvec[:,0])
check = not (err[:,0,:].max() > 0.5)
if not check:
rvec = neutral # reset to neutral pose
tvec = np.array([[0.],[0.],[100.]]) # reset to neutral position (same order as max of D3points)
pywikibot.warning(u'Could not calculate pose of face, too big errors. '
u'(looks like neutral pose/position is somehow singular)')
## debug: draw pose
##rvec *= 0
#mat, perp = self._util_getD2coords_calc(np.eye(3), cm, rvec, tvec, hacky=False)
## from '_util_drawAxes(...)'
#for i, item in enumerate(mat.transpose()):
# p = tuple((50+10*item).astype(int))[:2]
# cv2.line(img, (50, 50), p, (0., 0., 255.), 1)
# cv2.putText(img, str(i), p, cv2.FONT_HERSHEY_PLAIN, 1., (0., 0., 255.))
#cv2.imshow("win", img)
#cv2.waitKey()
# calculate delta to neutral pose
drv = -cv2.composeRT(-rvec, np.zeros((3,1)),
neutral, np.zeros((3,1)))[0]
rvec = cv2.Rodrigues(cv2.Rodrigues(rvec)[0])[0] # NOT unique!!!
#nrv = cv2.composeRT(neutral, np.zeros((3,1)),
# drv, np.zeros((3,1)))[0]
#print (rvec - nrv < 1E-12) # compare
data['Pose'] = map(float, tuple(drv[:,0]))
# TODO: POSIT has to be tested and compared; draw both results!
# POSIT: http://www.cfar.umd.edu/~daniel/daniel_papersfordownload/Pose25Lines.pdf
if False:
pywikibot.output("solvePnP:")
pywikibot.output(str(rvec[:,0]))
pywikibot.output(str(tvec[:,0]))
pywikibot.output(str(err[:,0,:]))
rvec, tvec, cm, err = self._util_get_Pose_POSIT(D3points, D2points)
pywikibot.output("POSIT:")
pywikibot.output(str(rvec[:,0]))
pywikibot.output(str(tvec))
pywikibot.output(str(np.array(err)[:,0,:]/max(self.image_size)))
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._features['Faces'] += result
return
def _util_get_Pose_solvePnP(self, D3points, D2points, shape):
""" Calculate pose from head model "little girl" w/o camera or other
calibrations needed.
D2points: left eye, right eye, nose, mouth
"""
# howto (credits to "Roy"):
# http://www.youtube.com/watch?v=ZDNH4BT5Do4
# http://www.morethantechnical.com/2010/03/19/quick-and-easy-head-pose-estimation-with-opencv-w-code/
# http://www.morethantechnical.com/2012/10/17/head-pose-estimation-with-opencv-opengl-revisited-w-code/
# e.g. with head model "little girl" for use in "MeshLab":
# http://www.turbosquid.com/FullPreview/Index.cfm/ID/302581
# http://meshlab.sourceforge.net/
# set-up camera matrix (no calibration needed!)
max_d = max(shape)
cameraMatrix = [[max_d, 0, shape[0]/2.0],
[ 0, max_d, shape[1]/2.0],
[ 0, 0, 1.0],]
# calculate pose
rvec, tvec = cv2.solvePnP(np.array(D3points).astype('float32'), np.array(D2points).astype('float32'), np.array(cameraMatrix).astype('float32'), None)
# compare to 2D points
err = []
for i, vec in enumerate(np.array(D3points)):
nvec = np.dot(cameraMatrix, (np.dot(cv2.Rodrigues(rvec)[0], vec) + tvec[:,0]))
err.append(((D2points[i] - nvec[:2]/nvec[2]), D2points[i], nvec[:2]/nvec[2]))
pywikibot.output(u'result for UN-calibrated camera:\n rot=%s' % rvec.transpose()[0])
return rvec, tvec, np.array(cameraMatrix), (np.array(err)/max_d)
#def _util_get_Pose_POSIT(self, D3points, D2points, shape):
def _util_get_Pose_POSIT(self, D3points, D2points):
""" Calculate pose from head model "little girl" w/o camera or other
calibrations needed.
Method similar to '_util_get_Pose_solvePnP', please compare.
D2points: left eye, right eye, nose, mouth
"""
# calculate pose
import opencv
#opencv.unit_test()
(rmat, tvec, mdl) = opencv.posit(D3points, D2points, (100, 1.0e-4))
rvec = cv2.Rodrigues(rmat)[0]
# Project the model points with the estimated pose
# http://opencv.willowgarage.com/documentation/cpp/camera_calibration_and_3d_reconstruction.html
# intrinsic: camera matrix
# extrinsic: rotation-translation matrix [R|t]
# CV_32F, principal point in the centre of the image is (0, 0) instead of (self.image_size[0]*0.5)
FOCAL_LENGTH = 760.0 # hard-coded in posit_python.cpp, should be changed...
cameraMatrix = [[FOCAL_LENGTH, 0.0, 0.0],#shape[0]*0.0],
[ 0.0, FOCAL_LENGTH, 0.0],#shape[1]*0.0],
[ 0.0, 0.0, 1.0],]
# compare to 2D points
err = []
for i, vec in enumerate(np.array(mdl)):
nvec = np.dot(cameraMatrix, (np.dot(rmat, vec) + tvec))
err.append(((D2points[i] - nvec[:2]/nvec[2]), D2points[i], nvec[:2]/nvec[2]))
#pywikibot.output(u'result for UN-calibrated camera:\n rot=%s' % rvec.transpose()[0])
return rvec, tvec, np.array(cameraMatrix), (np.array(err)/1.0)
# 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"""
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._features['Faces'] += result
return
# .../opencv/samples/cpp/peopledetect.cpp
# + Haar/Cascade detection
def _detect_People(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
scale = 1.
try:
img = cv2.imread(self.image_path_JPEG, cv.CV_LOAD_IMAGE_COLOR)