为什么python OpenCV GUI在Linux上的简单视频圈检测程序崩溃?

时间:2017-05-05 19:17:47

标签: python opencv computer-vision geometry hough-transform

Snapshot of the issue我一直试图检测视频中的圈子。我检查了很多教程和stackoverflow问题,我的代码似乎是正确的。它甚至可以正确编译。但是,打开GUI窗口需要一些时间,一旦打开,它就会崩溃。这是我的代码有什么问题吗?

`

import cv2
import numpy as np

cap  = cv2.VideoCapture('Red Motion Spin Looping Motion Background.mp4')
while (cap.isOpened()):
    ret,img = cap.read()
    img = cv2.medianBlur(img,5) 
    cimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    circles = cv2.HoughCircles(cimg,cv2.HOUGH_GRADIENT,1,20,
                            param1=50,param2=30,minRadius=0,maxRadius=0)

    circles = np.uint16(np.around(circles))
    for i in circles[0,:]:
            # draw the outer circle
            cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
            # draw the center of the circle
            cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

    cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

` 更新:我听了@Micka的建议,窗口出现了。然而,它需要永远打开,它不会超出视频的第一帧screenshot of the current situation

1 个答案:

答案 0 :(得分:0)

以下是使用Python 2.7.12OpenCV3.2.0测试的可行代码。

import numpy as np
import cv2

capture = cv2.VideoCapture("001.mp4")
#capture = cv2.VideoCapture(0)

while capture.isOpened():
    # grab the current frame and initialize the status text
    grabbed, frame = capture.read()

    if frame is not None:
        # convert the frame to grayscale, blur it, and detect circles
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        blur = cv2.medianBlur(gray,5) 
        circles = cv2.HoughCircles(blur,cv2.HOUGH_GRADIENT,1,20, \
                                   param1=50,param2=30,minRadius=0,maxRadius=0)

        if circles is not None:
            # convert the (x, y) coordinates and radius of the circles to integers
            circles = np.round(circles[0, :]).astype("int")
            #circles = np.uint16(np.around(circles[0,:]))

            # loop over the (x, y) coordinates and radius of the circles
            for (x, y, r) in circles:
                # draw the circle in the output image, then draw a rectangle
                # corresponding to the center of the circle
                cv2.circle(frame, (x, y), r, (255, 0, 255), 2)

            # show the frame and record if a key is pressed
            cv2.imshow("Frame", frame)
            # if the 'q' key is pressed, stop the loop
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

capture.release()
cv2.destroyAllWindows()


主要的变化是for (x, y, r) in circles:循环来获取和绘制圆圈。添加cv2.medianBlur()后视频播放有点慢。通过cv2.HoughCircles()检测,它甚至进一步放慢了速度。

以下是圈子视频播放的屏幕截图。假设您可能需要修改cv2.HoughCircles()函数参数和圆圈检索以满足您的要求。

enter image description here

希望得到这个帮助。