Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scikit-image: write a ndarray to image with imsave, read back with imread, data don't match

here is the minimum working example:

import numpy as np
from skimage.io import imsave, imread

image = np.array([[[109, 232, 173],
                [ 55,  35, 144]],
                [[ 43, 124, 185],
                [234, 127, 246]]], dtype=np.uint8)

imsave("test.jpg", image)
rb_image = imread("test.jpg")
print("original image")
print(image)
print("read back image")
print(rb_image)

after run it, the result is, the ndarray read back from file don't match with

original image
[[[109 232 173]
  [ 55  35 144]]

 [[ 43 124 185]
  [234 127 246]]]
read back image
[[[111 208 255]
  [ 42  61 138]]

 [[ 72 140 201]
  [141 131 218]]]

can some one give me some suggestiones?

like image 924
scott huang Avatar asked Nov 18 '17 02:11

scott huang


People also ask

Is scikit-image same as Skimage?

scikit-image (a.k.a. skimage ) is a collection of algorithms for image processing and computer vision.

What does IO Imread return?

io. imread() function to read a JPEG image entitled chair. jpg. Skimage reads the image, converts it from JPEG into a NumPy array, and returns the array; we save the array in a variable named image .

How do I save an array as a picture?

To save the Numpy array as a local image, use the save() function and pass the image filename with the directory where to save it. This will save the Numpy array as a jpeg image.


1 Answers

jpeg is a lossy image compression algorithm, designed to reduce the file size by getting rid of information that is not easily noticeable from the human eye. That means saving in jpg will save some disk space but change the pixel values of your array.

You can avoid the problem by saving in lossless png format instead. The following snippet works for me

import numpy as np
from skimage.io import imsave, imread

image = np.array([[[109, 232, 173],
                [ 55,  35, 144]],
                [[ 43, 124, 185],
                [234, 127, 246]]], dtype=np.uint8)

imsave("test.png", image)
rb_image = imread("test.png")
print("original image")
print(image)
print("read back image")
print(rb_image)

and this is the result

original image
[[[109 232 173]
  [ 55  35 144]]

 [[ 43 124 185]
  [234 127 246]]]
read back image
[[[109 232 173]
  [ 55  35 144]]

 [[ 43 124 185]
  [234 127 246]]]
like image 66
NeverNervous Avatar answered Oct 11 '22 14:10

NeverNervous