Как посчитать транспортные средства, используя opencv в python? - PullRequest
0 голосов
/ 30 октября 2019

Я работаю над проектом VCS (система подсчета транспортных средств). Целью проекта является классификация и подсчет транспортных средств. Я построил пользовательскую модель с использованием Faster-RCNN в Tensorflow-object-Detection-API. Эта модель содержит только 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()

1 Ответ

0 голосов
/ 31 октября 2019
# 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()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...