python - 给定 xy 触摸位置,如何用颜色填充 RGBA 图像的透明部分?

标签 python image

我正在尝试用 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")

下面给出的是freehand.png:(图案区域是透明的) enter image description here

最佳答案

cv2cv2.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/

相关文章:

python - matplotlib 修剪刻度标签

image - 使用 <object> 而不是 <img> 包含图像是否有效?

javascript - 使用 javascript 动态显示图像 url

c# - 如何使用 C# 将图像插入到 pdf 文档中?

python - 我如何报告在整个脚本中从未匹配的任何正则表达式?

python - 为什么 os.path 同时使用 '\' 和 '/' ?

python - 防止 Python 代码导入某些模块?

python - 如何检查一个字符串是否只包含小写字母和数字?

C#:调整图片框大小以适合图像

ruby-on-rails - Rails + Dragonfly gem : Saving image in a directory structure based on ActiveRecord object attributes