问题
I'm using this code to detect green color in the image.
The problem is this iteration is really slow.
How to make it faster? If it is using numpy, How to do it in numpy way?
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:
Try simply this:
blue = rawimg[:,:,0]
green = rawimg[:,:,1]
red = rawimg[:,:,2]
exg = 2*green-red-blue
processedimg = np.where(exg > 50, exg, 0)
回答2:
I've only dabbled with numpy as a hobbyist, but I believe that you could take advantage of fromfunction which creates a new np array from an existing one https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfunction.html
Here is what I think might work in that case - which would take advantage of numpy's speed:
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
来源:https://stackoverflow.com/questions/42991524/how-to-optimize-this-image-iteration-in-numpy