- add face pixelate model for train/evaluate
[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_REGION_IDX, FaceDetectTransform.COL_IMAGE_IDX]
60         blank_cols = [col for col in df.columns if col not in keep_col]
61         # set columns that aren't in our known column list to empty strings; search where face index==-1 (no face)
62         df.loc[df[FaceDetectTransform.COL_REGION_IDX]==FaceDetectTransform.VAL_REGION_IMAGE_ID,blank_cols] = ""
63         return df
64
65     @property
66     def output_names_(self):
67         return [FaceDetectTransform.COL_REGION_IDX, FaceDetectTransform.COL_FACE_X, FaceDetectTransform.COL_FACE_Y,
68                  FaceDetectTransform.COL_FACE_W, FaceDetectTransform.COL_FACE_H,
69                  FaceDetectTransform.COL_IMAGE_IDX, FaceDetectTransform.COL_IMAGE_MIME, FaceDetectTransform.COL_IMAGE_DATA]
70
71     @property
72     def output_types_(self):
73         list_name = self.output_names_
74         list_type = self.classes_
75         return [{list_name[i]:list_type[i]} for i in range(len(list_name))]
76
77     @property
78     def n_outputs_(self):
79         return 8
80
81     @property
82     def classes_(self):
83         return [int, int, int, int, int, int, str, str]
84
85     def score(self, X, y=None):
86         return 0
87
88     def fit(self, X, y=None):
89         return self
90
91     def predict(self, X, y=None):
92         """
93         Assumes a numpy array of [[mime_type, binary_string] ... ]
94            where mime_type is an image-specifying mime type and binary_string is the raw image bytes       
95         """
96         # if no model exists yet, create it
97         if self.cascade_obj is None:
98             if self.cascade_path is not None:
99                 self.cascade_obj = cv2.CascadeClassifier(self.cascade_path)
100             else:   # none provided, load what came with the package
101                 pathRoot = os.path.dirname(os.path.abspath(__file__))
102                 pathFile = os.path.join(pathRoot, FaceDetectTransform.CASCADE_DEFAULT_FILE)
103                 self.cascade_obj = cv2.CascadeClassifier(pathFile)
104
105         dfReturn = None
106         for image_idx in range(len(X)):
107             file_bytes = np.asarray(bytearray(X[FaceDetectTransform.COL_IMAGE_DATA][image_idx]), dtype=np.uint8)
108             img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
109             # img = cv2.imread(image_set[1])
110             faces = self.detect_faces(img)
111
112             df = pd.DataFrame()  # start with empty DF for this image
113             if self.include_image:  # create and append the image if that's requested
114                 dict_image = FaceDetectTransform.generate_out_dict(w=img.shape[0], h=img.shape[1], image=image_idx)
115                 dict_image[FaceDetectTransform.COL_IMAGE_MIME] = X[FaceDetectTransform.COL_IMAGE_MIME][image_idx]
116                 dict_image[FaceDetectTransform.COL_IMAGE_DATA] = X[FaceDetectTransform.COL_IMAGE_DATA][image_idx]
117                 df = pd.DataFrame([dict_image])
118             for idxF in range(len(faces)):  # walk through detected faces
119                 face_rect = faces[idxF]
120                 df = df.append(pd.DataFrame([FaceDetectTransform.generate_out_dict(idxF, face_rect[0], face_rect[1],
121                                                                     face_rect[2], face_rect[3], image=image_idx)]),
122                                ignore_index=True)
123             if dfReturn is None:  # create an NP container for all image samples + features
124                 dfReturn = df.reindex_axis(self.output_names_, axis=1)
125             else:
126                 dfReturn = dfReturn.append(df, ignore_index=True)
127             #print("IMAGE {:} found {:} total rows".format(image_idx, len(df)))
128
129         return dfReturn
130
131     def detect_faces(self, img):
132         if self.cascade_obj is None: return []
133         gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
134
135         faces = self.cascade_obj.detectMultiScale(
136             gray,
137             scaleFactor=1.1,
138             minNeighbors=5,
139             minSize=(30, 30),
140             flags=cv2.CASCADE_SCALE_IMAGE
141         )
142
143         # Draw a rectangle around the faces
144         #for (x, y, w, h) in faces:
145         #    cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
146         return faces
147
148     #############################################
149     ## helper for i/o
150     @staticmethod
151     def read_byte_arrays(bytearray_string):
152         """Method to recover bytes from pandas read/cast function:
153             inputDf = pd.read_csv(config['input'], converters:{FaceDetectTransform.COL_IMAGE_DATA:FaceDetectTransform.read_byte_arrays})
154            https://stackoverflow.com/a/43024993
155         """
156         from ast import literal_eval
157         if bytearray_string.startswith("b'"):
158             return bytearray(literal_eval(bytearray_string))
159         return bytearray_string