简体   繁体   English

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

[英]Scaling image held in numpy array cannot be undone

I loaded an image as pixel data into a numpy array (subjectImage). 我将图像作为像素数据加载到numpy数组(subjectImage)中。 The following lines of code successfully restores the numpy array back to an image and displays it: 以下代码行成功地将numpy数组还原到图像并显示它:

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

However, if i scale the pixel values of the image between 0 and 1, then I am unable to restore the image back to its original form. 但是,如果我在0到1之间缩放图像的像素值,则无法将图像恢复到其原始形式。 (It displays a bunch of noise) (它显示出一堆噪音)

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

Numpy even tells me the arrays are the same. Numpy甚至告诉我数组是相同的。

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

I am wondering what could possibly cause this? 我想知道是什么原因造成的? Any help would be great! 任何帮助将是巨大的!

Libraries used: 使用的库:

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

Interesting example of floating point representations and dtype... Examine the following example. 有趣的浮点表示形式和dtype示例...请检查以下示例。 You can print the arrays to see where the inequalities exist. 您可以打印数组以查看不等式所在的位置。 The following simplifies the results and the comparisons. 以下简化了结果和比较。

>>> 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)

The problem is that the array after multiplication and division by 255 becomes a floating-point array: 问题是乘以255后的数组变成了浮点数组:

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

My guess is that the img.show() function doesn't know how to display floating-point numbers. 我的猜测是img.show()函数不知道如何显示浮点数。 Possibly it interprets the floats as uint8, or some such and tries to display them somehow. 可能会将float解释为uint8或其他某种形式,并尝试以某种方式显示它们。 Unfortunately, the docs for img.show() don't tell us anything about how it works. 不幸的是, img.show()文档没有告诉我们有关其工作原理的任何信息。

Scipy's misc module has its own imshow , however, which works fine: Scipy的misc模块具有自己的imshow ,但是效果很好:

>>> misc.imshow(b)

On a related note, if you're thinking of using both scipy.misc and PIL / pillow concurrently, there seems to be some difference in the way they treat arrays. 与此相关的是,如果您考虑同时使用scipy.miscPIL / pillow ,那么它们对待数组的方式似乎有所不同。 See this question, for instance. 例如,参见问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM