【问题标题】:Optimization : How to improve if statement?优化:如何改进 if 语句?
【发布时间】:2018-04-27 09:27:15
【问题描述】:

我有多个图像,其中包含一个形状。我想把这个形状装箱,以便以后裁剪这些图像。我希望每个图像都有相同的裁剪框(形状之间的坐标变化不大)。

我得到了这段代码:

from PIL import Image
import glob
import numpy as np

def Region():

    path = glob.glob('label/*.tif')
    L = [640,640,0,0]
    for img_name in path:
        x = []
        y = []
        img = Image.open(img_name)
        pic = np.array(img)

        for index, lit in enumerate(pic):
            for indox, value in enumerate(lit):
                if value == 0:
                    y.append(index)
                    x.append(indox)

        if min(y) < L[0]:
            L[0]=min(y)
        if min(x) < L[1]:
            L[1]=min(x)
        if max(y) > L[2]:
            L[2]=max(y)
        if max(x) > L[3]:
            L[3]=max(x)

   print L

它给了我这个输出 [298, 258, 424, 386],这与我想要的非常吻合。 但是很好我需要处理大量数据,我相信可能有更好的方法来做到这一点。

由于我是编程新手,我想知道是否有更好的方法来完成这项任务。

有什么建议吗?

非常感谢,

问候

编辑:如果语句 L[3] ':'

【问题讨论】:

  • 您最后的if 语句缺少: 以及当它为真时要执行的语句。
  • 别介意我的第一条评论,我没有注意到index 和indox 之间的区别。您应该使用更好的变量名称,例如 x_index 和 y_index。
  • 关于改进编码风格的问题更适合Code Review
  • @Barmar 确实我不知道,谢谢。是的,我的代码中的 if 语句是正确的,因为它产生了我想要的输出。谢谢你。我的意思是有没有更好的方法来放置这些 if 语句?
  • 您可以在for 循环期间确定最小值和最大值,而不是作为单独的步骤进行。

标签: python if-statement optimization


【解决方案1】:

您可以在循环期间而不是在循环之后确定最小值和最大值。

    for index, lit in enumerate(pic):
        for indox, value in enumerate(lit):
            if value == 0:
                if index < L[0]:
                    L[0] = index
                if indox < L[1]:
                    L[1] = indox
                if index > L[2]:
                    L[2] = index
                if indox > L[3]:
                    L[3] = indox

【讨论】:

  • 确实!非常感谢 !您还有其他建议吗?
  • 可能有一种方法可以利用 numpy 或 pandas 直接从数组中获取零元素的最小和最大索引,而不是循环。但我对这些模块还不够了解。
猜你喜欢
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 2021-11-28
  • 2011-05-18
  • 2010-09-07
相关资源
最近更新 更多