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?

9
  • A grayscale image has 3 dimention, the third one represent light level Commented Sep 5, 2020 at 9: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) ? Commented Sep 5, 2020 at 9:39
  • You meant (256,256, 1) right ? because (256,256) is not an image Commented Sep 5, 2020 at 9:42
  • 1
    @YukiShioriii: That makes no sense. A gray-scale image is a 2D matrix. Commented Sep 5, 2020 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. Commented Sep 5, 2020 at 14:32

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.