如何划分轮廓?

时间:2018-12-02 16:48:49

标签: python image opencv

我想检测图像中的对象并测量它们之间的距离。只要对象距离不太近,此方法就起作用。不幸的是,图像的照明不是最佳的,因此看起来物体在触摸,尽管不是。我试图借助代表物体的线来确定距离。问题在于,一旦对象轮廓结合在一起,我就无法确定代表对象的线,因此无法计算距离。

输入图像:

enter image description here

代码:

import cv2
import numpy as np

#import image
img = cv2.imread('img.png', 0)

#Thresh
_, thresh = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)

#Finding the contours in the image
_, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

#Convert img to RGB and draw contour
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
cv2.drawContours(img, contours, -1, (0,0,255), 2)

#Object1
v = np.matrix([[0], [1]])
rect = cv2.minAreaRect(contours[0])

#determine angle
if rect[1][0] > rect[1][1]:
    ang = (rect[2] + 90)* np.pi / 180
else:
    ang = rect[2]* np.pi / 180
rot = np.matrix([[np.cos(ang), -np.sin(ang)],[np.sin(ang), np.cos(ang)]])
rv = rot*v

#draw angle line
lineSize = max(rect[1])*0.45                #length of line
p1 = tuple(np.array(rect[0] - lineSize*rv.T)[0].astype(int))
p2 = tuple(np.array(rect[0] + lineSize*rv.T)[0].astype(int))
cv2.line(img, p1, p2, (255,0,0), 2)

#Object2
if len(contours) > 1:
    rect = cv2.minAreaRect(contours[1])

    #determine angle
    if rect[1][0] > rect[1][1]:
        ang = (rect[2] + 90)* np.pi / 180
    else:
        ang = rect[2]* np.pi / 180
    rot = np.matrix([[np.cos(ang), -np.sin(ang)],[np.sin(ang), np.cos(ang)]])
    rv = rot*v

    #draw angle line
    lineSize = max(rect[1])*0.45                #length of line
    p1 = tuple(np.array(rect[0] - lineSize*rv.T)[0].astype(int))
    p2 = tuple(np.array(rect[0] + lineSize*rv.T)[0].astype(int))
    cv2.line(img, p1, p2, (255,0,0), 2)


#save output img
cv2.imwrite('output_img.png', img)

输出图像:

enter image description here

这很好用,但是当我使用具有连接轮廓的图像时,就会发生这种情况:

enter image description here enter image description here

有没有办法分割轮廓或解决方法?

修改

感谢B.M.的建议我尝试过将侵蚀作为解决方案,但不幸的是出现了新的问题。似乎不可能在侵蚀和阈值/轮廓之间找到平衡。

示例:

enter image description here enter image description here enter image description here enter image description here

5 个答案:

答案 0 :(得分:1)

您可以使用cv2.erode提供的腐蚀技术。之后

from cv2 import erode
import numpy as np    
kernel = np.ones((5,25),dtype=np.uint8) # this must be tuned 

im1=erode(im0,kernel)

您获得一张图像(im0是您的第二张图像),其中明亮区域缩小了:

enter image description here

现在,即使必须考虑侵蚀的影响,您也可以测量距离。

答案 1 :(得分:1)

如果您首先搜索轮廓并检查实际上是否有两个轮廓,该怎么办?如果只有一个,则可以制作一个循环以腐蚀并在侵蚀的图像上搜索轮廓,直到获得两个轮廓为止。当事件发生时,请制作一个黑色边框,该边框要大于侵蚀图像上使用的内核数量,并绘制“原始图像,它将物理划分并创建2个轮廓。然后将代码应用于结果图像。也许可以在处理之前上传您最困难的图像吗?希望对您有所帮助或为您提供新的想法。干杯!

示例代码:

import cv2
import numpy as np

