Python cv2边缘和轮廓检测

时间:2018-03-12 13:12:23

标签: python opencv

我正试图在OMR表上检测气泡,看起来像这样:

Raw image

边缘检测和轮廓显示的代码参考here。但是,在找到实际轮廓之前,我试图检测边缘,但不知何故无法设置正确的参数值。 这就是我得到的:

edged

代码:

from imutils.perspective import four_point_transform
from imutils import contours
import numpy as np
import argparse
import imutils
import cv2

def auto_canny(image, sigma=0.50):
    # compute the median of the single channel pixel intensities
    v = np.median(image)

    # apply automatic Canny edge detection using the computed median
    lower = int(max(0, (1.0 - sigma) * v))
    upper = int(min(255, (1.0 + sigma) * v))
    edged = cv2.Canny(image, lower, upper)


# return the edged image
return edged

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
    help="path to the input image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])

r = 500.0 / image.shape[1]
dim = (500, int(image.shape[0] * r))

# perform the actual resizing of the image and show it
image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
equalized_img =  cv2.equalizeHist(gray)
cv2.imshow('Equalized', equalized_img)
# cv2.waitKey(0)
blurred = cv2.GaussianBlur(equalized_img, (7, 7), 0)
# edged =cv2.Canny(equalized_img, 30, 160)
edged = auto_canny(blurred)

cv2.imshow('edged', edged)
cv2.waitKey(0)

如何获得所有90 * 4圈?

2 个答案:

答案 0 :(得分:1)

您应该使用Hough搜索圈子。此方法将每个白色像素投影为圆形,并尝试获得尽可能多的重叠像素。您必须指定在图像中找到的圆的预测半径。

Hough projects every white pixel on circles within specified radi

  • 左 - 原始图像
  • 右上角 - 每个白色像素都投影为红色圆圈 - 它们太小而无法找到相交点
  • 右下角 - 绿色圆圈较大,所有相交点恰好在圆圈中间相交!半径和位置均由cvHoughCircles
  • 返回

这个人使用cvHoughCirclescvCanny化图像(读取OP更新)来处理blob检测(这就是我认为正在寻找圈子的方法)。

OpenCV: Error in cvHoughCircles usage

答案 1 :(得分:0)

您需要改善轮廓检测。 最终,通过不进行更改,而是通过对早期阶段进行更好的预处理。 轮廓检测在图像中具有更多对比度和颜色分离的情况下效果更好。如果您还不需要使用简单阈值,自适应或Otsu等更智能的技术来阈值图像。选中打开CV文档here

此外,对于您的情况,最终需要诸如here所述的更高级的技术,例如“使用积分图像的自适应阈值处理”。