从边缘图像中提取组件并存储以供进一步处理

Extracting components from an edge image and storing for further processing

1输入

给定一张边缘图像,我想一个一个地检索其中的组件,并将每个组件存储为图像,以便以后使用它进行处理。我想这就是所谓的连接组件标签。

比如输入图片中有2条直线,1个圆,2条曲线 我想要包含这 5 个组件的 5 个图像文件。

我能够想出如下代码,但我不知道如何进一步进行。目前我在输出中得到了不同颜色的所有组件。

      import scipy
      from skimage import io
      from scipy import ndimage
      import matplotlib.pyplot as plt
      import cv2
      import numpy as np

    fname='..//Desktop//test1.png'
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    #canny
   img_canny = cv2.Canny(img,100,200)

   threshold = 50

   # find connected components
   labeled, nr_objects = ndimage.label(img_canny) 
   print('Number of objects is %d'% nr_objects)

   plt.imsave('..//Desktop//out.png', labeled)

输出

新输出

这个:

   num=nr_objects
   i=0
   while i<num:
      plt.imshow(labeled)
      i=i+1

不会遍历不同的标签,它只会显示相同的图像 num 次。您需要执行以下操作:

   for i in range(num):
      tmp = np.zeros(labeled.shape)
      tmp[labeled == i] = 255
      plt.imshow(tmp)

然后您会看到每个标签对应一个。您也可以使用 for 循环...如果您有任何问题,请发表评论。

您可能不需要使用 cv2.canny() 来分割轮廓,您可以简单地使用二进制阈值技术作为:

img = cv2.imread("/path/to/img.png")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img_gray, 130, 255, cv2.THRESH_BINARY_INV)

# Opencv v3.x
im, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for i in xrange(len(contours)):
    rect = cv2.boundingRect(contours[i])
    contour_component = img[rect[1]:rect[1] + rect[3], rect[0]:rect[0] + rect[2]]

    cv2.imwrite("component_{}.png".format(i), contour_component)