Python 从边缘图像中提取成分并存储以供进一步处理
输入 给定一个边缘图像,我希望逐个检索其中的组件,并将每个组件存储为一个图像,以便稍后使用它进行处理。我想这就是所谓的连接组件标签 例如,在输入图像中,有2条直线、1个圆、2条曲线 我想创建5个包含这5个组件的图像文件 我能够想出如下代码,但我不知道如何进一步进行。目前,我得到的所有组件的颜色在不同的颜色输出Python 从边缘图像中提取成分并存储以供进一步处理,python,opencv,edge-detection,connected-components,Python,Opencv,Edge Detection,Connected Components,输入 给定一个边缘图像,我希望逐个检索其中的组件,并将每个组件存储为一个图像,以便稍后使用它进行处理。我想这就是所谓的连接组件标签 例如,在输入图像中,有2条直线、1个圆、2条曲线 我想创建5个包含这5个组件的图像文件 我能够想出如下代码,但我不知道如何进一步进行。目前,我得到的所有组件的颜色在不同的颜色输出 import scipy from skimage import io from scipy import ndimage import
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)
输出
新输出
这是:
然后,您将看到每个标签对应一个标签。也可以使用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)
谢谢@api55输出:对象的数量是149(我想我必须存储149个组件),只有一个像@Azhar这样的图像,这是因为您使用的是canny,而不是所有组件都相互接触。您可以尝试使用连接的组件,然后使用canny或FindOntours,这就是ZdaR建议的:)
for i in range(num):
tmp = np.zeros(labeled.shape)
tmp[labeled == i] = 255
plt.imshow(tmp)
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)