视频以opencv python结尾时如何停止程序 [英] how to stop the program when the video ends in opencv python

查看:148
本文介绍了视频以opencv python结尾时如何停止程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有一个小问题.现在,im正在制作一个项目,该项目使用opencv python在自行车停在斑马线时检测自行车.该程序运行得很好.但是当我运行它直到视频结束时,它会出现错误,提示"frame_ROI = frame [point1 [1]:point2 [1],point1 [0]:point2 [0]] TypeError:"NoneType"对象不可下标"

hello i have a little problem. right now im doint a project that detects bikes when they stop at zebra cross with opencv python. the program run pretty well. but when i run it until the video ends it comes with error that tells "frame_ROI = frame[point1[1]:point2[1],point1[0]:point2[0]] TypeError: 'NoneType' object is not subscriptable"

我认为,因为当我运行视频直到结束时,由于视频不再可用并且出现错误,因此在ROI区域上没有可检测到的东西.当我尝试以"q"停止视频时,没有错误提示.

i assume that because when i run the video until it ends there is nothing to detect on the ROI area because the video is no longer availabe and then comes with error. when i try to stop the video with 'q' there is no error comes out.

然后我有一个想法,如果我只是在结束之前停止视频,但我不知道如何做

and then i have an idea what if i just stop the video before it was end.but i dont know how to do it

import cv2
import numpy as np
import pygame
import datetime as dt
from pygame import mixer
import time

#=============== Variable Mouse ==================#
drawing = False
point1 = ()
point2 = ()

drawingTwo = False
pointTwo_1 = ()
pointTwo_2 = ()
Mouse_count = False
#================================================#
def mouse_drawing(event, x, y, flags, params):
    global point1, point2, drawing
    global pointTwo_1, pointTwo_2, drawingTwo, Mouse_count

    #----------Mouse 1-------
    if Mouse_count == False:
        if event == cv2.EVENT_LBUTTONDOWN:
            if drawing is False:
                drawing = True
                point1 = (x, y)
            #else:
                #drawing = False

        elif event == cv2.EVENT_MOUSEMOVE:
            if drawing is True:
                point2 = (x, y)
        elif event == cv2.EVENT_LBUTTONUP:
            drawing = False
            Mouse_count = True


            
#================================================#
lastTime = dt.datetime.now()
currentTime = dt.datetime.now()

#Make Sound
pygame.mixer.init()


#create VideoCapture object and read from video file


cap = cv2.VideoCapture('test13.mp4')

cv2.namedWindow("Detecion motor")
cv2.setMouseCallback("Detecion motor", mouse_drawing)

