无法撤消numpy数组中保留的缩放图像

2024-10-01 07:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我将图像作为像素数据加载到numpy数组(subjectImage)中。以下代码行成功地将numpy数组还原回图像并显示它:

subjectImagePath = 'pathToFile/cat.0.jpg'        
subjectImage = misc.imresize(misc.imread(subjectImagePath), (224,224,3))
img = Image.fromarray(subjectImage, 'RGB')
img.show()

但是,如果将图像的像素值缩放到0和1之间,则无法将图像恢复到其原始形式。(它显示一堆噪音)

subjectImage = subjectImage/255
subjectImage = subjectImage*255
img = Image.fromarray(subjectImage, 'RGB')
img.show()

Numpy甚至告诉我数组是一样的。你知道吗

orig = subjectImage
subjectImage = subjectImage/255
print(np.array_equal(orig, subjectImage*255)) # => Prints True

我想知道是什么原因造成的?任何帮助都将是伟大的!你知道吗

使用的库:

import numpy as np
from PIL import Image
from scipy import misc

Tags: 图像imageimportnumpyimgshownprgb
2条回答

浮点表示和数据类型的有趣示例。。。检查以下示例。您可以打印数组以查看不等式存在的位置。下面简化了结果和比较。你知道吗

>>> a = np.arange(5*5*3, dtype=np.int64)
>>> b = a/(5*5)
>>> c = b*(5*5)
>>> d = np.around(b*(5*5))
>>> a[a!=c]
array([ 7, 14, 28, 29, 55, 56, 57, 58])
>>> a[a!=d]
array([], dtype=int64)

问题是,乘和除255之后的数组变成了浮点数组:

>>> a = misc.imread(path)
>>> a.dtype
dtype('uint8')
>>> b = a / 255
>>> b = b * 255
>>> b.dtype
dtype('float64')

我猜img.show()函数不知道如何显示浮点数。它可能将浮点值解释为uint8或类似的值,并尝试以某种方式显示它们。不幸的是,img.show()docs并没有告诉我们它是如何工作的。你知道吗

但是,Scipy的misc模块有自己的^{},它运行良好:

>>> misc.imshow(b)

另一方面,如果同时使用scipy.miscPIL/pillow,它们处理数组的方式似乎有些不同。例如,参见this问题。你知道吗

相关问题 更多 >