如何在python中使用opencv计算车辆?

问题描述 投票:-1回答:1

我正在从事VCS(车辆计数系统)项目。该项目的范围是对车辆进行分类和计数。我已经在Tensorflow-object-detection-API中使用Faster-RCNN构建了一个自定义模型。该模型仅包含7类,例如汽车摩托车,自行车等。该模型运行良好,但是问题是“ COUNTING” 。视频帧中的车辆很难计数。我在互联网上进行了预研究。我试了很多但我找不到任何有用的信息。 github上有一些项目,它们使用跟踪方法。

我想要以下东西。我想在框架中画一条水平线。当车辆碰到它时,应该进行计数。怎么做。我不知道其背后的算法。我听说质心跟踪会帮助我。

我的问题是,我想在它接触水平线时计算车辆数。我已经链接了下面的示例图像。

Sample_Image

import os
import cv2
import numpy as np
import tensorflow as tf
import sys

# This is needed since the notebook is stored in 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 = 'inference_graph'
VIDEO_NAME = 'Video_105.mp4'

# 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,'training','labelmap.pbtxt')

# Path to video
PATH_TO_VIDEO = os.path.join(CWD_PATH,VIDEO_NAME)

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

# Load the label map.
# Label maps map indices to category names, so that when our convolution
# network predicts `5`, we know that this corresponds to `king`.
# 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')

# Open video file
video = cv2.VideoCapture(PATH_TO_VIDEO)

while(video.isOpened()):

    # 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
    ret, frame = video.read()
    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})


    # 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.90)

    # All the results have been drawn on the frame, so it's time to display it.
    final_score = np.squeeze(scores)    
    count = 0

    cv2.line(frame, (1144, 568), (1723,664), (0,0,255), 2) #Line 

    for i in range(100):
        if scores is None or final_score[i] > 0.90:
            min_score_thresh = 0.90

            bboxes = boxes[scores > min_score_thresh]

            im_width = video.get(cv2.CAP_PROP_FRAME_WIDTH)
            im_height = video.get(cv2.CAP_PROP_FRAME_HEIGHT)
            final_box = []
            for box in bboxes:
                ymin, xmin, ymax, xmax = box
                print("Ymin:{}:Xmin:{}:Ymax:{}Xmax{}".format(ymin*im_width,xmin*im_width,ymax*im_width,xmax*im_width))

                final_box.append([xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height])

            #print(final_box)



    cv2.imshow('Object detector', frame)


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

# Clean up
video.release()
cv2.destroyAllWindows()

opencv machine-learning image-processing computer-vision object-detection-api
1个回答
0
投票
# import the necessary packages
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
import cv2

tracker = cv2.TrackerCSRT_create()
vs = cv2.VideoCapture("Video.mp4")
initBB = None

detec = []

def pega_centro(x, y, w, h):
    x1 = int(w / 2)
    y1 = int(h / 2)
    cx = x + x1
    cy = y + y1
    return cx,cy

roi = 480
counter = 0
offset = 6

# loop over frames from the video stream
while vs.isOpened():

    ret,frame = vs.read()

    cv2.line(frame, (769 , roi), (1298 , roi), (255,0,0), 3)
    # check to see if we are currently tracking an object
    if initBB is not None:
        # grab the new bounding box coordinates of the object
        (success, box) = tracker.update(frame)

        # check to see if the tracking was a success
        if success:
            (x, y, w, h) = [int(v) for v in box]
            cv2.rectangle(frame, (x, y), (x + w, y + h),
                (0, 255, 0), 2)

            cX = int((x + x+w) / 2.0)
            cY = int((y + y+h) / 2.0)

            cv2.circle(frame, (cX, cY), 3, (0, 0, 255), -1)

            c=pega_centro(x, y, w, h)
            detec.append(c)

        for (x,y) in detec:
            if y<(roi+offset) and y>(roi-offset):
                counter+=1
                print(counter)
                cv2.line(frame, (769 , roi), (1298 , roi), (0,0,255), 3)
                detec.remove((x,y))

    # show the output frame
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("s"):
        # select the bounding box of the object we want to track (make
        # sure you press ENTER or SPACE after selecting the ROI)
        initBB = cv2.selectROI("Frame", frame, fromCenter=False,
            showCrosshair=True)

        # start OpenCV object tracker using the supplied bounding box
        # coordinates, then start the FPS throughput estimator as well
        tracker.init(frame, initBB)
        fps = FPS().start()

    # if the `q` key was pressed, break from the loop
    elif key == ord("q"):
        break

else:
    vs.release()

cv2.destroyAllWindows()

© www.soinside.com 2019 - 2024. All rights reserved.