【问题标题】:How to optimize this image iteration in numpy?如何在 numpy 中优化此图像迭代?
【发布时间】:2017-08-16 22:06:20
【问题描述】:

我正在使用此代码来检测图像中的绿色。

问题是这个迭代真的很慢。

如何让它更快?如果是使用 numpy,如何使用 numpy 的方式呢?

def convertGreen(rawimg):
    width, height, channels = rawimg.shape
    size = (w, h, channels) = (width, height, 1)
    processedimg = np.zeros(size, np.uint8)
    for wimg in range(0,width):
        for himg in range(0,height):
            blue = rawimg.item(wimg,himg,0)
            green = rawimg.item(wimg,himg,1)
            red = rawimg.item(wimg,himg,2)
            exg = 2*green-red-blue
            if(exg > 50):
                processedimg.itemset((wimg,himg,0),exg)

    return processedimg

【问题讨论】:

    标签: python opencv numpy image-processing opencv3.0


    【解决方案1】:

    试试这个:

    blue = rawimg[:,:,0]
    green = rawimg[:,:,1]
    red = rawimg[:,:,2]
    exg = 2*green-red-blue
    processedimg = np.where(exg > 50, exg, 0)
    

    【讨论】:

    • 太好了,您完全避免使用for 循环!!
    • 我收到了这个错误。 exg = 2*green-red-blue ueError: 操作数无法与形状一起广播 (480,640) (480,2,3)
    • 哎呀错字!查看编辑(red 定义中缺少最后一个逗号)
    【解决方案2】:

    我只是作为业余爱好者涉足过 numpy,但我相信您可以利用 fromfunction 从现有的 @987654321 创建一个新的 np 数组@

    这是我认为在这种情况下可能有效的方法 - 这将利用 numpy 的速度:

    def handle_colors(img, x, y):
        blue = img.item(x,y,0)
        green = img.item(x,y,1)
        red = img.item(x,y,2)
        exg = 2*green-red-blue
        if exg > 50:
            return (exg, green, red)
        return blue, green, red
    
    def convertGreen(rawimg):
        processedimg = np.fromfunction(lambda i, j: handle_colors(rawimg, i, j), rawimg.shape)
        return processedimg
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 2017-06-28
      • 2017-09-19
      • 1970-01-01
      • 2011-04-09
      • 1970-01-01
      相关资源
      最近更新 更多