【问题标题】:How can I count how many apple or banana that detected by camera?如何计算相机检测到的苹果或香蕉数量?
【发布时间】:2020-07-30 03:27:06
【问题描述】:

我找到了这段代码。该程序使用 TensorFlow 分类器来执行对象检测和计数。

它在来自 picamera 的每一帧中围绕感兴趣的对象绘制框和分数。

它还使用一个变量来计算编号。框架中的对象。 如何更改代码以计算相机检测到的目标对象,例如香蕉和苹果?

######## Object counting using tensorflow on picamera #########
# Author: Vineeth Rajendran
# Date: 4/1/19
# Description: 
# This program uses a TensorFlow classifier to perform object detection and counting.
# It draws boxes and scores around the objects of interest in each frame from the picamera.
# IT also uses a variable for counting the no. of objects in the frame.

## Some of the code is copied from Evan Juras example at
## https://github.com/EdjeElectronics/TensorFlow-Object-Detection-on-the-Raspberry-Pi/blob/master/Object_detection_picamera.py


# Import packages
import os
import cv2
import numpy as np
from picamera.array import PiRGBArray
from picamera import PiCamera
import tensorflow as tf
import argparse
import sys

# Set up camera constants
IM_WIDTH = 1280
IM_HEIGHT = 720
#IM_WIDTH = 640    Use smaller resolution for
#IM_HEIGHT = 480   slightly faster framerate

# Select camera type (if user enters --usbcam when calling this script,
# a USB webcam will be used)
camera_type = 'picamera'
parser = argparse.ArgumentParser()
parser.add_argument('--usbcam', help='Use a USB webcam instead of picamera',
                    action='store_true')
args = parser.parse_args()
if args.usbcam:
    camera_type = 'usb'

# This is needed since the working directory is the object_detection folder.
sys.path.append('..')

# Import utilites
from utils import label_map_util
from utils import visualization_utils as vis_util

# Name of the directory containing the object detection module we're using
MODEL_NAME = 'ssdlite_mobilenet_v2_coco_2018_05_09'

# Grab path to current working directory
CWD_PATH = os.getcwd()

# Path to frozen detection graph .pb file, which contains the model that is used
# for object detection.
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,'data','mscoco_label_map.pbtxt')

# Number of classes the object detector can identify
NUM_CLASSES = 90

## Load the label map.
# Label maps map indices to category names, so that when the convolution
# network predicts `5`, we know that this corresponds to `airplane`.
# Here we use internal utility functions, but anything that returns a
# dictionary mapping integers to appropriate string labels would be fine
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

# Load the Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

    sess = tf.Session(graph=detection_graph)


# Define input and output tensors (i.e. data) for the object detection classifier

# 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')

# Number of objects detected
num_detections = detection_graph.get_tensor_by_name('num_detections:0')

# creating a fucntion 
def object_counting()
    # Initialize Picamera and grab reference to the raw capture
    camera = PiCamera()
    camera.resolution = (IM_WIDTH,IM_HEIGHT)
    camera.framerate = 10
    rawCapture = PiRGBArray(camera, size=(IM_WIDTH,IM_HEIGHT))
    rawCapture.truncate(0)

    for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):

        totalcount=0

        # Acquire frame and expand frame dimensions to have shape: [1, None, None, 3]
        # i.e. a single-column array, where each item in the column has the pixel RGB value
        frame = np.copy(frame1.array)
        frame.setflags(write=1)
        frame_expanded = np.expand_dims(frame, axis=0)

        # Perform the actual detection by running the model with the image as input
        (boxes, scores, classes, num) = sess.run(
            [detection_boxes, detection_scores, detection_classes, num_detections],
            feed_dict={image_tensor: frame_expanded})

        # Visualizing the results of the detection
        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.40)

          # Updating totalcount
        totalcount=totalcount+num

          # Displaying the number of objects detected using the totalcount variable
        cv2.putText(frame,"Count"+str(totalcount) ,(10, 35),font,0.8,(0, 0xFF, 0xFF),2,cv2.FONT_HERSHEY_SIMPLEX,)

        # All the results have been drawn on the frame, so it's time to display it.
        cv2.imshow('Object detector', frame)

        # Press 'q' to quit
        if cv2.waitKey(1) == ord('q'):
            break

        rawCapture.truncate(0)

    camera.close()

cv2.destroyAllWindows()

object_counting()

【问题讨论】:

    标签: python opencv tensorflow object-detection counting


    【解决方案1】:

    上面的代码使用来自 TF Object Detection API 的模型。 该模型在名为 COCO (http://cocodataset.org/#home) 的数据集上进行了训练 该数据集包含许多通用类(总共 80 个用于检测的类),您可以找出脚本调用的标签文件中存在哪些类:

    # Path to label map file
    PATH_TO_LABELS = os.path.join(CWD_PATH,'data','mscoco_label_map.pbtxt')
    

    你会看到很多类(人、汽车、公共汽车、狗……),甚至是“橙色”和“香蕉”。 因此,当您编写脚本计算检测器检测到的对象数量时,您只对特定的类(标签)感兴趣:

    231 item {
    232   name: "/m/09qck"
    233   id: 52
    234   display_name: "banana"
    235 }
    ...
    246 item {
    247   name: "/m/0cyhj_"
    248   id: 55
    249   display_name: "orange"
    250 }
    

    所以,52 类是香蕉,55 类是橙色。

    剩下要做的就是从以下几行中获取结果:

    # Perform the actual detection by running the model with the image as input
    (boxes, scores, classes, num) = sess.run(
        [detection_boxes, detection_scores, detection_classes, num_detections],
        feed_dict={image_tensor: frame_expanded})
    

    查看您生成的,并计算 52 出现了多少次以及 55 出现了多少次。 (一个简单的命令,如:numpy.sum(classes == 52) 应该可以解决问题)

    【讨论】:

    • 好的,兄弟,我知道了,但是计算这些特定类的代码是什么?
    猜你喜欢
    • 2014-08-31
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 2015-01-28
    • 2012-08-01
    • 2017-11-22
    • 1970-01-01
    相关资源
    最近更新 更多