Create Colored Image from Numpy array
In this article, we have explored how to Create Colored Image from Numpy array along with complete Python code example.
Table of contents:
- Create Colored Image from Numpy array
- Green colored Image in Numpy
- Red colored Image in Numpy
Create Colored Image from Numpy array
A standard RGB image has 3 dimensions:
- Height
- Width
- Channels
The number of channels is 3 for RGB images. RGB image means that each pixel has 3 values that is amount of red, green and blue and with the correct combination, any color can be generated.
So, the idea of creating a colored image is to:
- First create a blank image of 3 dimensions (Height x Width x Channels)
- Get the pixel value of the color you want. It will be a set of 3 values RGB.
- Fill in all values in (Height x Width) with the correct pixel value (BGR). Note, in Numpy, the format is BGR and not RGB.
Doing this, a color is added to the image. If you place different pixel values at different locations, complex images can be generated as well.
The main code snippet is:
image_blank[:0:width] = (B, G, R) # BGR format
Green colored Image in Numpy
The pixel value of Green color is (0, 255, 0) in BGR format. Note components of B (blue) and R (red) is 0 while the component of Green G is maximum that is 255. If you reduce the value from 255, the brightness of green will reduce.
So, to create a Green colored image in Numpy, set all pixel values to (0, 255, 0).
The main code snippet is as follows:
image_blank[:0:width] = (0, 255, 0) # Green in BGR format
Following is the complete Python code to create a sample image in Numpy with Green color:
import numpy as np
image_blank = np.zeros((height, width, channels), np.uint8)
image_blank[:0:width] = (0, 255, 0) # Green in BGR format
image_filename = "image_color.jpeg"
image_blank.save(image_filename)
Red colored Image in Numpy
The pixel value of Red color is (0, 0, 255) in BGR format. Note components of B (blue) and G (green) is 0 while the component of Red R is maximum that is 255. If you reduce the value from 255, the brightness of red will reduce.
So, to create a Red colored image in Numpy, set all pixel values to (0, 0, 255).
The main code snippet is as follows:
image_blank[:0:width] = (0, 0, 255) # Red in BGR format
Following is the complete Python code to create a sample image in Numpy with Red color:
import numpy as np
image_blank = np.zeros((height, width, channels), np.uint8)
image_blank[:0:width] = (0, 0, 255) # Red in BGR format
image_filename = "image_color.jpeg"
image_blank.save(image_filename)
With this article at OpenGenus, you must have the complete idea of how to create colored images in Numpy.