python - 重新调整 PIL 图像的强度

标签 python image-processing python-imaging-library

重新调整 PIL 图像强度的最简单/最干净的方法是什么?

假设我有一张来自 12 位相机的 16 位图像,因此只使用了 0–4095 的值。我想重新调整强度,以便使用整个范围 0–65535。当图像表示为 PIL 的图像类型时,最简单/最干净的方法是什么?

到目前为止我想出的最好的解决方案是:

pixels = img.getdata()
img.putdata(pixels, 16)

这行得通,但始终将四个最低有效位留空。理想情况下,我想将每个值向左移动四位,然后将四个最高有效位复制到四个最低有效位。我不知道如何快速做到这一点。

最佳答案

既然你知道像素值是 0-4095,我找不到比这更快的方法了:

new_image= image.point(lambda value: value<<4 | value>>8)

根据documentation ,无论图像大小如何,lambda 函数最多将被调用 4096 次。

编辑:由于赋予点的函数必须的形式是argument * scale + offset for in I image,那么这是最好使用 point 函数:

new_image= image.point(lambda argument: argument*16)

最大输出像素值为 65520。

第二次拍摄:

您自己的解决方案的修改版本,使用 itertools 提高效率:

import itertools as it # for brevity
import operator

def scale_12to16(image):
    new_image= image.copy()
    new_image.putdata(
        it.imap(operator.or_,
            it.imap(operator.lshift, image.getdata(), it.repeat(4)),
            it.imap(operator.rshift, image.getdata(), it.repeat(8))
        )
    )
    return new_image

这避免了 point 函数参数的限制。

关于python - 重新调整 PIL 图像的强度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1327954/

相关文章:

image-processing - 不同尺度的 HOG 特征

python - OpenCV - 如何通过斜线将图像分割为两个区域?

python - 如何将 Python 和 OpenCV 与多处理一起使用?

python-3.x - 使用 Python 查找 '.dng' 图像分辨率

python - 通过 Pillow 的 Image.frombytes 创建的图像与预期不同

python - 如何根据两个数组的条件创建一个新数组?

python - 使 wxPython TextCtrl 响应 cr 或 tab

python - 使用 cx_Freeze 编译为 exe 时没有此类文件或目录 webdriver_prefs.json

python - IronPython WPF 加载新窗口

python - 调整地面实况图像的大小,而不更改标签