gpt4 book ai didi

python - 我如何调整我的代码,以便我的透明 python 图像在另一个图像(具有新的着色颜色)之上呈现为高质量?

转载 作者:太空宇宙 更新时间:2023-11-03 14:12:07 25 4
gpt4 key购买 nike

所以我有两张图片。一张 png 皮卡丘和一张黑色背景。

enter image description here enter image description here

使用我当前的代码,我成功地将两个图像合并在一起并对透明皮卡丘进行着色,但如您所见,结果并不好。我尝试过使用多张透明图片获得相同的结果。

enter image description here

这是我的代码当前的样子:

def image_tint(src, tint='#ffffff'):
if Image.isStringType(src): # file path?
src = Image.open(src)
src = src.convert('RGB')
if src.mode not in ['RGB', 'RGBA']:
raise TypeError('Unsupported source image mode: {}'.format(src.mode))
src.load()

tr, tg, tb = getrgb(tint)
tl = getcolor(tint, "L") # tint color's overall luminosity
if not tl: tl = 1 # avoid division by zero
tl = float(tl) # compute luminosity preserving tint factors
sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb)) # per component
# adjustments
# create look-up tables to map luminosity to adjusted tint
# (using floating-point math only to compute table)
luts = (tuple(map(lambda lr: int(lr*sr + 0.5), range(256))) +
tuple(map(lambda lg: int(lg*sg + 0.5), range(256))) +
tuple(map(lambda lb: int(lb*sb + 0.5), range(256))))
l = grayscale(src) # 8-bit luminosity version of whole image
if Image.getmodebands(src.mode) < 4:
merge_args = (src.mode, (l, l, l)) # for RGB verion of grayscale
else: # include copy of src image's alpha layer
a = Image.new("L", src.size)
a.putdata(src.getdata(3))
merge_args = (src.mode, (l, l, l, a)) # for RGBA verion of grayscale
luts += tuple(range(256)) # for 1:1 mapping of copied alpha values

return Image.merge(*merge_args).point(luts)

当我使用它时:

transparent_files = 'Images/transparentImageFolder' 
static_files = 'Images/staticImageFolder'

for pathtransparent, dirs, filetransparent in os.walk(transparent_files):
for pathstatic, dirs, filesstatic in os.walk(static_files):
for transparentfile in filetransparent:
input_image_path = pathtransparent + "/" + transparentfile
print('tinting "{}"'.format(input_image_path))
result = image_tint(input_image_path, '#444222')
result.save(input_image_path)

for staticfile in filesstatic:
staticImage= Image.open(pathstatic + "/" + staticfile, 'r').convert("RGBA")

transparentImage = Image.open(pathtransparent + "/" + transparentfile, 'r').convert("RGBA")
text_img = Image.new('RGBA', (staticImage.width, staticImage.height), (0, 0, 0, 0))
text_img.paste(staticImage, ((text_img.width - staticImage.width) // 2, (text_img.height - staticImage.height) // 2))
text_img.paste(transparentImage, ((text_img.width - transparentImage.width) // 2, (text_img.height - transparentImage.height)
text_img.save(pathtransparent + "/" + transparentfile)

为什么质量这么差?

最佳答案

你的第四行src = src.convert('RGB')正在获取src并丢弃alpha channel 。尝试删除该行,或者执行src = src.convert('RGBA'),您的结果应该会有所改善。

关于python - 我如何调整我的代码,以便我的透明 python 图像在另一个图像(具有新的着色颜色)之上呈现为高质量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48425440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com