|
7 | 7 |
|
8 | 8 | # step 2 - feed a 640x640 image to get predictions
|
9 | 9 |
|
10 |
| -image = cv2.imread('misc/car.jpg') |
11 |
| -blob = cv2.dnn.blobFromImage(image, 1/255.0, (640, 640), swapRB=True) |
| 10 | +def format_yolov5(frame): |
| 11 | + |
| 12 | + row, col, _ = frame.shape |
| 13 | + _max = max(col, row) |
| 14 | + result = np.zeros((_max, _max, 3), np.uint8) |
| 15 | + result[0:row, 0:col] = frame |
| 16 | + return result |
| 17 | + |
| 18 | +image = cv2.imread('misc/corrida-crianças-1280x720.jpg') |
| 19 | +input_image = format_yolov5(image) # making the image square |
| 20 | +blob = cv2.dnn.blobFromImage(input_image , 1/255.0, (640, 640), swapRB=True) |
12 | 21 | net.setInput(blob)
|
13 | 22 | predictions = net.forward()
|
14 | 23 |
|
|
20 | 29 |
|
21 | 30 | output_data = predictions[0]
|
22 | 31 |
|
| 32 | +image_width, image_height, _ = input_image.shape |
| 33 | +x_factor = image_width / 640 |
| 34 | +y_factor = image_height / 640 |
| 35 | + |
23 | 36 | for r in range(25200):
|
24 | 37 | row = output_data[r]
|
25 | 38 | confidence = row[4]
|
|
35 | 48 | class_ids.append(class_id)
|
36 | 49 |
|
37 | 50 | x, y, w, h = row[0].item(), row[1].item(), row[2].item(), row[3].item()
|
38 |
| - left = int(x - 0.5 * w) |
39 |
| - top = int(y - 0.5 * h) |
40 |
| - box = np.array([left, top, int(w), int(h)]) |
| 51 | + left = int((x - 0.5 * w) * x_factor) |
| 52 | + top = int((y - 0.5 * h) * y_factor) |
| 53 | + width = int(w * x_factor) |
| 54 | + height = int(h * y_factor) |
| 55 | + box = np.array([left, top, width, height]) |
41 | 56 | boxes.append(box)
|
42 | 57 |
|
43 | 58 | class_list = []
|
44 | 59 | with open("config_files/classes.txt", "r") as f:
|
45 | 60 | class_list = [cname.strip() for cname in f.readlines()]
|
46 | 61 |
|
47 |
| -for i in range(len(class_ids)): |
| 62 | +indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.25, 0.45) |
| 63 | + |
| 64 | +result_class_ids = [] |
| 65 | +result_confidences = [] |
| 66 | +result_boxes = [] |
| 67 | + |
| 68 | +for i in indexes: |
| 69 | + result_confidences.append(confidences[i]) |
| 70 | + result_class_ids.append(class_ids[i]) |
| 71 | + result_boxes.append(boxes[i]) |
| 72 | + |
| 73 | +for i in range(len(result_class_ids)): |
48 | 74 |
|
49 |
| - box = boxes[i] |
50 |
| - class_id = class_ids[i] |
| 75 | + box = result_boxes[i] |
| 76 | + class_id = result_class_ids[i] |
51 | 77 |
|
52 | 78 | cv2.rectangle(image, box, (0, 255, 255), 2)
|
53 | 79 | cv2.rectangle(image, (box[0], box[1] - 20), (box[0] + box[2], box[1]), (0, 255, 255), -1)
|
54 | 80 | cv2.putText(image, class_list[class_id], (box[0], box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, .5, (0,0,0))
|
55 | 81 |
|
| 82 | +cv2.imwrite("misc/kids_detection.png", image) |
56 | 83 | cv2.imshow("output", image)
|
57 | 84 | cv2.waitKey()
|
0 commit comments