Pillow:将 TIFF 从 16 位灰度转换为 8 位导致全白图像
Pillow: converting a TIFF from greyscale 16 bit to 8 bit results in fully white image
我知道SO上有多个类似的问题,但是我尝试了多个建议的解决方案都无济于事。
我有以下在 Pillow 中打开的 TIFF 图像 type='I;16'
。
基于这个SO问题,我写了这段代码来转换它:
def tiff_force_8bit(image, **kwargs):
if image.format == 'TIFF' and image.mode == 'I;16':
array = np.array(image)
normalized = (array.astype(np.uint16) - array.min()) * 255.0 / (array.max() - array.min())
image = Image.fromarray(normalized.astype(np.uint8))
return image
然而,结果是一张全白的图像。
我也尝试过其他解决方案,例如:
table = [i/256 for i in range(65536)]
image = image.point(table, 'L')
结果相同:全白。
任何人都可以解释一下吗?
谢谢!
您的代码没有任何问题。如果你 运行:
# Open image
im = Image.open('NGC 281 11-01-2021 Ha 1.15.tif')
# Force to 8-bit
res = tiff_force_8bit(im)
# Check min and max of result
res.getextrema() # prints (0,255) as expected
# Save as PNG
res.save('result.png')
# Display it
res.show()
我只能猜测您的安装或显示结果的方式有问题。
我知道SO上有多个类似的问题,但是我尝试了多个建议的解决方案都无济于事。
我有以下在 Pillow 中打开的 TIFF 图像 type='I;16'
。
基于这个SO问题,我写了这段代码来转换它:
def tiff_force_8bit(image, **kwargs):
if image.format == 'TIFF' and image.mode == 'I;16':
array = np.array(image)
normalized = (array.astype(np.uint16) - array.min()) * 255.0 / (array.max() - array.min())
image = Image.fromarray(normalized.astype(np.uint8))
return image
然而,结果是一张全白的图像。
我也尝试过其他解决方案,例如:
table = [i/256 for i in range(65536)]
image = image.point(table, 'L')
结果相同:全白。
任何人都可以解释一下吗? 谢谢!
您的代码没有任何问题。如果你 运行:
# Open image
im = Image.open('NGC 281 11-01-2021 Ha 1.15.tif')
# Force to 8-bit
res = tiff_force_8bit(im)
# Check min and max of result
res.getextrema() # prints (0,255) as expected
# Save as PNG
res.save('result.png')
# Display it
res.show()
我只能猜测您的安装或显示结果的方式有问题。