11472a93c837fdce5f24b74f278810b0247d8210
[platform/upstream/opencv.git] / modules / contrib / doc / facerec / src / crop_face.py
1 #!/usr/bin/env python
2 # Software License Agreement (BSD License)
3 #
4 # Copyright (c) 2012, Philipp Wagner
5 # All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions
9 # are met:
10 #
11 #  * Redistributions of source code must retain the above copyright
12 #    notice, this list of conditions and the following disclaimer.
13 #  * Redistributions in binary form must reproduce the above
14 #    copyright notice, this list of conditions and the following
15 #    disclaimer in the documentation and/or other materials provided
16 #    with the distribution.
17 #  * Neither the name of the author nor the names of its
18 #    contributors may be used to endorse or promote products derived
19 #    from this software without specific prior written permission.
20 #
21 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 # POSSIBILITY OF SUCH DAMAGE.
33
34 import sys, math, Image
35
36 def Distance(p1,p2):
37   dx = p2[0] - p1[0]
38   dy = p2[1] - p1[1]
39   return math.sqrt(dx*dx+dy*dy)
40
41 def ScaleRotateTranslate(image, angle, center = None, new_center = None, scale = None, resample=Image.BICUBIC):
42   if (scale is None) and (center is None):
43     return image.rotate(angle=angle, resample=resample)
44   nx,ny = x,y = center
45   sx=sy=1.0
46   if new_center:
47     (nx,ny) = new_center
48   if scale:
49     (sx,sy) = (scale, scale)
50   cosine = math.cos(angle)
51   sine = math.sin(angle)
52   a = cosine/sx
53   b = sine/sx
54   c = x-nx*a-ny*b
55   d = -sine/sy
56   e = cosine/sy
57   f = y-nx*d-ny*e
58   return image.transform(image.size, Image.AFFINE, (a,b,c,d,e,f), resample=resample)
59
60 def CropFace(image, eye_left=(0,0), eye_right=(0,0), offset_pct=(0.2,0.2), dest_sz = (70,70)):
61   # calculate offsets in original image
62   offset_h = math.floor(float(offset_pct[0])*dest_sz[0])
63   offset_v = math.floor(float(offset_pct[1])*dest_sz[1])
64   # get the direction
65   eye_direction = (eye_right[0] - eye_left[0], eye_right[1] - eye_left[1])
66   # calc rotation angle in radians
67   rotation = -math.atan2(float(eye_direction[1]),float(eye_direction[0]))
68   # distance between them
69   dist = Distance(eye_left, eye_right)
70   # calculate the reference eye-width
71   reference = dest_sz[0] - 2.0*offset_h
72   # scale factor
73   scale = float(dist)/float(reference)
74   # rotate original around the left eye
75   image = ScaleRotateTranslate(image, center=eye_left, angle=rotation)
76   # crop the rotated image
77   crop_xy = (eye_left[0] - scale*offset_h, eye_left[1] - scale*offset_v)
78   crop_size = (dest_sz[0]*scale, dest_sz[1]*scale)
79   image = image.crop((int(crop_xy[0]), int(crop_xy[1]), int(crop_xy[0]+crop_size[0]), int(crop_xy[1]+crop_size[1])))
80   # resize it
81   image = image.resize(dest_sz, Image.ANTIALIAS)
82   return image
83
84 def readFileNames():
85     try:
86         inFile = open('path_to_created_csv_file.csv')
87     except:
88         raise IOError('There is no file named path_to_created_csv_file.csv in current directory.')
89         return False
90
91     picPath = []
92     picIndex = []
93
94     for line in inFile.readlines():
95         if line != '':
96             fields = line.rstrip().split(';')
97             picPath.append(fields[0])
98             picIndex.append(int(fields[1]))
99
100     return (picPath, picIndex)
101
102
103 if __name__ == "__main__":
104   [images, indexes]=readFileNames()
105 if not os.path.exists("modified"):
106     os.makedirs("modified")
107 for img in images:
108     image =  Image.open(img)
109     CropFace(image, eye_left=(252,364), eye_right=(420,366), offset_pct=(0.1,0.1), dest_sz=(200,200)).save("modified/"+img.rstrip().split('/')[1]+"_10_10_200_200.jpg")
110     CropFace(image, eye_left=(252,364), eye_right=(420,366), offset_pct=(0.2,0.2), dest_sz=(200,200)).save("modified/"+img.rstrip().split('/')[1]+"_20_20_200_200.jpg")
111     CropFace(image, eye_left=(252,364), eye_right=(420,366), offset_pct=(0.3,0.3), dest_sz=(200,200)).save("modified/"+img.rstrip().split('/')[1]+"_30_30_200_200.jpg")
112     CropFace(image, eye_left=(252,364), eye_right=(420,366), offset_pct=(0.2,0.2)).save("modified/"+img.rstrip().split('/')[1]+"_20_20_70_70.jpg")