如何使用循环多个如果coniditions [英] How to use loop for multiple if coniditions
问题描述
coordinate(x)
和<$ c $ 标签[(x,y)]
c>坐标(y)。标签[(x,y)]
实际上表示不同的形状图像和检测后每个形状被保存为一个不同的图像。对于每一个形状或组件,我使用多个如果条件,例如如果标签[(x,y)] == 0:#将其另存为图像
。对于每一个新的形状,但是我必须创建一个新的如果
,到目前为止我已经使用 7如果条件
。如何才能解决这个问题,只有一个条件。
pre $ 对于标签中的(x,y):
component = uf.find(labels [(x,y) ])
labels [(x,y)] = component
print(format(x)+,+ format(y)++ format(labels [(x,y)]) )
如果标签[(x,y)] == 0:
Zero [y] [x] = int(255)
count = count + 1
如果计数<= 43:
继续
elif计数> 43:
Zeroth = Image.fromarray(零)
Zeroth.save(os.path.join(dirs,如果标签[(x,y)] == 1:
一个[y] [x] = int(255)
count1 = count1 + 1
如果count1 <= 43:
continue
elif count1> 43:
First = Image.fromarray(One)
First.save os.path.join(dirs,'First.png'),'png')
解决由于 if 块遵循相同的逻辑,除了源数组(Zero,One,...)和目标f ilename(Zero.png,First.png等)。您可以将这些信息记录在键盘标签的字典中。例如:
dict = {
0:{source:Zero,file:Zero。 png},
1:{source:一个,file:First.png},#等等。
$ b然后,在循环中,只需使用:
$ p $ data = dict.get(labels [(x,y )])
if data:如果label不在字典中,数据将是None(falsy)
data [source] [y] [x] = int(255)
计数+ = 1
如果计数<= 43:
继续
elif计数> 43:
image = image.fromarray(data [source])
image.save(os.path.join(dirs,data [file]),'png')
labels[(x, y)]
returns the value at coordinate(x)
and coordinate(y)
.
labels[(x, y)]
is actually representing a different shape in the image and after detection each shape is being saved as a different image. For every shape or component I am using multiple if
conditions for example if labels[(x, y)] == 0: # save it as an image
. For every new shape however I have to create a new if
, so far i have used 7 if conditions
. How can I solve this problem with only one if condition.
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')
解决方案 Since the if
blocks follow the same logic, except for the source array (Zero, One, ...) and target filename (Zero.png, First.png, etc). You could record this information in a dictionary where keys are labels. For example:
dict = {
0: {"source": Zero, "file": "Zero.png"},
1: {"source": One, "file": "First.png"}, # and so on.
}
Then, in the loop, you just look up the label using 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')
这篇关于如何使用循环多个如果coniditions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文