gpt4 book ai didi

python - 将连接的组件分离到多个图像

转载 作者:太空宇宙 更新时间:2023-11-03 22:39:17 25 4
gpt4 key购买 nike

我有this一种白色和黑色图像,我想将每个白色形状保存为适合形状大小的图像。

我正在使用 connectedComponentsWithStats() 来标记连接的区域,然后我使用一个包围该区域的矩形来提取它并将其分开保存。

img = imread('shapes.png', IMREAD_GRAYSCALE)
_ , img = threshold(img,120,255,THRESH_BINARY)
n_labals, labels, stats, centroids = connectedComponentsWithStats(img)
for label in range(1,n_labals):
width = stats[label, CC_STAT_WIDTH]
height = stats[label, CC_STAT_HEIGHT]
x = stats[label, CC_STAT_LEFT]
y = stats[label, CC_STAT_TOP]
roi = img[y-5:y + height+5, x-5:x + width+5]
pyplot.imshow(roi,cmap='gray')
pyplot.show()

但是,这样我在形状之间有一些交叉点,如图所示 here

我想将每个连接的区域保存到一个单独的图像中,没有任何交集,如图所示 here


更新

我拿了一个矩形覆盖感兴趣的区域然后我 ommoted 其他标签

img = imread('shapes.png', IMREAD_GRAYSCALE)
_ , img = threshold(img,120,255,THRESH_BINARY)
n_labals, labels, stats, centroids = connectedComponentsWithStats(img)
for label in range(1,n_labals):
width = stats[label, CC_STAT_WIDTH]
height = stats[label, CC_STAT_HEIGHT]
x = stats[label, CC_STAT_LEFT]
y = stats[label, CC_STAT_TOP]
roi = labels[y-1:y + height+1, x-1:x + width+1].copy() # create a copy of the interest region from the labeled image
roi[ roi != label] = 0 # set the other labels to 0 to eliminate untersections with other labels
roi[ roi == label] = 255 # set the interest region to white
pyplot.imshow(roi,cmap='gray')
pyplot.show()

最佳答案

来自this post的接受答案详细介绍函数 connectedComponentsWithStats:

Labels is a matrix the size of the input image where each element has a value equal to its label.

因此,这意味着对象 1 的所有像素都具有值 1,对象 2 的所有像素都具有值 2,依此类推。

我建议您使用 regionprops 来解决您的问题这在 skimage 中实现(这对于 python 中的图像处理非常有用)

您可以使用 pip 或 conda 安装它,详见 here

因此,对整数数组调用 regionprops 将返回一个生成器列表,这些生成器几乎可以计算出您可能希望得到的所有基本对象属性。具体来说,您要创建的图像可以通过“filled_image”访问:

import numpy as np
from skimage.measure import regionprops

# generate dummy image:
labels = np.zeros((100,100), dtype=np.int) # this does not work on floats
# adding two rectangles, similar to output of your label function
labels[10:20, 10:20] = 1
labels[40:50, 40:60] = 2

props = regionprops(labels)
print(type(props))

现在,我们可以遍历列表中的每一项:

for prop in props:
print(prop['label']) # individual properties can be accessed via square brackets
cropped_shape = prop['filled_image'] # this gives you the content of the bounding box as an array of bool.
cropped_shape = 1 * cropped_shape # convert to integer
# save image with your favourite imsave. Data conversion might be neccessary if you use cv2

关于python - 将连接的组件分离到多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55730084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com