Getting RGB channels in separate arrays from CIFAR-10 dataset

CIFAR-10 is a dataset used in machine learning for recognizing 10 categories. It has been used in multiple papers and large studies have been conducted, especially with Deep Learning.

In this article, we will give you the necessary code to extract the R, G and B channels separately.

We will be using pickle, libs.image and Numpy libraries. If you do not have these already installed, you can do so using PiP (

      # import the necessary libraries
import pickle
import numpy as np

# read 1 file from the training dataset 
with open('cifar/data_batch_1', 'rb') as fo: # change the folder according to the location of your CIFAR-10 files
   data = pickle.load(fo, encoding='latin1') # load the images using pickle
   for i in range(0, len(data['data'])): # loop through each image
      x = np.reshape(data['data'][i], [3, 32, 32]) # reshape the array into Red, Green & Blue channels
      channel_r = x[0]
      channel_g = x[1]
      channel_b = x[2]
      image = np.array([channel_r, np.zeros(shape=(32,32)),np.zeros(shape=(32,32))]) # create the image with empty Green and Blue channels
      libs.image.show_image_from_array(image) # Display the Red channel

Leave a Reply