【问题标题】:How to use loop for multiple if coniditions如何对多个if条件使用循环
【发布时间】:2017-12-25 13:55:43
【问题描述】:

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

【问题讨论】:

  • 它使用两遍连通分量算法来检测图像中的分量,因此 uf 是数组文件,标签位于每个坐标 x 和坐标 y 上,该值称为标签,因此“==0”表示一个标记为“0”的形状,依此类推
  • 你能解决吗

标签: python numpy for-loop if-statement python-imaging-library


【解决方案1】:

由于if 块遵循相同的逻辑,除了源数组(零、一、...)和目标文件名(零.png、First.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')

【讨论】:

    猜你喜欢
    • 2015-09-28
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2012-06-16
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    相关资源
    最近更新 更多