2

I want to save an image without any channel, so the dimension would only be 2. Thus, is there a way I do it in matplotlib?

I have already tried using

matplotlib.pyplot.imsave('img.png', image, cmap='gray')

but when I read it using

matplotlib.pyplot.imread('img.png')

The dimension is 3. So I'm confusing how. I know maybe I can't use imread but what can I do instead?

Walker
  • 109
  • 1
  • 9
  • A grayscale image has 3 dimention, the third one represent light level – Ando Sep 05 '20 at 09:37
  • Thank you! Already changed the question. So do you know how to make them 2 dimension? like array.shape = (256,256), not (256,256,3) ? – Walker Sep 05 '20 at 09:39
  • You meant (256,256, 1) right ? because (256,256) is not an image – Ando Sep 05 '20 at 09:42
  • try checking https://stackoverflow.com/questions/23339315/read-image-grayscale-opencv-3-0-0-dev – Ando Sep 05 '20 at 09:42
  • Nop, but I can also export the array to npy with (256,256) and import them with the same 2 dimension. So can I achieve this using matplotlib? – Walker Sep 05 '20 at 09:43
  • Thank you! Unfortunately, the system is linux and I can't install opencv on it and I tried. – Walker Sep 05 '20 at 09:45
  • An grayscale image consist of x axis, y axis and a color depth, if you're only saving 2 dimentions then it wouldn't be an image Also I'm using ubuntu and have opencv installed – Ando Sep 05 '20 at 09:49
  • 1
    @YukiShioriii: That makes no sense. A gray-scale image is a 2D matrix. – Cris Luengo Sep 05 '20 at 14:28
  • 1
    From the docs, it looks like matplotlib only saves RGB or RGBA format image files. You’ll have to use a different package to save a gray-scale image. OpenCV as suggested below is just one option. There are many. Try PIL. – Cris Luengo Sep 05 '20 at 14:32

1 Answers1

1

If you have opencv installed, you can try:

cv2.imread('1.png', cv2.IMREAD_GRAYSCALE)

Also, you can also try PIL.

from PIL import Image
Image.fromarray(array)

I didn't see this one on the internet, but this one works! thanks to my teacher!

skimage.io.imsave('1.png', np.around(image*255).astype(np.uint8))

To use this, you have to have skimage preinstalled.

pip3 install scikit-image

Thanks @Cris Luengo in the comment above to point out that

"From the docs, it looks like matplotlib only saves RGB or RGBA format image files. You’ll have to use a different package to save a gray-scale image. OpenCV as suggested below is just one option. There are many. Try PIL."

Give him an upvote when you saw it!

Dwa
  • 593
  • 4
  • 13