两遍连通分量算法正在检测一幅图像中的单独分量,每次检测后我都会保存每个component
作为不同的图像。要显示每个component
在单独的图像上,我使用多个 if 条件,但是这些if conditions
每当图像中每个组件都有很多形状时,它就会增加,到目前为止我已经使用了 7 个 if 条件,但它正在增加。任何关于如何使用循环或如何处理它的想法。
for (x, y) in labels:
component = uf.find(labels[(x, y)])
labels[(x, y)] = component
############################################################
if labels[(x, y)]==0:
Zero[y][x]=int(255)
count=count+1
if count<=43:
continue
elif count>43:
Zeroth = Image.fromarray(Zero)
Zeroth.save(os.path.join(dirs, 'Zero.png'), 'png')
#############################################################
if labels[(x, y)]==1:
One[y][x]=int(255)
count1=count1+1
if count1<=43:
continue
elif count1>43:
First = Image.fromarray(One)
First.save(os.path.join(dirs, 'First.png'),'png')
我不确定我完全理解你的代码,但我认为可能有一个简单的方法可以解决你的变量过多和if
声明。您不应使用单独的变量和代码来保存每个图像,而应将它们放入列表中并为这些列表建立索引以获取要更新和保存的值。
以下是您的代码的查找方式:
# at some point above, create an "images" list instead of separate Zero, One, etc variables
# also create a "counts" list instead of count, count1, etc
for (x, y) in labels:
component = uf.find(labels[(x, y)])
labels[(x, y)] = component
# optionally, add code here to create a new image if needed
images[component][y][x] = 255 # update image
counts[component] += 1 # update count
if counts[component] > 43: # if count is high enough, save out image
img = images[component] = Image.fromarray(Zero)
img.save(os.path.join(dirs, 'image{:02d}.png'.format(component), 'png')
请注意,您需要以编程方式生成图像文件名,因此而不是Zero.png
and One.png
等等,我去了image00.png
and image01.png
。如果您想保持相同的名称系统,您可能可以创建从数字到英文名称的映射,但我怀疑使用数字无论如何都会更方便您以后的使用。
如果您不知道提前需要多少图像和计数,您可以向循环添加一些额外的逻辑,根据需要创建新的图像,并将它们附加到images
and counts
列表。我在上面的代码中添加了一条注释,显示了您想要该逻辑的位置。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)