When I generate an image and then generate a numpy array from it, the original .npy file differs from the new one. I thought new-array.npy would be exactly the same as original-array.npy since they are coming from the same image.
For an example, I used this little image with 4*4 pixels:
original-image.png
Here is a larger version (not the one I'm working with):

The last part of the code is the one that converts the .png to .npy. I think the problem is in here somewhere.
import numpy as np
from PIL import Image
from matplotlib import pyplot as plt
filename = 'image-test'
img = Image.open( filename + '.png' )
data = np.array( img, dtype='uint8' )
np.save( filename + '.npy', data)
# visually testing our output
img_array = np.load(filename + '.npy')
plt.imshow(img_array)
My simple algorithm:
- Generate random rgb array and save it as
.npy - Save a
.pngfile from that numpy array. - Load that
.pngfile and save it back to.npy
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
from PIL import Image
####create a matrix of random colors
filename = "original-array"
matrix=np.random.random((4,4,3))
nx,ny,nz=np.shape(matrix)
CXY=np.zeros([ny, nx])
for i in range(ny):
for j in range(nx):
CXY[i,j]=np.max(matrix[j,i,:])
#Save binary data
np.save(filename + '.npy', CXY)
print(filename + " was saved")
#Load npy
img_array = np.load(filename + '.npy')
plt.imshow(img_array)
####Save npy as png
filename = "original-image"
img_name = filename +".png"
matplotlib.image.imsave(img_name, img_array)
print(filename + " was saved")
#### Convert that png back to numpy array
img = Image.open( filename + '.png' )
data = np.array( img, dtype='uint8' )
#Convert the new npy file to png
filename = "new-array"
np.save( filename + '.npy', data)
print(filename + " was saved")
#Load npy
img_array = np.load(filename + '.npy')
filename = "new-image"
#Save as png
img_name = filename +".png"
matplotlib.image.imsave(img_name, img_array)
print(filename + " was saved")
When I regenerate an image from new-array.npy I get exactly the same image as original-image.png:


CXYorimg_array) to a PNG file and expect to read back the same values.CXYcontains floating point numbers in the range 0..1. PNG files can only store integer numbers, and cannot therefore store your floating point values.