- first pass at app endpoint simulation
[face-privacy-filter.git] / face_privacy_filter / transform_detect.py
1 #! python
2 # -*- coding: utf-8 -*-
3 """
4 Wrapper for face detection task; wrapped in classifier for pipieline terminus
5 """
6 import cv2
7 import os
8 import pandas as pd
9 import numpy as np
10 from sklearn.base import BaseEstimator, ClassifierMixin
11
12 class FaceDetectTransform(BaseEstimator, ClassifierMixin):
13     '''
14     A sklearn transformer mixin that detects faces and optionally outputa the original detected image
15     '''
16     CASCADE_DEFAULT_FILE = "data/haarcascade_frontalface_alt.xml.gz"
17     COL_FACE_X = 'x'
18     COL_FACE_Y = 'y'
19     COL_FACE_W = 'w'
20     COL_FACE_H = 'h'
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
26
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
31
32     def get_params(self, deep=False):
33         return {'include_image': self.include_image}
34
35     @staticmethod
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])
41
42     @staticmethod
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])
47
48     @staticmethod
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: ''}
54
55     @staticmethod
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] = ""
64         return df
65
66     @property
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]
71
72     @property
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))]
77
78     @property
79     def n_outputs_(self):
80         return 8
81
82     @property
83     def classes_(self):
84         return [int, int, int, int, int, int, str, str]
85
86     def score(self, X, y=None):
87         return 0
88
89     def fit(self, X, y=None):
90         return self
91
92     def predict(self, X, y=None):
93         """
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       
96         """
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)
105
106         dfReturn = None
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)
112
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)]),
123                                ignore_index=True)
124             if dfReturn is None:  # create an NP container for all image samples + features
125                 dfReturn = df.reindex_axis(self.output_names_, axis=1)
126             else:
127                 dfReturn = dfReturn.append(df, ignore_index=True)
128             #print("IMAGE {:} found {:} total rows".format(image_idx, len(df)))
129
130         return dfReturn
131
132     def detect_faces(self, img):
133         if self.cascade_obj is None: return []
134         gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
135
136         faces = self.cascade_obj.detectMultiScale(
137             gray,
138             scaleFactor=1.1,
139             minNeighbors=5,
140             minSize=(30, 30),
141             flags=cv2.CASCADE_SCALE_IMAGE
142         )
143
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)
147         return faces
148
149     #############################################
150     ## helper for i/o
151     @staticmethod
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
156         """
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
161
162 # FaceDetectTransform.__module__ = '__main__'