Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

detectors_adapt.py 6.8 KB

You have to be logged in to leave a comment. Sign In
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
  1. # coding: utf-8
  2. #!/usr/bin/env pypy
  3. """
  4. Description::
  5. Facial Recognition Model
  6. """
  7. import cv2
  8. import numpy as np
  9. import os
  10. import sys
  11. def set_trace():
  12. """A Poor mans break point"""
  13. # without this in iPython debugger can generate strange characters.
  14. from IPython.core.debugger import Pdb
  15. Pdb().set_trace(sys._getframe().f_back)
  16. class FaceDetector:
  17. def __init__(
  18. self, face_casc='haarcascade_frontalface_default.xml',
  19. left_eye_casc='haarcascade_lefteye_2splits.xml',
  20. right_eye_casc='haarcascade_righteye_2splits.xml', scale_factor=4):
  21. self.scale_factor = scale_factor
  22. self.face_casc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
  23. if self.face_casc.empty():
  24. print 'Warning: Could not load face cascade:', 'haarcascade_frontalface_default.xml'
  25. raise SystemExit
  26. self.left_eye_casc = cv2.CascadeClassifier('haarcascade_lefteye_2splits.xml')
  27. if self.left_eye_casc.empty():
  28. print 'Warning: Could not load left eye cascade:', 'haarcascade_lefteye_2splits.xml'
  29. raise SystemExit
  30. self.right_eye_casc = cv2.CascadeClassifier('haarcascade_righteye_2splits.xml')
  31. if self.right_eye_casc.empty():
  32. print 'Warning: Could not load right eye cascade:', 'haarcascade_righteye_2splits.xml'
  33. raise SystemExit
  34. def detect(self, frame):
  35. frameCasc = cv2.cvtColor(cv2.resize(frame,
  36. (0, 0),
  37. fx=1.0 / self.scale_factor,
  38. fy=1.0 / self.scale_factor),
  39. cv2.COLOR_RGB2GRAY)
  40. faces = self.face_casc.detectMultiScale(frameCasc,
  41. scaleFactor=1.1,
  42. minNeighbors=3,
  43. flags=cv2.CASCADE_FIND_BIGGEST_OBJECT) * self.scale_factor
  44. for (x, y, w, h) in faces:
  45. cv2.rectangle(frame, (x, y), (x + w, y + h), (100, 255, 0), 2)
  46. head = cv2.cvtColor(frame[y:y + h, x:x + w],
  47. cv2.COLOR_RGB2GRAY)
  48. return True, frame, head
  49. return False, frame, None
  50. def align_head(self, head):
  51. """Aligns a head region using affine transformations
  52. This method preprocesses an extracted head region by rotating
  53. and scaling it so that the face appears centered and up-right.
  54. The method returns True on success (else False) and the aligned
  55. head region (head). Possible reasons for failure are that one or
  56. both eye detectors fail, maybe due to poor lighting conditions.
  57. :param head: extracted head region
  58. :returns: success, head
  59. """
  60. # -----> PUT IN SOME CODE TO DEAL WITH NONETYPES FOR head below
  61. height, width = head.shape[:2]
  62. # detect left eye
  63. left_eye_region = head[int(0.2 * height):int(0.8 * height), int(0.2 * width):int(0.5 * width)]
  64. left_eye = self.left_eye_casc.detectMultiScale(
  65. left_eye_region,
  66. scaleFactor=1.1,
  67. minNeighbors=3,
  68. flags=cv2.CASCADE_FIND_BIGGEST_OBJECT)
  69. left_eye_center = None
  70. for (xl, yl, wl, hl) in left_eye:
  71. # find the center of the detected eye region
  72. left_eye_center = np.array([0.1 * width + xl + wl / 2,
  73. 0.2 * height + yl + hl / 2])
  74. break # need only look at first, largest eye
  75. # detect right eye
  76. right_eye_region = head[int(0.2 * height):int(0.8 * height), int(0.5 * width):int(0.9 * width)]
  77. right_eye = self.right_eye_casc.detectMultiScale(
  78. right_eye_region,
  79. scaleFactor=1.1,
  80. minNeighbors=3,
  81. flags=cv2.CASCADE_FIND_BIGGEST_OBJECT)
  82. right_eye_center = None
  83. for (xr, yr, wr, hr) in right_eye:
  84. # find the center of the detected eye region
  85. right_eye_center = np.array([0.5 * width + xr + wr / 2,
  86. 0.2 * height + yr + hr / 2])
  87. break # need only look at first, largest eye
  88. # need both eyes in order to align face
  89. # else break here and report failure (False)
  90. if left_eye_center is None or right_eye_center is None:
  91. return False, head
  92. # we want the eye to be at 25% of the width, and 20% of the height
  93. # resulting image should be square (desired_img_width,
  94. # desired_img_height)
  95. desired_eye_x = 0.25
  96. desired_eye_y = 0.2
  97. desired_img_width = 200
  98. desired_img_height = desired_img_width
  99. # get center point between the two eyes and calculate angle
  100. eye_center = (left_eye_center + right_eye_center) / 2
  101. eye_angle_deg = np.arctan2(right_eye_center[1] - left_eye_center[1],
  102. right_eye_center[0] - left_eye_center[0]) \
  103. * 180.0 / 3.1415927
  104. # scale distance between eyes to desired length
  105. eyeSizeScale = (1.0 - desired_eye_x * 2) * desired_img_width / \
  106. np.linalg.norm(right_eye_center - left_eye_center)
  107. # get rotation matrix
  108. rot_mat = cv2.getRotationMatrix2D(tuple(eye_center), eye_angle_deg,
  109. eyeSizeScale)
  110. # shift center of the eyes to be centered in the image
  111. rot_mat[0, 2] += desired_img_width * 0.5 - eye_center[0]
  112. rot_mat[1, 2] += desired_eye_y * desired_img_height - eye_center[1]
  113. # warp perspective to make eyes aligned on horizontal line and scaled
  114. # to right size
  115. res = cv2.warpAffine(head, rot_mat, (desired_img_width,
  116. desired_img_width))
  117. # return success
  118. return True, res
  119. def main():
  120. set_trace()
  121. cwd = os.getcwd()
  122. path = './Criminals'
  123. frame = cv2.imread('./Criminals/056a.jpg', cv2.CV_8UC1)
  124. face_casc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
  125. faces = face_casc.detectMultiScale(frame,
  126. scaleFactor=1.1,
  127. minNeighbors=3
  128. )
  129. for (x, y, w, h) in faces:
  130. # draw bounding box on frame
  131. cv2.rectangle(frame, (x, y), (x + w, y + h), (100, 255, 0), 2)
  132. self.face_casc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
  133. if self.face_casc.empty():
  134. print 'Warning: Could not load face cascade:', 'haarcascade_frontalface_default.xml'
  135. raise SystemExit
  136. set_trace()
  137. if __name__ == "__main__":
  138. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...