Implement the Image Resize and Grayscale Features

Learn how to implement the image resizing and grayscaling functionalities by manipulating the 3D arrays.

Introduction

In the previous lessons, we implemented the functions to upload, save, rotate, and flip an image. In this lesson, we'll be implementing functions to resize an image and grayscale an image. Let's move on to the implementation.

Function to resize an image

Below is an illustration of the logic of resizing the pixel values of an image. Suppose that we have an image with 3×33\times 3 pixels, and we want to resize the image to 4×44\times 4 pixels. We need to calculate two values that will denote the ratio by which we want the height and the width of the pixels to be updated. So, we apply these formulas:

  • Wratio = current width (columns)/new width (columns)

  • Hratio = current height (rows)/new height (rows)

Now, we'll create a 3D array of the new height (rows) and width (columns). Each (i,j)th(i, j)^{th} pixel in the new 3D array becomes equal to the i×Hratio,j×Wratioi\times Hratio, j\times Wratio pixel in the original 3D array. This technique of generating resized images by using pixels is also known as sampling.

Get hands-on with 1200+ tech skills courses.