如何使用负值保存PIL图像 [英] How to save PIL image with negative values

查看:249
本文介绍了如何使用负值保存PIL图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PIL保存具有负值的图像,但是,保存后,图像文件将所有负值剪裁为0。

I am trying to save an image with negative values using PIL, however, after saving, the image files has all negative values clipped to 0.

from PIL import Image
import numpy as np

# generate random image for demo
img_arr = np.random.random_integers(-1000,1000, size=[10,10]).astype(np.int32)
print "original min {}, max: {}".format(img_arr.min(),img_arr.max())

# create PIL image
img1 = Image.fromarray(img_arr)
print "PIL min {}, max: {}".format(np.array(img1.getdata()).min(),np.array(img1.getdata()).max())

# save image
img1.save("test_file.png", "PNG")

# reload image
img_file = Image.open("test_file.png")
print "img_file min {}, max: {}".format(np.array(img_file.getdata()).min(),np.array(img_file.getdata()).max())

这导致输出:

original min -983, max: 965
PIL min -983, max: 965
img_file min 0, max: 965

如何保存此图像并保持负值?

How can I save this image and maintain the negative values?

推荐答案

请注意,根据PIL存储像素为32位有符号整数,图像模式I用于处理这在PIL中。因此,由于技术原因错误,所以评论说这没有任何意义。

Note that there is such a thing as storing your pixels as 32-bit signed integers according to PIL, and the image mode 'I' is meant to handle this in PIL. So the comments saying this makes no sense due to technical reasons are mistaken.

我不认为PNG格式支持这种模式(尽管你写的时候不会抛出任何错误模式I中的图像。但是,。tt扩展似乎是:

I don't think the PNG format supports this mode(Despite no errors being thrown when you write an Image in mode 'I'). However, the ".tif" extension seems to:

img1.save("test_file.tif")

更改(以及读取以获取正确的文件)似乎有效:

Changing that (and the read to get the correct file) seems to work:

original min -993, max: 990
PIL min -993, max: 990
img_file min -993, max: 990

这篇关于如何使用负值保存PIL图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