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

Why does python OpenCV GUI crashes in simple video circle detection program on linux?

Snapshot of the issue 我一直在尝试检测视频中的圆圈。我检查了很多教程和 Whosebug 问题,我的代码似乎是正确的。它甚至可以正确编译。但是打开GUI需要时间window,而且一打开就崩溃。这是我的代码,有什么问题吗?

`

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 的建议, window 出现了。然而,它花了很长时间才打开,而且它不会超出视频的第一帧 screenshot of the current situation

下面是使用 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() 函数参数和圆圈检索以满足您的要求。

希望对您有所帮助。