我正在使用此代码检测图像中的绿色。
问题是这个迭代真的很慢。
如何让它更快?如果它正在使用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
答案 0 :(得分:4)
试试这个:
blue = rawimg[:,:,0]
green = rawimg[:,:,1]
red = rawimg[:,:,2]
exg = 2*green-red-blue
processedimg = np.where(exg > 50, exg, 0)
答案 1 :(得分:1)
我只讨论numpy作为业余爱好者,但我相信你可以利用 fromfunction 从现有的{n>数组创建一个新的np数组{{ 3}}
以下是我认为在这种情况下可能会起作用的 - 这将利用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