How to optimize this image iteration in numpy?

后端 未结 2 1073
余生分开走
余生分开走 2020-12-20 08:40

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 d

相关标签:
2条回答
  • 2020-12-20 09:34

    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
    
    0 讨论(0)
  • 2020-12-20 09:38

    Try simply this:

    blue = rawimg[:,:,0]
    green = rawimg[:,:,1]
    red = rawimg[:,:,2]
    exg = 2*green-red-blue
    processedimg = np.where(exg > 50, exg, 0)
    
    0 讨论(0)
提交回复
热议问题