【问题标题】:Wand turns transparent background to black魔杖将透明背景变为黑色
【发布时间】:2015-10-23 13:41:06
【问题描述】:

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

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 的东西。

谢谢!

【问题讨论】:

  • JPEG 没有透明度,所以您是否希望背景始终变为白色?
  • 对,对不起,我发布了错误的代码,我编辑了它。这是否意味着我应该先将每张图片转换为 jpg 而不能灰度化 png?

标签: python grayscale wand magickwand


【解决方案1】:

这并不能回答你关于魔杖的问题......但你可以很容易地用 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")

或者如果您想根据阈值限制极端情况

#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")

或者如果你想过滤一个单一的颜色通道

def CalcLuminosityBLUE(RED,GREEN,BLUE):
    return BLUE

【讨论】:

  • 谢谢,我试试,我喜欢这个,因为你可以编辑灰度
【解决方案2】:

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:
   ....

【讨论】:

  • 好的,谢谢第二个和第三个选项有效。第一个不是,但我喜欢它,我需要什么版本?最后一个选项,什么是 image.fx?最后,您在哪里找到了色彩空间的代码?我在文档中的任何地方都找不到它
  • @PaulBernhardWagner 仍在解决这个问题。 IM 的 C-API 颜色结构随着即将推出的 IM7 发生了变化,wan 0.4.1 的下一次迭代将包括一些重写。
  • Docs & examples 是一个好的开始。还可以查看 wand development branch 了解附近的功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2021-10-20
  • 2014-11-12
  • 1970-01-01
相关资源
最近更新 更多