魔杖将透明背景变为黑色

时间:2015-07-31 19:16:10

标签: python grayscale wand magickwand

我正在尝试使用Wand使用pyhton进行灰度调整,但是当我这样做时

from wand.image import Image
with Image(filename='image.png') as img:
    img.type = 'grayscale'
    img.save(filename='image_gray.png')

它将透明背景变为黑色。如果我使用白色背景,它的工作原理。我做错了什么而且灰度也是

Y = 0.2126 * RED + 0.7152 * GREEN + 0.0722 * BLUE

我可以在Wand中手动执行此操作,如果我想稍微更改值,请说明。我查看了文档和各种论坛,但我找不到任何答案,只有Photoshop的内容。

谢谢!

2 个答案:

答案 0 :(得分:3)

设置为灰度的PNG图像类型会删除透明图层(请参阅PNG docs)。一种选择是在设置灰度后启用Alpha通道。

img.alpha = True
# or
img.background_color = Color('transparent')

根据您的版本,这可能不起作用。

另一个选项

使用Image.modulate更改颜色饱和度。

img.modulate(saturation=0.0)

另一个选项

改变色彩空间。

img.colorspace = 'gray'
# or
img.colorspace = 'rec709luma'
# or
img.colorspace = 'rec601luma'

另一个选项

如果您的版本有Image.fx。以下工作

with img.fx('lightness') as gray_copy:
   ....

答案 1 :(得分:1)

this doesnt answer your question about wand ... but you can do it easy enough with just pil ...

from PIL import Image
from math import ceil
import q
def CalcLuminosity(RED,GREEN,BLUE):
    return int(ceil(0.2126 * RED + 0.7152 * GREEN + 0.0722 * BLUE))

im = Image.open('bird.jpg')
# im.convert("L")  will apply the standard luminosity mapping

data = [CalcLuminosity(*im.getpixel((c,r))) for r in range(im.height) for c in range(im.width) ]

#now make our new image using our luminosity values
x = Image.new("L",(im.width,im.height))
image_px = x.load()
for c in range(im.width):
    for r in range(im.height):
        image_px[c,r] = data[r*im.width+c]

x.save("output.jpg")

or if you wanted to limit extremes based on a threshold

#now make our new image using our luminosity values
x = Image.new("L",(im.width,im.height))
image_px = x.load()
for c in range(im.width):
    for r in range(im.height):
        image_px[c,r] = 0 if data[r*im.width+c] < 120 else 255

x.save("output.jpg")

or if you wanted to filter a single color chanel

def CalcLuminosityBLUE(RED,GREEN,BLUE):
    return BLUE
相关问题