所以我有两张照片。一个png皮卡丘和一个黑色背景
用我目前的代码,我成功地合并了两个图像在一起,并着色透明皮卡丘,但正如你所看到的结果是不好的。我尝试了多张透明图片,结果都是一样的
以下是我的代码当前的外观:
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通道。尝试删除该行,或者改为执行src = src.convert('RGBA')
,结果应该会有所改善相关问题 更多 >
编程相关推荐