Ask Your Question

Remove pixels(BGR) within a certain threshold of the selected pixel(BGR)

asked 2018-01-25 04:58:00 -0500

Santhosh1 gravatar image

I want to remove pixels in an image within a certain threshold of a particular BGR pixel.

Similar to the Magic Wand or Fuzzy Tool

I found this old MATLAB implementation here

This are the steps mentioned in the post

Add the square of difference of the RGB value at particular location with selected pixel value

c_r, c_g and c_b are the pixel values at a particular location

ref_r, ref_g and ref_b is the selected pixel

((c_r - ref_r).^2 + (c_g - ref_g).^2 + (c_b - ref_b).^2) <= tolerance^2;

I'm trying to implement this is python here's my code

I have a group of pixels values(BGR) stored in a numpy array in __pixels

__b,__g,__r = 0,0,0
#go through each pixel
for index,x in np.ndindex(__pixels.shape):
    if x == 0:
        __b = __pixels[index,x]
    elif x == 1:
        __g = __pixels[index,x]
    elif x == 2:
        __r = __pixels[index,x]
        #Change the color of w
        print(__pixels.shape[0]," ",index)
        img[np.where(((np.square(img[0]-__b))+(np.square(img[1]-__g))+(np.square(img[2]-__r))) <= TOLs).all(axis=2)] = [255, 255, 255]

I'm getting this error

img[np.where(((np.square(img[0]-__b))+(np.square(img[1]-__g))+(np.square(img[2]-__r))) <= TOLs).all(axis=2)] = [255, 255, 255]
AttributeError: 'tuple' object has no attribute 'all'

Can anyone guide me?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2018-01-27 04:37:57 -0500

Santhosh1 gravatar image

With help from online article Python numpy array with multiple conditions to iterate over image

I was able to extract each BGR value then work on them to accomplish the same task on same image in around 4000 milliseconds

Here's the code

TOL = 90**2

#((c_r - ref_r).^2 + (c_g - ref_g).^2 + (c_b - ref_b).^2)
Res = (img[...,0]-[122])**2+(img[...,1]-[112])**2+(img[...,2]-[96])**2

#<= tolerance^2 then 255
Res1 = cv2.bitwise_not(Res.astype(np.uint8))
Res1 = cv2.merge((Res1,Res1,Res1))
Trest = cv2.bitwise_and(img,Res1)
edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower


Asked: 2018-01-25 04:58:00 -0500

Seen: 157 times

Last updated: Jan 27 '18