首页 > 解决方案 > 从 numpy 数组中保存 jpg 图像的转换是什么?

问题描述

我正在使用 hamamatsu 相机,我得到一个 NumPy 数组,我想像图像一样保存数组,我可以将其保存为 TIF 图像,但我不知道如何转换 TIF 图像或数组以获得正确的jpg图像,我有这个代码:

img = Image.fromarray(self.val_fin)

    if int(self.vTIFF.get()) == 1:
        imgTIFF = img.convert('I')
        img.save('name1.tiff')

    if int(self.vJPG.get()) == 1:
        imgJPG = img.convert('RGB')
        imgJPG.save('name2.jpg')

其中val_fin是一个32bit的数组,其负值已经变为0,jpg图像的结果是黑色图像。谢谢。

标签: pythonpython-imaging-librarytiff

解决方案


使用 tiff 32bites 浮动图像:

tiff 32bites 浮动

我可以运行这段代码:

from PIL import Image

import numpy as np


def normalize8(I):
  mn = I.min()
  mx = I.max()

  mx -= mn

  I = ((I - mn)/mx) * 255.0
  return np.round(I).astype(np.uint8)

img1 = Image.open('test_fl.tif', 'r')

arr = np.asarray(img1)

print(arr.size, arr.shape, arr.ndim , arr.dtype)


img = Image.fromarray(arr, mode='F')
print(img.size, img.format, img.mode)
img.save('test_saved.tif')

# doesnt work
# imgTIFF = img.convert(mode='I')
# imgTIFF.save('name1.tif')
# img2 = Image.open('name1.tif', 'r')
# print(img2.size, img2.format, img2.mode)

imgTIFF = Image.fromarray(normalize8(arr))
imgTIFF.save('name1.tif')
img2 = Image.open('name1.tif', 'r')
print(img2.size, img2.format, img2.mode)



imgJPG = imgTIFF.convert('RGB')
imgJPG.save('name2.jpg')

img3 = Image.open('name2.jpg')
print(img3.size, img3.format, img3.mode)
img3.show()

print(img3.getpixel((0,0)))

取自How should I convert a float32 image to an uint8 image?

imgTIFF = img.convert(mode='I')

尝试将 tiff 32float 转换为 32int 也会给我一个黑色图像


推荐阅读