Home > Back-end >  how to accurately count unique instances of an object open cv python
how to accurately count unique instances of an object open cv python

Time:06-23

I have an OpenCV python application where I need I need to count the unique occurrences of the detected object(s).

I have tried to track the occurrence of the bounding boxes, but it looks like it keeps resetting every time and not adding up the total number of times the object is detected.

Here is the console output:

Palm Trees: 0
Palm Trees: 3
Palm Trees: 3
Palm Trees: 4
Palm Trees: 4
Palm Trees: 6
Palm Trees: 4
Palm Trees: 4
Palm Trees: 4
Palm Trees: 4
Palm Trees: 4
Palm Trees: 5
Palm Trees: 3
Palm Trees: 3
Palm Trees: 3
Palm Trees: 3
Palm Trees: 3
Palm Trees: 2
Palm Trees: 2
Palm Trees: 3
Palm Trees: 3
Palm Trees: 2
Palm Trees: 3
Palm Trees: 3
Palm Trees: 3
Palm Trees: 5
Palm Trees: 4
Palm Trees: 3
Palm Trees: 3

Here is my python code:

import cv2
import numpy as np
import matplotlib.pyplot as plt

net = cv2.dnn.readNet('yolov3_training_last.weights', 'yolov3_testing.cfg')

classes = []
with open("classes.txt", "r") as f:
    classes = f.read().splitlines()

cap = cv2.VideoCapture('driveday2_plamtrees.mp4')
# cap = cv2.VideoCapture(4)
font = cv2.FONT_HERSHEY_PLAIN
colors = np.random.uniform(0, 255, size=(100, 3))

a=[]
count_trees = 0;

while True:
    _, img = cap.read()
    height, width, _ = img.shape

    blob = cv2.dnn.blobFromImage(img, 1/255, (416, 416), (0,0,0), swapRB=True, crop=False)
    net.setInput(blob)
    output_layers_names = net.getUnconnectedOutLayersNames()
    layerOutputs = net.forward(output_layers_names)

    boxes = []
    confidences = []
    class_ids = []

    for output in layerOutputs:
        for detection in output:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.2:
                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)

                boxes.append([x, y, w, h])
                a.append([center_x,center_y])
                # print("Palm Trees: "   str(len(a)))
                confidences.append((float(confidence)))
                class_ids.append(class_id)

    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.2, 0.4)

    if len(indexes)>0:
        for i in indexes.flatten():
            x, y, w, h = boxes[i]
            label = str(classes[class_ids[i]])
            confidence = str(round(confidences[i],2))
            color = colors[i]
            cv2.rectangle(img, (x,y), (x w, y h), color, 2)
            cv2.putText(img, label   " "   confidence, (x, y 20), font, 2, (255,255,255), 1)
            count_trees = 1   len(boxes)
    print("Palm Trees: "   str(count_trees))

    cv2.imshow('Image', img)
    key = cv2.waitKey(1)
    if key==ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

How do I accurately count the number of times the object is uniquely detected?

CodePudding user response:

If I understand your code correctly, you should just change

count_trees = 1   len(boxes)

to

count_trees  = 1   len(boxes)

so you keep adding the number of boxes to the total

CodePudding user response:

Adding to @Stefan's, to verify if you accumulated unique count of palm trees correctly, add this line before cap.release()

print(f"Total palm tree count -- {count_trees}")
  • Related