Abraham
Abraham

Reputation: 53

How to correctly display red, green, and blue (rgb) channels of an image with pyplot

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.

Upvotes: 5

Views: 12852

Answers (1)

Y. Luo
Y. Luo

Reputation: 5732

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

Upvotes: 6

Related Questions