import cv2 %pylab inline import sys sys.setrecursionlimit(10000) def dfs(x, y, r, g, b, mask, im, Prange): # Check if image dimensions are not violated and the pixel is not previously visited if (x < 0 or y < 0 or x == im.shape[1] or y == im.shape[0] or mask[y, x] == True): return; # Check the if the current values are in +- range (Prange) of the required pixel value elif ( (abs(int(im[y, x, 2])- r) < Prange) and (int(abs(im[y, x, 1])- g) < Prange) and (int(abs(im[y, x, 0])- b) < Prange)): # If yes, set the value for the pixel in mask is equal to True mask[y, x] = True # Move to the pixel on above the current pixel dfs(x , y - 1, r, g, b, mask, im, Prange); # Move to the pixel right of current pixel dfs(x + 1, y, r, g, b, mask, im, Prange); # Move to the pixel left of current pixel dfs(x - 1, y , r, g, b, mask, im, Prange); # Move to the pixel below the current pixel dfs(x, y + 1, r, g, b, mask, im, Prange); #Similarly dfs(x - 1, y - 1, r, g, b, mask, im, Prange); dfs(x - 1, y + 1, r, g, b, mask, im, Prange); dfs(x + 1, y + 1, r, g, b, mask, im, Prange); dfs(x + 1, y - 1, r, g, b, mask, im, Prange); return def dfsFunction(x, y, im, Prange): # Initiate a boolean array named mask and set all values equal to false mask = np.zeros(im.shape[:2], dtype = 'bool') # Call the recursive function dfs(x, y, int(im[y, x ,2]), int(im[y, x , 1]), int(im[y, x , 0]), mask, im, Prange) return mask im = imread("/home/bikz05/Desktop/$_35.JPG") # Display the original image title("Original Image") axis("off") imshow(im) show() im = cv2.cvtColor(im, cv2.COLOR_RGB2BGR) mask = dfsFunction(60, 256, im, 50) im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) new = im * np.dstack((mask, mask, mask)) # Display the resulting image title("Resulting Image") axis("off") imshow(new) show()