|
| 1 | +# Import Libraries |
| 2 | +import cv2 |
| 3 | +import os |
| 4 | +import filetype |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +# The model architecture |
| 8 | +# download from: https://drive.google.com/open?id=1kiusFljZc9QfcIYdU2s7xrtWHTraHwmW |
| 9 | +AGE_MODEL = 'weights/deploy_age.prototxt' |
| 10 | +# The model pre-trained weights |
| 11 | +# download from: https://drive.google.com/open?id=1kWv0AjxGSN0g31OeJa02eBGM0R_jcjIl |
| 12 | +AGE_PROTO = 'weights/age_net.caffemodel' |
| 13 | +# Each Caffe Model impose the shape of the input image also image preprocessing is required like mean |
| 14 | +# substraction to eliminate the effect of illunination changes |
| 15 | +MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746) |
| 16 | +# Represent the 8 age classes of this CNN probability layer |
| 17 | +AGE_INTERVALS = ['(0, 2)', '(4, 6)', '(8, 12)', '(15, 20)', |
| 18 | + '(25, 32)', '(38, 43)', '(48, 53)', '(60, 100)'] |
| 19 | +# download from: https://raw.githubusercontent.com/opencv/opencv/master/samples/dnn/face_detector/deploy.prototxt |
| 20 | +FACE_PROTO = "weights/deploy.prototxt.txt" |
| 21 | +# download from: https://raw.githubusercontent.com/opencv/opencv_3rdparty/dnn_samples_face_detector_20180205_fp16/res10_300x300_ssd_iter_140000_fp16.caffemodel |
| 22 | +FACE_MODEL = "weights/res10_300x300_ssd_iter_140000_fp16.caffemodel" |
| 23 | + |
| 24 | +# Initialize frame size |
| 25 | +frame_width = 1280 |
| 26 | +frame_height = 720 |
| 27 | + |
| 28 | +# load face Caffe model |
| 29 | +face_net = cv2.dnn.readNetFromCaffe(FACE_PROTO, FACE_MODEL) |
| 30 | +# Load age prediction model |
| 31 | +age_net = cv2.dnn.readNetFromCaffe(AGE_MODEL, AGE_PROTO) |
| 32 | + |
| 33 | + |
| 34 | +def get_faces(frame, confidence_threshold=0.5): |
| 35 | + """Returns the box coordinates of all detected faces""" |
| 36 | + # convert the frame into a blob to be ready for NN input |
| 37 | + blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), (104, 177.0, 123.0)) |
| 38 | + # set the image as input to the NN |
| 39 | + face_net.setInput(blob) |
| 40 | + # perform inference and get predictions |
| 41 | + output = np.squeeze(face_net.forward()) |
| 42 | + # initialize the result list |
| 43 | + faces = [] |
| 44 | + # Loop over the faces detected |
| 45 | + for i in range(output.shape[0]): |
| 46 | + confidence = output[i, 2] |
| 47 | + if confidence > confidence_threshold: |
| 48 | + box = output[i, 3:7] * np.array([frame_width, frame_height, frame_width, frame_height]) |
| 49 | + # convert to integers |
| 50 | + start_x, start_y, end_x, end_y = box.astype(np.int) |
| 51 | + # widen the box a little |
| 52 | + start_x, start_y, end_x, end_y = start_x - \ |
| 53 | + 10, start_y - 10, end_x + 10, end_y + 10 |
| 54 | + start_x = 0 if start_x < 0 else start_x |
| 55 | + start_y = 0 if start_y < 0 else start_y |
| 56 | + end_x = 0 if end_x < 0 else end_x |
| 57 | + end_y = 0 if end_y < 0 else end_y |
| 58 | + # append to our list |
| 59 | + faces.append((start_x, start_y, end_x, end_y)) |
| 60 | + return faces |
| 61 | + |
| 62 | + |
| 63 | +def display_img(title, img): |
| 64 | + """Displays an image on screen and maintains the output until the user presses a key""" |
| 65 | + # Display Image on screen |
| 66 | + cv2.imshow(title, img) |
| 67 | + # Mantain output until user presses a key |
| 68 | + cv2.waitKey(0) |
| 69 | + # Destroy windows when user presses a key |
| 70 | + cv2.destroyAllWindows() |
| 71 | + |
| 72 | + |
| 73 | +def predict_age(input_path: str): |
| 74 | + """Predict the age of the faces showing in the image""" |
| 75 | + # Read Input Image |
| 76 | + img = cv2.imread(input_path) |
| 77 | + # resize the image |
| 78 | + img = cv2.resize(img, (frame_width, frame_height)) |
| 79 | + # Take a copy of the initial image and resize it |
| 80 | + frame = img.copy() |
| 81 | + faces = get_faces(frame) |
| 82 | + for i, (start_x, start_y, end_x, end_y) in enumerate(faces): |
| 83 | + face_img = frame[start_y: end_y, start_x: end_x] |
| 84 | + # image --> Input image to preprocess before passing it through our dnn for classification. |
| 85 | + blob = cv2.dnn.blobFromImage( |
| 86 | + image=face_img, scalefactor=1.0, size=(227, 227), |
| 87 | + mean=MODEL_MEAN_VALUES, swapRB=False |
| 88 | + ) |
| 89 | + # Predict Age |
| 90 | + age_net.setInput(blob) |
| 91 | + age_preds = age_net.forward() |
| 92 | + print("="*30, f"Face {i+1} Prediction Probabilities", "="*30) |
| 93 | + for i in range(age_preds[0].shape[0]): |
| 94 | + print(f"{AGE_INTERVALS[i]}: {age_preds[0, i]*100:.2f}%") |
| 95 | + i = age_preds[0].argmax() |
| 96 | + age = AGE_INTERVALS[i] |
| 97 | + age_confidence_score = age_preds[0][i] |
| 98 | + # Draw the box |
| 99 | + label = f"Age:{age} - {age_confidence_score*100:.2f}%" |
| 100 | + print(label) |
| 101 | + # get the position where to put the text |
| 102 | + yPos = start_y - 15 |
| 103 | + while yPos < 15: |
| 104 | + yPos += 15 |
| 105 | + # write the text into the frame |
| 106 | + cv2.putText(frame, label, (start_x, yPos), |
| 107 | + cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), thickness=2) |
| 108 | + # draw the rectangle around the face |
| 109 | + cv2.rectangle(frame, (start_x, start_y), (end_x, end_y), color=(255, 0, 0), thickness=2) |
| 110 | + # Display processed image |
| 111 | + display_img('Age Estimator', frame) |
| 112 | + # save the image if you want |
| 113 | + # cv2.imwrite("predicted_age.jpg", frame) |
| 114 | + |
| 115 | + |
| 116 | + |
| 117 | +if __name__ == '__main__': |
| 118 | + # Parsing command line arguments entered by user |
| 119 | + import sys |
| 120 | + image_path = sys.argv[1] |
| 121 | + predict_age(image_path) |
0 commit comments