So in general there are no problems, the script works well and does what it is supposed to do, I would just like to ask you for advice on what I can improve in the code and what other function I can implement.
Below you will find the py code, I used yolo for training and coco.names for labels:
`import cv2
import numpy as np
from concurrent.futures import ThreadPoolExecutor
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
cap = cv2.VideoCapture(0)
min_confidence = 0.5
max_detections = 10
detections_count = 0
input_width = 416
input_height = 416
def process_detection(frame, detection, detected_objects):
global detections_count
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > min_confidence:
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
detected_objects.append({"class_id": class_id, "confidence": confidence, "x": x, "y": y, "w": w, "h": h})
detections_count += 1
if detections_count >= max_detections:
return True
return False
while True:
ret, frame = cap.read()
height, width, channels = frame.shape
detected_objects = []
blob = cv2.dnn.blobFromImage(frame, 0.00392, (input_width, input_height), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
with ThreadPoolExecutor() as executor:
futures = [executor.submit(process_detection, frame, detection, detected_objects) for detection in outs[0]]
for future in futures:
if future.result():
break
for obj in detected_objects:
cv2.rectangle(frame, (obj["x"], obj["y"]), (obj["x"] + obj["w"], obj["y"] + obj["h"]), (0,255, 0), 2)
cv2.putText(frame, classes[obj["class_id"]], (obj["x"], obj["y"] - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.imshow("Object Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()`
I would like to be able to implement new features, and if possible understand how to improve the code and what to optimize.
New contributor
Ciro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.