如何在numpy中优化这个图像迭代?

时间:2017-03-24 04:41:37

标签: image-processing python opencv

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

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

如何让它更快?如果它正在使用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

1 个答案:

答案 0 :(得分:2)

我会选择这样的(未经测试):

def convertGreen(rawimg):
    red, green, blue = rawimg[:,:,0], rawimg[:,:,1], rawimg[:,:,2]
    exg = 2*green - red - blue
    processedimg = exg.copy();
    processedimg[processedimg < 50] = 0

    return processedimg

实际上可以省略复制操作,但我保持它与原始代码保持一致。

请注意,通常编程问题实际上是offtopic,更适合StackOverflow。