【问题标题】:Converting an ImageMagick FX operator to pure Python code with PIL使用 PIL 将 ImageMagick FX 运算符转换为纯 Python 代码
【发布时间】:2009-04-25 17:53:27
【问题描述】:

我正在尝试从 Image Magick 移植一些图像处理功能 使用PIL 命令(使用Fx Special Effects Image Operator)到Python。我的 问题是我并不完全理解这个 fx 操作员在做什么:

convert input.png gradient.png -fx "v.p{0,u*v.h}" output.png

从高层次上看,此命令从渐变图像中获取颜色 (gradient.png) 并将它们用作输入图像的调色板 (input.png),写入输出图像 (output.png)。

据我所知,u 是输入图像,v 是渐变,它是 从上到下遍历渐变中最左边的每个像素, 以某种方式将其颜色应用于输入图像。

我不知道如何以编程方式做同样的事情 皮尔。我想出的最好的方法是将图像转换为调色板 图像(下采样到微不足道的 256 种颜色)并单独抓取颜色 来自带有像素访问对象的渐变。

import Image

# open the input image
input_img = Image.open('input.png')

# open gradient image and resize to 256px height
gradient_img = Image.open('gradient.png')
gradient_img = gradient_img.resize( (gradient_img.size[0], 256,) )

# get pixel access object (significantly quicker than getpixel method)
gradient_pix = gradient_img.load()

# build a sequence of 256 palette values (going from bottom to top)
sequence = []
for i in range(255, 0, -1):
    # from rgb tuples for each pixel row
    sequence.extend(gradient_pix[0, i])

# convert to "P" mode in order to use putpalette() with built sequence
output_img = input_img.convert("P")
output_img.putpalette(sequence)

# save output file
output_img = output_img.convert("RGBA")
output_img.save('output.png')

这行得通,但就像我说的那样,它会下采样到 256 种颜色。不仅是 这是一种笨拙的做事方式,它会导致非常糟糕的输出 图片。我怎样才能复制 Magick 功能而不填塞 结果变成265色?

附录:忘记引用blog where I found the original Magick command

【问题讨论】:

    标签: python imagemagick python-imaging-library


    【解决方案1】:

    我知道这已经过去了大约一个月,您可能已经弄清楚了。但这里有答案。

    从 ImageMagicK 文档中,我能够理解效果的实际作用。

    convert input.png gradient.png -fx "v.p{0,u*v.h}" output.png
    
    v is the second image (gradient.png)
    u is the first image (input.png)
    v.p will get a pixel value
    v.p{0, 0} -> first pixel in the image
    v.h -> the hight of the second image
    v.p{0, u * v.h} -> will read the Nth pixel where N = u * v.h
    

    我将其转换为 PIL,结果看起来与您想要的完全一样:

    import Image
    
    # open the input image
    input_img = Image.open('input.png')
    
    # open gradient image and resize to 256px height
    gradient_img = Image.open('gradient.png')
    gradient_img = gradient_img.resize( (gradient_img.size[0], 256,) )
    
    # get pixel access object (significantly quicker than getpixel method)
    gradient_pix = gradient_img.load()
    
    data = input_img.getdata()
    input_img.putdata([gradient_pix[0, r] for (r, g, b, a) in data])
    input_img.save('output.png')
    

    【讨论】:

    • 谢谢,效果很好!我想出了一个类似的算法(头部和键盘的敲击声,以及来自 imagemagick 的大量帮助),但我认为你的算法实际上可能比我的更有效
    猜你喜欢
    • 1970-01-01
    • 2012-08-25
    • 2017-01-24
    • 2015-02-18
    • 1970-01-01
    • 2020-03-06
    • 2014-03-17
    • 2011-07-04
    • 2011-09-15
    相关资源
    最近更新 更多