In the previous blogs, we learned about pixels, intensity value, color, and greyscale image. Now, with OpenCV and numpy, let’s try to visualize these concepts.
First, we need an image, either you can load one or can make own image. Loading an image from the device looks like this
1 2 3 4 |
import cv2 import numpy as np img = cv2.imread('F:/downloads/Python.png') |
To access the pixel location, we must first know the shape of the image. This can be done by
1 2 |
>>> img.shape (2000, 2000, 3) |
It returns a tuple of the number of rows, columns, and channels (if the image is color).
Total number of pixels can be found either by multiplying rows, columns, channels found using img.shape or by using the following command
1 2 |
>>> img.size # same as 2000*2000*3 12000000 |
After knowing the image shape, we can access the pixel location by its row and column coordinates as
1 2 |
>>> img[250,250] # for single pixel >>> img[280:340, 330:390] # for image region |
This returns the intensity value at that pixel location. For a greyscale image, intensity or pixel value is a single integer while for a color image, it is an array of Blue, Green, Red values.
1 2 3 4 5 6 |
# for color image, [Blue,Green,Red] value is returned >>> img[250,250] [157 166 200] # for 8-bit greyscale image >>> img[250,250] 257 |
Note: OpenCV reads the color image in BGR mode and not in RGB mode. Be careful
We know that intensity levels depend on the number of bits that can be found by
1 2 |
>>> img.dtype dtype('uint8') # 8-bit image |
To access the RGB channels separately, use numpy indexing as shown below
1 |
>>> img[:,:,0] # 0 for Blue, 1 - Green, 2 - Red |
You can change the pixel value just by normal assignment as shown below
1 2 3 4 5 6 7 8 9 |
>>> img[250,250] [0,0,0] >>> img[250,250] = 34 >>> img[250,250] [34,34,34] # we can assign different values to each channel at a pixel >>> img[250,250] = [234,145,23] # to make all the red pixels to zero >>> img[:,:,2] = 0 |
You can change the color image to greyscale using the following command
1 |
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) |
All the operations that you can perform on the array like add, subtract etc apply to images also.
Play with all these commands to understand better. 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.