how to fill the transparent part of an RGBA image with color, given the xy touch position?

Viewed 286

i am trying to develop an android application in python that fills the area which is touched (exactly like the fill color tool in ms paint, which fills the closed area with color, or if not closed the color spreads everywhere).Given the xy position of touch, how can i fill the transparent area of a RGBA image using PIL or cv2, then save it? given below is the pseudo code:

#rgb_value is the rgb value of the color with which to fill
#touchx, touchy are the xy positions of touch
#src is the source image, dst is the filename with which to save the output image
def fill_color(src, rgb_value, touchx, touchy, dst):
    #code goes here
    #then the image is saved
fill_color("freehand.png", [0,0,0], 5, 1000, "freehand(filled).png")

given below is freehand.png:(the patterned area is transparent) enter image description here

1 Answers

cv2 has cv2.floodFill()

It will get color in start_point and search the same color in neighborhood and replace with color

import cv2

img_before = cv2.imread('image.png')

img_after = img_before.copy()

start_point = (400, 300)
color = (128, 128, 128)
cv2.floodFill(img_after, None, start_point, color)

cv2.imshow('before', img_before)
cv2.imshow('after',  img_after)
cv2.waitKey(0)
    
cv2.destroyAllWindows()     

but it works only with RGB but not RBGA so it would need more work.


pillow also has ImageDraw.floodfill() and it work with RGBA. If you work with numpy.array then it will need only to convert from array to Image and later back to array.

from PIL import Image, ImageDraw

img_before = Image.open('image.png')

img_after = img_before.copy()

start_point = (400, 300)
color = (128, 128, 128, 255)
img_draw = ImageDraw.floodfill(img_after, start_point, color, thresh=50)

img_before.show()
img_after.show()

#img_after.save('image_after.png')
Related