1
+ import cv2
2
+ import numpy as np
3
+
4
+ # https://raw.githubusercontent.com/opencv/opencv/master/samples/dnn/face_detector/deploy.prototxt
5
+ prototxt_path = "weights/deploy.prototxt.txt"
6
+ # https://raw.githubusercontent.com/opencv/opencv_3rdparty/dnn_samples_face_detector_20180205_fp16/res10_300x300_ssd_iter_140000_fp16.caffemodel
7
+ model_path = "weights/res10_300x300_ssd_iter_140000_fp16.caffemodel"
8
+
9
+ # load Caffe model
10
+ model = cv2 .dnn .readNetFromCaffe (prototxt_path , model_path )
11
+
12
+ # read the desired image
13
+ image = cv2 .imread ("kids.jpg" )
14
+ # get width and height of the image
15
+ h , w = image .shape [:2 ]
16
+
17
+ # preprocess the image: resize and performs mean subtraction
18
+ blob = cv2 .dnn .blobFromImage (image , 1.0 , (300 , 300 ), (104.0 , 177.0 , 123.0 ))
19
+ # set the image into the input of the neural network
20
+ model .setInput (blob )
21
+ # perform inference and get the result
22
+ output = np .squeeze (model .forward ())
23
+ font_scale = 1.0
24
+ for i in range (0 , output .shape [0 ]):
25
+ # get the confidence
26
+ confidence = output [i , 2 ]
27
+ # if confidence is above 50%, then draw the surrounding box
28
+ if confidence > 0.5 :
29
+ # get the surrounding box cordinates and upscale them to original image
30
+ box = output [i , 3 :7 ] * np .array ([w , h , w , h ])
31
+ # convert to integers
32
+ start_x , start_y , end_x , end_y = box .astype (np .int )
33
+ # draw the rectangle surrounding the face
34
+ cv2 .rectangle (image , (start_x , start_y ), (end_x , end_y ), color = (255 , 0 , 0 ), thickness = 2 )
35
+ # draw text as well
36
+ cv2 .putText (image , f"{ confidence * 100 :.2f} %" , (start_x , start_y - 5 ), cv2 .FONT_HERSHEY_SIMPLEX , font_scale , (255 , 0 , 0 ), 2 )
37
+ # show the image
38
+ cv2 .imshow ("image" , image )
39
+ cv2 .waitKey (0 )
40
+ # save the image with rectangles
41
+ cv2 .imwrite ("kids_detected_dnn.jpg" , image )
0 commit comments