如何对多个if条件使用循环

2024-04-26 01:18:28 发布

您现在位置:Python中文网/ 问答频道 /正文

labels[(x, y)]返回coordinate(x)coordinate(y)处的值。
labels[(x, y)]实际上代表图像中的一个不同形状,在检测到每个形状后,将保存为一个不同的图像。对于每个形状或组件,我使用多个if条件,例如if labels[(x, y)] == 0: # save it as an image。但是,对于每个新形状,我都必须创建一个新的if,到目前为止,我已经使用了7 if conditions。只有一个if条件如何解决这个问题。你知道吗

for (x, y) in labels:
    component = uf.find(labels[(x, y)])
    labels[(x, y)] = component
    print (format(x) +","+ format(y)+ " " +format(labels[(x, y)]))

    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')

Tags: 图像formatcoordinatelabelsifpngsavecount
1条回答
网友
1楼 · 发布于 2024-04-26 01:18:28

因为if块遵循相同的逻辑,除了源数组(0,1,…)和目标文件名(零.png, 第一.png等)。您可以将这些信息记录在以键为标签的词典中。例如:

dict = {
        0: {"source": Zero, "file": "Zero.png"},
        1: {"source": One, "file": "First.png"},    # and so on. 
       }

然后,在循环中,您只需使用dict.get查找标签:

data = dict.get(labels[(x, y)])
if data:     # data will be None (falsy) if label isn't in the dictionary   
    data["source"][y][x] = int(255)
    count += 1
    if count <= 43:
        continue
    elif count > 43:
        image = Image.fromarray(data["source"])
        image.save(os.path.join(dirs, data["file"]), 'png')

相关问题 更多 >