ddjfjfj djfiejdn
ddjfjfj djfiejdn

Reputation: 131

In Python, the shape of an image with a single channel is a problem

I took a 256x256 RGB image and switched it to YCbCr,

I created code to import only the Y channel

Here is my code:

from PIL import Image
import numpy as np

im = Image.open ('test.bmp')
img = im.convert ('YCbCr')
arr_img = np.asarray (img)
arr_img = arr_img [:,:, 0]

img = Image.fromarray (arr_img)
img.show ()

After doing this, I created an image with the Y channel I wanted.

I was happy

But the problem is from here.

I ran this code

print (np.shape (arr_img))

Here, what I want is (256, 256, 1).

However, the above code output (256, 256).

So I changed "arr_img = arr_img [:,:, 0]" to "arr_img = arr_img [:, :, :1]".

However, it did not run because of an error.

I made the RGB image into an image with three channels of YCbCr,

I thought it would be the size (256, 256, 1) when I imported only the first channel, "Y"

How can I get the shape of (256, 256, 1)?

Upvotes: 2

Views: 1519

Answers (2)

Raj
Raj

Reputation: 41

Numpy has a built-in function np.expand_dims() to add an additional dimension.

Example:

a = np.random.randn(2,3)

a.shape

(2, 3)

a = np.expand_dims(a, axis=2)

a.shape

(2, 3, 1)

Upvotes: 1

N.G
N.G

Reputation: 367

A possibility is to add by hand the missing dimension:

arr_img = np.zeros( [256,256] )

arr_img = arr_img.reshape( * arr_img.shape, 1 )

Upvotes: 2

Related Questions