Python 图片转换

Python image conversion

我正在尝试将具有模式 I(32 位带符号整数像素)的图像转换为标准灰度或 'RGB' 图像。问题是当我尝试转换它时,它只是变成了空白的白色图像。我正在使用 PIL 模块。

有我要转换的图片。

from PIL import Image
sample_img = Image.open('sample.png') 
sample_img=sample_img.convert('L')

这对你有用吗?

from PIL import Image
import numpy as np

sample_img = Image.open('sample.png') 
rescaled = 255 * np.asarray(sample_img)/2**16
img = Image.fromarray(np.uint8(rescaled))

给出:

>>> np.asarray(img)

array([[ 95,  96,  98, ...,  98, 105, 107],
       [ 93,  97,  99, ..., 100, 105, 108],
       [ 94,  99, 100, ..., 102, 105, 110],
       ..., 
       [130, 125, 125, ...,  97,  98, 100],
       [128, 120, 123, ...,  99,  99, 101],
       [125, 119, 120, ..., 101, 100, 101]], dtype=uint8)

这是一张 'standard' 8 位灰度图像。

PIL 是我曾经尝试依赖的错误最多的软件包之一。这是一个非常直接的转换,您提供的示例代码应该可以正常工作。

这里有一个解决方法。

def ItoL(im):
    w, h = im.size
    result = Image.new('L', (w, h))
    pix1 = im.load()
    pix2 = result.load()
    for y in range(h):
        for x in range(w):
            pix2[x,y] = pix1[x,y] >> 8
return result