img = cv2.imread('cont.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, threshold = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
_, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
k = 2

if len(contours)==1:
    for i in range (0,1000):
        kernel = np.ones((1,k),np.uint8)
        erosion = cv2.erode(threshold,kernel,iterations = 1)
        _, contours, hierarchy = cv2.findContours(erosion,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
        if len(contours) == 1:
            k+=1
        if len(contours) == 2:
            break
        if len(contours) > 2:
            print('more than one contour')

x,y,w,h = cv2.boundingRect(contours[0])
cv2.rectangle(threshold,(x-k,y-k),(x+w+k,y+h+k), 0, 1)
_, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cv2.drawContours(img, contours, -1, (0,0,255), 2)

#Object1
v = np.matrix([[0], [1]])
rect = cv2.minAreaRect(contours[0])

#determine angle
if rect[1][0] > rect[1][1]:
    ang = (rect[2] + 90)* np.pi / 180
else:
    ang = rect[2]* np.pi / 180
rot = np.matrix([[np.cos(ang), -np.sin(ang)],[np.sin(ang), np.cos(ang)]])
rv = rot*v

#draw angle line
lineSize = max(rect[1])*0.45                #length of line
p1 = tuple(np.array(rect[0] - lineSize*rv.T)[0].astype(int))
p2 = tuple(np.array(rect[0] + lineSize*rv.T)[0].astype(int))
cv2.line(img, p1, p2, (255,0,0), 2)

#Object2
if len(contours) > 1:
    rect = cv2.minAreaRect(contours[1])

    #determine angle
    if rect[1][0] > rect[1][1]:
        ang = (rect[2] + 90)* np.pi / 180
    else:
        ang = rect[2]* np.pi / 180
    rot = np.matrix([[np.cos(ang), -np.sin(ang)],[np.sin(ang), np.cos(ang)]])
    rv = rot*v

    #draw angle line
    lineSize = max(rect[1])*0.45                #length of line
    p1 = tuple(np.array(rect[0] - lineSize*rv.T)[0].astype(int))
    p2 = tuple(np.array(rect[0] + lineSize*rv.T)[0].astype(int))
    cv2.line(img, p1, p2, (255,0,0), 2)


#save output img

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

enter image description here

答案 2 :(得分:1)

我认为您可以采用分水岭式的二进制分割方法(为此我建议使用ITK)。 的组合:

  • 距离图计算
  • 通过扩张重建
  • 区域千里马
  • 标记的形态学分水岭 将导致以下分离: separated

完成分离后即可:

  • 提取轮廓点
  • 计算关联的多边形逼近
  • 计算两个粒子之间的精确距离 (例如,几何零件可以使用增强几何库,但这是一个c ++库)

您还可以使用纯几何/形态学方法:

  • 提取轮廓点
  • 计算关联的多边形逼近 polygonal approximation
  • 计算关联的voronoi图(可以视为形状的骨架) voronoi diagram
  • 计算与先前骨骼的每个分支相关的厚度
  • 在最小厚度部分切割 image cuts

此致

答案 3 :(得分:0)

我解决了这样的问题:

  1. 获取最后一张图片的对象的长度(如果是第一张图片,则取一个因素)
  2. 为每个对象建立两个阈值
  3. 擦除阈值以下/之上的所有内容(借助1)。基本上,我开始从对象的下边缘开始计数直到它的长度(在阈值数组中)。
  4. 进行分割并将两个对象共享为轮廓边界。
  5. 找到新轮廓。

向上计数阈值数组(对于第二个对象)以找到最低点,如下所示:

    else:
        del lineSize_list[-1], ang_list[-1]       #delete wrong values from Size and Angle lists
        z = 0
        thresh2 = np.copy(thresh)
        for x in thresh2[::-1]:                   #check threshold backwards for positive values
            for e in x:
                if e > 0:
                    break
            z += 1
            if e > 0:
                 - first positive value found in threshold (edge of object)
                 - add object length to this position
                 - make a cut in threshold (this will be the break for new contours)
                 - use threshold to find contours ....

这用于测量两个对象之间的距离。结果看起来与kavko相似。我会接受他的回答,因为他花了时间。

这是一个简化的笨拙解决方案。这只能工作,因为我可以将阈值数组切成两半。如果有一种更专业的方法来分割轮廓,那将非常棒。无论如何,非常感谢。

答案 4 :(得分:0)

您可以在唯一轮廓的所有点上应用聚类分析(例如k均值),聚类数为2。

from sklearn.cluster import KMeans

array = np.vstack(contours)
all_points = array.reshape(array.shape[0], array.shape[2])
kmeans = KMeans(n_clusters=2, random_state=0, n_init = 50).fit(all_points)
new_contours = [all_points[kmeans.labels_==i] for i in range(2)]*