Home > Net >  How can you store an image as a ndarray of each of its colour channels?
How can you store an image as a ndarray of each of its colour channels?

Time:01-08

I am currently trying to get an image and save it to an array of each of its colour channels (RGB). When I append the image to a list it instead stores the three colour channels of each pixel together. I was wondering how I could separate them?

Current code

img = cv2.imread(f'Data/keyboard/00{i 1:02d}.jpg') 
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)   # BGR -> RGB  
imgdata.append([img,"keyboard"])

print(trainData[0][0][0])

Current output

 [185, 233, 255]
 [185, 233, 255]
 [185, 233, 255]
 ...
 [189 229 254]

Needed Format

Red = [[185,185,16,...,189],[185,185,16,...,185],...]
Green = [[233,233,233,...,229],[233,233,233,...,229],...]
Blue = [[255,255,255,...,254],[255,255,255,...,254],...]

CodePudding user response:

After you load in your image using cv2 and perform the color conversion, you can verify its dimensions using img.shape which will be in the form of W, H, 3, where 3 represents the R, G, and B color channels.

Now to separate the colors, you can start by reshaping the image data to 2 dimensions as (W*H, 3) using the following code

w, h, channels = img.shape
img_reshaped = img.reshape((w * h, channels)) 

This way each entry will be [R, G, B]. However, to extract just the R, G, or B, you would use an second dimension index of 0, 1, or 2 respectively.
For example, to extract all the red values, you would use reds = img_reshaped[:, 0]

If you need to extend this to multiple images, you could call the extend() function or use a NumPy array initialized to the right size using np.zeros()

  •  Tags:  
  • Related