In this tutorial, we will learn how we can create our own image using numpy and OpenCV. This will help you in understanding the image concepts more. Let’s see how the 256 intensity levels for an 8-bit image looks like.
Steps:
- Create an array of any desired size using numpy. Always specify the ‘datatype’
- Fill the values of the array using some logic
- Show the image using cv2.imshow() or matplotlib.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import cv2 import numpy as np import matplotlib.pyplot as plt img = np.zeros((100,256),dtype=np.uint8) for i in range(img.shape[1]): for j in range(img.shape[0]): img[j,i]=i cv2.imshow('a',img) cv2.waitKey(0) cv2.destroyAllWindows() #--------- using Matplotlib ------------ ##plt.imshow(img, cmap = 'gray') ##plt.tick_params(axis='y',left = False,labelleft = False) ##plt.xticks([0,50,100,150,200,255]) ##plt.show() |
The resulting image looks like this
To create a color image just specify the third dimension of the array (for example (100,256,3)) and rest is same.
Now, you are ready to create your own images. Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.