Simplest way to replace a color

asked 2014-01-31 07:36:46 -0500

Franksm gravatar image

I'm trying to change a color to another in a given image.

I'm getting quite good performace with "Solution 1", but maybe there is a simplest (and also an as fast way) to get the same results with SimpleCV.

Solution 1 - Numpy solution:

# color: color to be replaced
# newColor: replacing color

nimg = img.getNumpy()
indices = np.where(
            (nimg[:,:,0] == color[0]) &  # RGB values
            (nimg[:,:,1] == color[1]) &
            (nimg[:,:,2] == color[2]) 
        )
nimg[indices] = newColor
newImage = Image(nimg)

Solution 2 - Nested-Loop solution:

width, height = img.size()
y = 0
while y < height:
    x = 0
    while x < width:
            if img[x, y] == color:
                img[x, y] = newColor
    x+=1
y+=1

Solution 1 is, in average, more than 40 times faster than solution 2.

Any thoughts with another solution as fast as Solution 1 with SimpleCV API?

Thanks in advance.

edit retag flag offensive close merge delete