Bob van Luijt
Bob van Luijt

Reputation: 7588

How to change the color channels of an image in Python?

This is a question that probably should be floating around somewhere here, but I don't seem to find it.

I have this code:

import matplotlib.image as img     

img1 = img.imread('./images_32x32/test_1.png')
print("Shape = ", img1.shape) # Output: 32x32x3

img2 = img.imread('./images_32x32/test_2.png')
print("Shape = ", img2.shape) # Output: 32x32x4

My problem is in the shape of img2 (img2.shape) I would like it to be also 3.

How do I change this?

Upvotes: 0

Views: 4338

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31250

Your first image is a RGB image (three values per pixel, red green and blue), the second is a RGBA image (red, green, blue and alpha, for the transparancy of the pixel).

It's just a numpy array, you can slice them:

img2_rgb = img2[:, :, :3]

Yields a 32x32x3 image without the transparency data.

Upvotes: 1

Related Questions