Search code examples
tensorflowopencvmachine-learningcomputer-visionobject-detection

How to count objects using tensorflow model?


i want to count detected objects based on detection scores. I am using EdjeElectronics's Object detection code. And here's the code i've been using:

# Input tensor is the image
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

# Output tensors are the detection boxes, scores, and classes
# Each box represents a part of the image where a particular object was detected
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

# Each score represents level of confidence for each of the objects.
# The score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')

This is the detection lines:

(boxes, scores, classes, num) = sess.run(
        [detection_boxes, detection_scores, detection_classes, num_detections],
        feed_dict={image_tensor: frame_expanded})

And visualizing it using this:

# Draw the results of the detection (aka 'visulaize the results')
    vis_util.visualize_boxes_and_labels_on_image_array(
        frame,
        np.squeeze(boxes),
        np.squeeze(classes).astype(np.int32),
        np.squeeze(scores),
        category_index,
        use_normalized_coordinates=True,
        line_thickness=8,
        min_score_thresh=0.60)

My problem is, i found a video and that video tells me how to count based on scores (value of confidence). But i can't quite figure it out.

The guy in the video using this loop to count the detected objects:

# Loop over all detections and draw detection box if confidence is above minimum threshold
    for i in range (len(scores)):
        if ((scores[i] > 0.6).all() and (scores[i] <= 1.0).all()):

            current_count+=1

And print it on screen using this:

# Draw framerate, current count, and total count in corner of frame
    cv2.putText (frame,'Detections In Frame: ' + str(current_count),(30,75),cv2.FONT_HERSHEY_SIMPLEX,1,(98,189,184),2,cv2.LINE_AA)

So far, i can't update the current_count value, i'm guessing there's something wrong in the loop. So, i can't count the detected objects because it always showed 0 value. Please help me


Solution

  • Try this

    for box,score,cls in zip(boxes[0],scores[0],classes[0]):
        if score >= 0.6 and score <= 1.0:
            count += 1