python - 如何在 VIPS/Python 中对特定色调范围应用变换

标签 python image-processing vips

我必须在 VIPS(和 Python)中对 16 位 tiff 文件的不同色调范围应用各种转换。我已经设法做到了这一点,但我是 VIPS 的新手,我不相信我能以有效的方式做到这一点。这些图像每个都有几百兆字节,削减每个多余的步骤可以为每个图像节省几秒钟。

我想知道是否有更有效的方法来实现与我从下面的代码中获得的相同结果,例如使用查找表(我无法真正弄清楚它们在 VIPS 中是如何工作的)。该代码分离红色 channel 中的阴影并通过变换将它们传递。

im = Vips.Image.new_from_file("test.tiff")

# Separate the red channel
band = im[0]

# Find the tone limit for the bottom 5%
lim = band.percent(5) 

# Create a mask using the tone limit
mask = (band <= lim) 

# Convert the mask to 16 bits
mask = mask.cast(band.BandFmt, shift = True) 

# Run the transformation on the image and keep only the shadow areas
new_shadows = (65535 * (shadows / lim * 0.1)) & mask 

对每个色调范围(高光、阴影、中间色调)运行或多或少相似的代码后,我将所有生成的图像添加在一起以重建原始频带:

new_band = (new_shadows.add(new_highlights).add(new_midtones)).cast(band.BandFmt)

最佳答案

我为您制作了一个演示程序,展示如何使用 vips 直方图函数执行类似的操作:

import sys
import pyvips

im = pyvips.Image.new_from_file(sys.argv[1])

# find the image histogram 
# 
# we'll get a uint image, one pixel high and 256 or
# 65536 pixels across, it'll have three bands for an RGB image source
hist = im.hist_find()

# find the normalised cumulative histogram 
#
# for a 16-bit source, we'll have 65535 as the right-most element in each band
norm = hist.hist_cum().hist_norm()

# search from the left for the first pixel > 5%: the position of this pixel 
# will give us the pixel value that 5% of pixels fall below
# 
# .profile() gives back a pair of [column-profile, row-profile], we want index 1
# one. .getpoint() reads out a pixel as a Python array, so for an RGB Image 
# we'll have something like [19.0, 16.0, 15.0] in shadows
shadows = (norm > 5.0 / 100.0 * norm.width).profile()[1].getpoint(0, 0)

# Now make an identity LUT that matches our original image
lut = pyvips.Image.identity(bands=im.bands,  
                            ushort=(im.format == "ushort"))

# do something to the shadows ... here we just brighten them a lot
lut = (lut < shadows).ifthenelse(lut * 100, lut)

# make sure our lut is back in the original format, then map the image through
# it
im = im.maplut(lut.cast(im.format))

im.write_to_file(sys.argv[2])

它对源图像执行单个查找直方图操作,然后执行单个 map 直方图操作,因此它应该很快。

这只是调整阴影,您还需要稍微扩展它以进行中间色调和高光,但您可以从单个初始直方图进行所有三个修改,因此它不会变慢。

如果您有任何其他问题,请在 libvips 跟踪器上提出问题:

https://github.com/libvips/libvips/issues

关于python - 如何在 VIPS/Python 中对特定色调范围应用变换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39166164/

相关文章:

python - 按消费者分配 celery worker

c# - 颜色数量减少的位图——它的大小不应该减小吗?

matlab - 为手-前臂分割实现手腕裁剪程序(Matlab)

java - 如何从android中的位图中获取图像的原始字符串?

imagick - Vips + mozjpeg 与 Imagick

macos - 从 go 构建 vips 库的问题

python - 使用 ExcelWriter 时 Pandas 库写入损坏的 xlsx 文件

python - 将 strip 应用于 DataFrame 中的列表列

go - 在 Go 中给定多个 URL 参数的过程图像

python - 将 DataFrame 行与包含列表的几列之间的笛卡尔积相乘