圆检测不重叠

时间:2018-09-27 11:10:29

标签: python opencv

我想在以下条件下进行圆检测:重叠的圆将计为1个圆。

特别是,当我进行圆检测并将下面的图像的每个圆(实际上是花粉或类似圆的物体)上加上字母“ P”时 enter image description here

它变成了

enter image description here

(同一张照片,但我不知道为什么我在这里上传时变成水平的样子)

但是我只希望每个圆圈1个字母P。调整半径也许是个好主意,但是我还有很多其他照片要去,所以我希望有一种方法可以忽略重叠。

这是我的代码:

import cv2
import numpy as np


path = "./sample.JPG"
font = cv2.FONT_HERSHEY_COMPLEX



def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
    # initialize the dimensions of the image to be resized and
    # grab the image size
    dim = None
    (h, w) = image.shape[:2]

    # if both the width and height are None, then return the
    # original image
    if width is None and height is None:
        return image

    # check to see if the width is None
    if width is None:
        # calculate the ratio of the height and construct the
        # dimensions
        r = height / float(h)
        dim = (int(w * r), height)

    # otherwise, the height is None
    else:
        # calculate the ratio of the width and construct the
        # dimensions
        r = width / float(w)
        dim = (width, int(h * r))

    # resize the image
    resized = cv2.resize(image, dim, interpolation = inter)

    # return the resized image
    return resized


# In[22]:

iml = cv2.imread(path,cv2.IMREAD_COLOR)
img = image_resize(iml,width=960)


cimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cimg = cv2.medianBlur(cimg,5)

#Circle detection to detect pollen in big images, return the center's coordinates and radius of circles in array
circles = cv2.HoughCircles(cimg,cv2.HOUGH_GRADIENT,1,10,param1=15,param2=20,minRadius=10,maxRadius=25)
circles = np.uint16(np.around(circles))[0,:]


for i in circles:
     cv2.putText(img,'P',(i[0],i[1]), font, 0.5,(0,0,255),1,cv2.LINE_AA)

cv2.imwrite("./output.jpg",img)

3 个答案:

答案 0 :(得分:0)

如果我这样做,我不会使用HoughCircles,而是尝试:

1)平滑,消除一些噪音
2)阈值,以生成二进制掩码
3)轮廓,每个轮廓都是检测到的花粉。

简单,但我认为应该可以。

答案 1 :(得分:0)

我建议改用轮廓。但是,如果您确实想使用HoughCircles,请查看function中的第4个参数。改变这一点,我可以摆脱重叠。此外,我对HoughCircles函数中的canny threshold参数进行了一些调整,直到获得所需的结果。我建议在得出结论之前先了解一下参数。

代码:

import cv2
import numpy as np

arr = cv2.imread("U:/SO/032OR.jpg")
print(arr.shape)
imggray = cv2.cvtColor(arr, cv2.COLOR_BGR2GRAY)
# Not median blur 
imggray = cv2.GaussianBlur(imggray, (9,9),3)

circles_norm = cv2.HoughCircles(imggray, cv2.HOUGH_GRADIENT, 1, imggray.shape[0]/16, 
                                param1=20, param2=8, minRadius=15, maxRadius=30)
circles_norm = np.uint16(np.around(circles_norm))[0,:]

for i in circles_norm:
    center = (i[0], i[1])
    cv2.putText(arr, 'P', (i[0], i[1]), cv2.FONT_HERSHEY_COMPLEX, 0.5, 
               (0,0,255),1,cv2.LINE_AA)

结果:

Result

答案 2 :(得分:0)

  

(1)使用OTSU设置阈值,然后再次调整阈值

enter image description here

  

(2)在二值图像上找到外部轮廓,按区域过滤轮廓,然后找到minClosingCircle。

就这样:

enter image description here