2 # -*- coding: utf-8 -*-
4 Wrapper for face detection task; wrapped in classifier for pipieline terminus
10 from sklearn.base import BaseEstimator, ClassifierMixin
12 class FaceDetectTransform(BaseEstimator, ClassifierMixin):
14 A sklearn transformer mixin that detects faces and optionally outputa the original detected image
16 CASCADE_DEFAULT_FILE = "data/haarcascade_frontalface_alt.xml.gz"
21 COL_REGION_IDX = 'region'
22 COL_IMAGE_IDX = 'image'
23 COL_IMAGE_MIME = 'mime_type'
24 COL_IMAGE_DATA = 'binary_stream'
25 VAL_REGION_IMAGE_ID = -1
27 def __init__(self, cascade_path=None, include_image=True):
28 self.include_image = include_image # should output transform include image?
29 self.cascade_path = cascade_path # abs path outside of module
30 self.cascade_obj = None # late-load this component
32 def get_params(self, deep=False):
33 return {'include_image': self.include_image}
36 def generate_in_df(path_image="", bin_stream=b""):
37 # munge stream and mimetype into input sample
38 if path_image and os.path.exists(path_image):
39 bin_stream = open(path_image, 'rb').read()
40 return pd.DataFrame([['image/jpeg', bin_stream]], columns=[FaceDetectTransform.COL_IMAGE_MIME, FaceDetectTransform.COL_IMAGE_DATA])
43 def generate_out_image(row, path_image):
44 # take image row and output to disk
45 with open(path_image, 'wb') as f:
46 f.write(row[FaceDetectTransform.COL_IMAGE_DATA][0])
49 def generate_out_dict(idx=VAL_REGION_IMAGE_ID, x=0, y=0, w=0, h=0, image=0):
50 return {FaceDetectTransform.COL_REGION_IDX: idx, FaceDetectTransform.COL_FACE_X: x,
51 FaceDetectTransform.COL_FACE_Y: y, FaceDetectTransform.COL_FACE_W: w, FaceDetectTransform.COL_FACE_H: h,
52 FaceDetectTransform.COL_IMAGE_IDX: image,
53 FaceDetectTransform.COL_IMAGE_MIME: '', FaceDetectTransform.COL_IMAGE_DATA: ''}
56 def suppress_image(df):
57 keep_col = [FaceDetectTransform.COL_FACE_X, FaceDetectTransform.COL_FACE_Y,
58 FaceDetectTransform.COL_FACE_W, FaceDetectTransform.COL_FACE_H,
59 FaceDetectTransform.COL_FACE_W, FaceDetectTransform.COL_FACE_H,
60 FaceDetectTransform.COL_REGION_IDX, FaceDetectTransform.COL_IMAGE_IDX]
61 blank_cols = [col for col in df.columns if col not in keep_col]
62 # set columns that aren't in our known column list to empty strings; search where face index==-1 (no face)
63 df.loc[df[FaceDetectTransform.COL_REGION_IDX]==FaceDetectTransform.VAL_REGION_IMAGE_ID,blank_cols] = ""
67 def output_names_(self):
68 return [FaceDetectTransform.COL_REGION_IDX, FaceDetectTransform.COL_FACE_X, FaceDetectTransform.COL_FACE_Y,
69 FaceDetectTransform.COL_FACE_W, FaceDetectTransform.COL_FACE_H,
70 FaceDetectTransform.COL_IMAGE_IDX, FaceDetectTransform.COL_IMAGE_MIME, FaceDetectTransform.COL_IMAGE_DATA]
73 def output_types_(self):
74 list_name = self.output_names_
75 list_type = self.classes_
76 return [{list_name[i]:list_type[i]} for i in range(len(list_name))]
84 return [int, int, int, int, int, int, str, str]
86 def score(self, X, y=None):
89 def fit(self, X, y=None):
92 def predict(self, X, y=None):
94 Assumes a numpy array of [[mime_type, binary_string] ... ]
95 where mime_type is an image-specifying mime type and binary_string is the raw image bytes
97 # if no model exists yet, create it
98 if self.cascade_obj is None:
99 if self.cascade_path is not None:
100 self.cascade_obj = cv2.CascadeClassifier(self.cascade_path)
101 else: # none provided, load what came with the package
102 pathRoot = os.path.dirname(os.path.abspath(__file__))
103 pathFile = os.path.join(pathRoot, FaceDetectTransform.CASCADE_DEFAULT_FILE)
104 self.cascade_obj = cv2.CascadeClassifier(pathFile)
107 for image_idx in range(len(X)):
108 file_bytes = np.asarray(bytearray(X[FaceDetectTransform.COL_IMAGE_DATA][image_idx]), dtype=np.uint8)
109 img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
110 # img = cv2.imread(image_set[1])
111 faces = self.detect_faces(img)
113 df = pd.DataFrame() # start with empty DF for this image
114 if self.include_image: # create and append the image if that's requested
115 dict_image = FaceDetectTransform.generate_out_dict(w=img.shape[1], h=img.shape[0], image=image_idx)
116 dict_image[FaceDetectTransform.COL_IMAGE_MIME] = X[FaceDetectTransform.COL_IMAGE_MIME][image_idx]
117 dict_image[FaceDetectTransform.COL_IMAGE_DATA] = X[FaceDetectTransform.COL_IMAGE_DATA][image_idx]
118 df = pd.DataFrame([dict_image])
119 for idxF in range(len(faces)): # walk through detected faces
120 face_rect = faces[idxF]
121 df = df.append(pd.DataFrame([FaceDetectTransform.generate_out_dict(idxF, face_rect[0], face_rect[1],
122 face_rect[2], face_rect[3], image=image_idx)]),
124 if dfReturn is None: # create an NP container for all image samples + features
125 dfReturn = df.reindex_axis(self.output_names_, axis=1)
127 dfReturn = dfReturn.append(df, ignore_index=True)
128 #print("IMAGE {:} found {:} total rows".format(image_idx, len(df)))
132 def detect_faces(self, img):
133 if self.cascade_obj is None: return []
134 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
136 faces = self.cascade_obj.detectMultiScale(
141 flags=cv2.CASCADE_SCALE_IMAGE
144 # Draw a rectangle around the faces
145 #for (x, y, w, h) in faces:
146 # cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
149 #############################################
152 def read_byte_arrays(bytearray_string):
153 """Method to recover bytes from pandas read/cast function:
154 inputDf = pd.read_csv(config['input'], converters:{FaceDetectTransform.COL_IMAGE_DATA:FaceDetectTransform.read_byte_arrays})
155 https://stackoverflow.com/a/43024993
157 from ast import literal_eval
158 if type(bytearray_string)==str and bytearray_string.startswith("b'"):
159 return bytearray(literal_eval(bytearray_string))
160 return bytearray_string