如何在 numpy 中优化这个图像迭代?
How to optimize this image iteration in numpy?
我正在使用此代码检测图像中的绿色。
问题是这次迭代真的很慢。
如何让它更快?如果是用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
试试这个:
blue = rawimg[:,:,0]
green = rawimg[:,:,1]
red = rawimg[:,:,2]
exg = 2*green-red-blue
processedimg = np.where(exg > 50, exg, 0)
作为业余爱好者,我只接触过 numpy,但我相信您可以利用 fromfunction 创建一个新的来自现有数组的 np 数组 https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfunction.html
以下是我认为在这种情况下可能起作用的方法——这将利用 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
我正在使用此代码检测图像中的绿色。
问题是这次迭代真的很慢。
如何让它更快?如果是用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
试试这个:
blue = rawimg[:,:,0]
green = rawimg[:,:,1]
red = rawimg[:,:,2]
exg = 2*green-red-blue
processedimg = np.where(exg > 50, exg, 0)
作为业余爱好者,我只接触过 numpy,但我相信您可以利用 fromfunction 创建一个新的来自现有数组的 np 数组 https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfunction.html
以下是我认为在这种情况下可能起作用的方法——这将利用 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