简体   繁体   中英

Scaling image held in numpy array cannot be undone

I loaded an image as pixel data into a numpy array (subjectImage). The following lines of code successfully restores the numpy array back to an image and displays it:

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. (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.

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. 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:

>>> 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. Possibly it interprets the floats as uint8, or some such and tries to display them somehow. Unfortunately, the docs for img.show() don't tell us anything about how it works.

Scipy's misc module has its own imshow , however, which works fine:

>>> 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. See this question, for instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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