我的代码为每个数字返回一个图像.e.g if x==0
然后它将创建一个图像并将其保存在特定文件夹中,但问题是数字从0到无穷大如何避免multiple if conditions
在这样的问题中。如果问题不清楚,请询问。 在这里,我只发布了两个if condition
但它正在增加。
Zero=np.zeros(shape=(100, 100),dtype=np.uint8)
count=0
count1=0
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<=32:
continue
elif count>32:
Zeroth = Image.fromarray(Zero)
Zeroth.save(os.path.join(dirs, file_+'_Zero.png'), 'png')
if labels[(x, y)]==1:
One[y][x]=int(255)
count1=count1+1
if count1<=32:
continue
elif count1>32:
First = Image.fromarray(One)
First.save(os.path.join(dirs, file_+'_First.png'),'png')
与其尝试将所有内容命名为"零"、"第一"、"第二"等,不如直接命名文件名 _1.png、_2.png、...、_31.png?它允许您使代码更简单。
temp=np.zeros(shape=(100, 100),dtype=np.uint8)
for count, (x, y) in enumerate(labels):
component = uf.find(labels[(x, y)])
labels[(x, y)] = component
temp[y][x]=int(255)
if count>32:
temp_img = Image.fromarray(temp_img)
temp_img.save(os.path.join(dirs, file_+'_' + str(labels[(x,y)]) +'.png'), 'png')
如果这不起作用,您可以使用具有所有可能性的数组或字典"零"、"第一"、"第二"、"..."、"第三十二",然后简单地使用如下名称文件:
temp.save(os.path.join(dirs, file_ + '_'+ name_arr[labels[(x,y)]] + '.png'), 'png')