Getting ready

In this example, we will use the CIFAR-10 dataset, which consists of color images of a size of 32x32. There are 50,000 training images and 10,000 test images. We will preprocess its images to grayscale and then build an autoencoder to color them.

Let's first load the required libraries into the environment:

library(keras)
library(wvtool)
library(grid)
library(abind)

We load the training and testing datasets and store them into variables:

data <- dataset_cifar10()
x_train = data$train$x
x_test = data$test$x

Let's store relevant dimension data into respective variables:

num_images = dim(x_train)[1]
num_images_test = dim(x_test)[1]
img_width = dim(x_train)[2]
img_height = dim(x_train)[3]

Let's convert all of the images in the train and test data into grayscale images using the rgb2gray() function from wvtools:

# grayscale train set 
x_train_gray <- apply(x_train[1:num_images,,,], c(1), FUN = function(x){
rgb2gray(x, coefs=c(0.299, 0.587, 0.114))
})
x_train_gray <- t(x_train_gray)
x_train_gray = array(x_train_gray,dim = c(num_images,img_width,img_height))

# grayscale test set
x_test_gray <- apply(x_test[1:num_images_test,,,], c(1), FUN = function(x){
rgb2gray(x, coefs=c(0.299, 0.587, 0.114))
})
x_test_gray <- t(x_test_gray)
x_test_gray = array(x_test_gray,dim = c(num_images_test,img_width,img_height))

Next, we normalize the train and test colored images and the grayscale images within the range of 0 and 1:

# normalize train and test coloured images
x_train = x_train / 255
x_test = x_test / 255

# normalize train and test grayscale images
x_train_gray = x_train_gray / 255
x_test_gray = x_test_gray / 255

Then, we reshape each grayscale image into the shape of the image height, image width, and number of channels:

x_train_gray <- array_reshape(x_train_gray,dim = c(num_images,img_height,img_width,1))
x_test_gray <- array_reshape(x_test_gray,dim = c(num_images_test,img_height,img_width,1))

Note that, in the case of grayscale images, the number of channels is 1.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset