Python Opencv使用霍夫圆变换从二进制图像中检测圆

Posted

技术标签:

【中文标题】Python Opencv使用霍夫圆变换从二进制图像中检测圆【英文标题】:Python Opencv Detecting Circles from the Binary Image by Using Hough Circle Transform 【发布时间】:2018-11-09 10:15:19 【问题描述】:

我正在尝试将应用阈值的视频分割成帧,然后尝试在图像中找到圆圈。但是我搜索到将二进制图像转换为灰度是不可能的。我搜索了霍夫圆,该方法只能拍摄灰度图像。霍夫线可以处理二值图像,但霍夫圆不能。在霍夫圆法中使用阈值图像有什么建议吗?请帮我。

ps:我正在添加代码和图像,目的是在阈值图像中找到圆圈。

while videoCapture.isOpened(): #Begins to detect the captures in video by frames

    ret, image = videoCapture.read()
    print("image capture opened")

    if ret == True:

        #rgb = cv2.cvtColor(image, cv2.COLOR_HLS2RGB)
        gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
        bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) #converting video color to gray

        print("gray scaled image\n")
        frameCounter = frameCounter + 1
        circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=71, param2=70, minRadius=0, maxRadius=0)
        if circles is not None:

            print("Hough Circle on each frame")
            circles = np.uint16(np.around(circles))
            for i in circles[0, :]:
                cv2.circle(bgr, (i[0],i[1]), i[2], (0, 255, 0), 2) #Outer circle in the image
                cv2.circle(bgr, (i[0],i[1]), 2, (0, 0, 255), 3) #inner circle center
                print("inner outer circle draw")

            cv2.imwrite(outputDir + "/%d.jpg" % (frameCounter), bgr) #Saving frame to the output directory
        else :
            print('Circle could not find')
            cv2.imwrite(outputDir + "/%d.jpg" % (frameCounter), bgr)  # Saving frame to the output directory

        print("image saved to directory")

        videoOutput.write(bgr)

        if(frameCounter > (frameLength-1)):
            endTime = time.time()
            videoCapture.release()
            videoOutput.release()
            print("Converting video took %d seconds." % (endTime-startTime))
            break
    else:
       break

【问题讨论】:

【参考方案1】:

尝试使用 convertTo 而不是 cvtColor。这个例子有效:

cv::Mat image = imread("binary.bmp");
cv::Mat outImage;
image.convertTo(outImage, CV_8U);
imwrite("grayscale.bmp", outImage);

P.S.:您仍然需要使用 HoughCircles 的 param1 和 param2 参数,具体取决于您要检测的圆圈的“圆形”程度,在您的情况下,它确实不是一个完美的圆圈。开始在图像中检测硬币进行练习会容易得多。

【讨论】:

嗯...我误解了你所说的二进制图像是什么意思吗? 感谢您的回答。我找到了一种使用 2 个 for 循环应用阈值的方法,因此我不再将图像格式更改为二进制。再次感谢我通过这种方式搜索并学到了很多东西。

以上是关于Python Opencv使用霍夫圆变换从二进制图像中检测圆的主要内容,如果未能解决你的问题,请参考以下文章

python - OpenCV 霍夫圆变换检测球体

学习 opencv---(13)opencv霍夫变换:霍夫线变换,霍夫圆变换

使用 OpenCV(基于霍夫变换或其他特征)编写鲁棒的(颜色和大小不变)圆检测

OpenCV 霍夫变换——圆

20opencv入门霍夫变换:霍夫线变换,霍夫圆变换合辑

Python+opencv 机器视觉 - 基于霍夫圈变换算法检测图像中的圆形实例演示