我正在尝试用 python 开发一个 android 应用程序来填充触摸的区域(就像 ms paint 中的填充颜色工具一样,它用颜色填充封闭区域,或者如果没有关闭,颜色会散布到各处)。给定触摸的xy位置,如何使用PIL或cv2填充RGBA图像的透明区域,然后保存? 下面给出伪代码:
#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")
最佳答案
cv2
有 cv2.floodFill()
它会在 start_point
处获取颜色并在附近搜索相同的颜色并替换为 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()
但它只适用于 RGB
而不是 RBGA
所以它需要更多的工作。
pillow
也有 ImageDraw.floodfill()
并且它与 RGBA
一起工作。如果您使用 numpy.array
,那么它只需要将 array
转换为 Image,然后再转换回 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')
关于python - 给定 xy 触摸位置,如何用颜色填充 RGBA 图像的透明部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67507267/