5

I have a tiny project so I started doing some tests on Python a week ago. I have to show the 3 channels of an rgb image, but pyplot.imshow() function displays the following:

Current display

I want to show Red, Green, and Blue channels, like this:

Red channel from RGB

This is my code, so far:

from matplotlib import pyplot as plt
from PIL import Image
import numpy as np

img1 = np.array(Image.open('img1.png'))
figure, plots = plt.subplots(ncols=3, nrows=1)
for i, subplot in zip(range(3), plots):
    temp = np.zeros(img1.shape, dtype='uint8')
    temp = img1[:,:,i]
    subplot.imshow(temp)
    subplot.set_axis_off()
plt.show()

I do not work in any notebook. Rather, I work in PyCharm. I read this post: 24739769. I checked and img1.dtype is uint8, so I have no more ideas how to show what I want.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Abraham
  • 53
  • 1
  • 1
  • 4
  • Hi @Abraham Gutierrez, welcome to SO. I understand that you don't have enough reputation to post the images in the post but, in the future, please do it. If people don't have to go to external pages they are more likely to look at your problem. What are `img1.shape`, `temp.min()` and `temp.max()`? Also, could you maybe post the original image so that we can reproduce your error? – Aleksander Lidtke Jun 26 '17 at 04:44
  • I sorry. I used the image button but the editor put them as links. img1.shape is the dimension of the image loaded, as far as I know (x,y, rgb channels). min() and max() functions return the min an max values of any array/matrix respectively. – Abraham Jun 26 '17 at 20:16

1 Answers1

6

You need only one tiny changes: temp[:,:,i] = img1[:,:,i].

A complete and verifiable example using the first image you've shown:

from matplotlib import pyplot as plt
from PIL import Image
import numpy as np

img1 = np.array(Image.open('img1.png'))
figure, plots = plt.subplots(ncols=3, nrows=1)
for i, subplot in zip(range(3), plots):
    temp = np.zeros(img1.shape, dtype='uint8')
    temp[:,:,i] = img1[:,:,i]
    subplot.imshow(temp)
    subplot.set_axis_off()
plt.show()

enter image description here

Y. Luo
  • 5,622
  • 1
  • 18
  • 25
  • Thank you so much. I missed the line you added. Also, `img1.shape` returns `(x,y,4)` (maybe for RGBA format) instead of `(x,y,3)` (for RGB only). – Abraham Jun 26 '17 at 20:19