Untitled

 avatar
user_9363972
python
21 days ago
1.6 kB
2
Indexable
Never
import numpy as np
import cv2

min_confidence = 0.6
classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow',
           'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
net = cv2.dnn.readNetFromCaffe(
    "models/MobileNetSSD_deploy.prototxt.txt", "models/MobileNetSSD_deploy.caffemodel"
)
colors = np.random.uniform(0, 255, size=(len(classes), 3))
image = cv2.imread("images/1.jpg")
image = cv2.resize(image, (800, 600))

height, width = image.shape[0], image.shape[1]

blob = cv2.dnn.blobFromImage(cv2.resize(
    image, (300, 300)), 0.007843, (300, 300), 127.5)
net.setInput(blob)
detections = net.forward()
for i in range(0, detections.shape[2]):
    confidence = detections[0, 0, i, 2]

    if confidence > min_confidence:
        class_id = int(detections[0, 0, i, 1])
        box = detections[0, 0, i, 3:7] * \
            np.array([width, height, width, height])
        (startX, startY, endX, endY) = box.astype('int')
        text = "{:.2f}%".format(confidence * 100) + f"- {classes[class_id]}"
        y = startY - 10 if startY - 10 > 10 else startY+10
        print(startX, startY, endX, endY)
        cv2.rectangle(image, (startX, startY),
                      (endX, endY),  colors[class_id], 2)
        cv2.putText(image, text, (startX, y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.45, colors[class_id], 2)
        print(classes[class_id])

cv2.imshow("Output", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Leave a Comment