gpt4 book ai didi

python - 使用 PIL 将 ImageMagick FX 运算符转换为纯 Python 代码

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:46 26 4
gpt4 key购买 nike

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

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

最佳答案

我知道已经过去了大约一个月,您可能已经明白了。但这就是答案。

从 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')

关于python - 使用 PIL 将 ImageMagick FX 运算符转换为纯 Python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/789401/

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