while True:
    ret, frame = cap.read()
    car_cascade = cv2.CascadeClassifier('cascade11.xml')

    #============================== ROI One ============================#
    if point1 and point2:

        #Rectangle marker
        r = cv2.rectangle(frame, point1, point2, (200, 100, 400), 5)
        frame_ROI = frame[point1[1]:point2[1],point1[0]:point2[0]]

        #------------------Detect car ROI-------------------#
        if drawing is False:
            #convert video into gray scale of each frames
            ROI_grayscale = cv2.cvtColor(frame_ROI, cv2.COLOR_BGR2GRAY)
            #detect cars in the video
            cars_ROI = car_cascade.detectMultiScale(ROI_grayscale, 1.1, 3)
            if len(cars_ROI) > 0:
                if (currentTime - lastTime).seconds > 20:
                    lastTime = dt.datetime.now()
                    sound = mixer.Sound('sirine2.wav')
                    sound.play()

            for (x, y, w, h) in cars_ROI:
                cv2.rectangle(frame_ROI, (x, y), (x + w, y + h), (0, 255, 0), 2)
                currentTime = dt.datetime.now()
                # cv2.putText(frame_ROI, "Jumlah Motor : " + str(cars_ROI.shape[0]), (10,frame_ROI.shape[0] -25), cv2.FONT_HERSHEY_TRIPLEX, 0.5,(0,255,0), 1)
            # -------------------------------------------------#

    #============================== ROI Two ============================#

    #==================================================================#
    cv2.imshow("Detecion motor", frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
         break

cap.release()
cv2.destroyAllWindows()


!!!and the error is

Traceback (most recent call last):
  File "D:/Skripsi/CarDetection-master/DeteksiMotor.py", line 65, in <module>
    frame_ROI = frame[point1[1]:point2[1],point1[0]:point2[0]]
TypeError: 'NoneType' object is not subscriptable

推荐答案

在此行中使用ret

ret, frame = cap.read() # ret denotes whether frame obtained or not

引入一个循环while(ret):,然后将car_cascade中的所有代码放入该循环中的break语句.在while循环结束之后,放置一个break语句.阅读循环末尾的框架.我已经在您的代码中进行了必要的更改,请签出.

Introduce a loop while(ret): and put all your code from car_cascade to the break statement in that loop. After this while loop ends put a break statement. Read the frames at the end of the loop. I've made the required changes in your code Check it out.

import cv2
import numpy as np
import pygame
import datetime as dt
from pygame import mixer
import time

#=============== Variable Mouse ==================#
drawing = False
point1 = ()
point2 = ()

drawingTwo = False
pointTwo_1 = ()
pointTwo_2 = ()
Mouse_count = False
#================================================#
def mouse_drawing(event, x, y, flags, params):
    global point1, point2, drawing
    global pointTwo_1, pointTwo_2, drawingTwo, Mouse_count

    #----------Mouse 1-------
    if Mouse_count == False:
        if event == cv2.EVENT_LBUTTONDOWN:
            if drawing is False:
                drawing = True
                point1 = (x, y)
            #else:
                #drawing = False

        elif event == cv2.EVENT_MOUSEMOVE:
            if drawing is True:
                point2 = (x, y)
        elif event == cv2.EVENT_LBUTTONUP:
            drawing = False
            Mouse_count = True


            
#================================================#
lastTime = dt.datetime.now()
currentTime = dt.datetime.now()

#Make Sound
pygame.mixer.init()


#create VideoCapture object and read from video file


cap = cv2.VideoCapture('test13.mp4')

cv2.namedWindow("Detecion motor")
cv2.setMouseCallback("Detecion motor", mouse_drawing)
while True:
    ret, frame = cap.read()
    while(ret):
        
        car_cascade = cv2.CascadeClassifier('cascade11.xml')

        #============================== ROI One ============================#
        if point1 and point2:

            #Rectangle marker
            r = cv2.rectangle(frame, point1, point2, (200, 100, 400), 5)
            frame_ROI = frame[point1[1]:point2[1],point1[0]:point2[0]]

            #------------------Detect car ROI-------------------#
            if drawing is False:
                #convert video into gray scale of each frames
                ROI_grayscale = cv2.cvtColor(frame_ROI, cv2.COLOR_BGR2GRAY)
                #detect cars in the video
                cars_ROI = car_cascade.detectMultiScale(ROI_grayscale, 1.1, 3)
                if len(cars_ROI) > 0:
                    if (currentTime - lastTime).seconds > 20:
                        lastTime = dt.datetime.now()
                        sound = mixer.Sound('sirine2.wav')
                        sound.play()

                for (x, y, w, h) in cars_ROI:
                    cv2.rectangle(frame_ROI, (x, y), (x + w, y + h), (0, 255, 0), 2)
                    currentTime = dt.datetime.now()
                    # cv2.putText(frame_ROI, "Jumlah Motor : " + str(cars_ROI.shape[0]), (10,frame_ROI.shape[0] -25), cv2.FONT_HERSHEY_TRIPLEX, 0.5,(0,255,0), 1)
                # -------------------------------------------------#

        #============================== ROI Two ============================#

        #==================================================================#
        cv2.imshow("Detecion motor", frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
             break
        ret, frame = cap.read()
    break

    cap.release()
    cv2.destroyAllWindows()

这篇关于视频以opencv python结尾时如何停止程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