- Mastering OpenCV 4 with Python
- Alberto Fernández Villán
- 462字
- 2021-07-02 12:07:14
Accessing and manipulating pixels in OpenCV with grayscale images
Grayscale images have only one channel. Therefore, some differences are introduced when working with these images. We are going to highlight these differences here.
Again, we will use the cv2.imread() function to read an image. In this case, the second argument is needed because we want to load the image in grayscale. The second argument is a flag specifying the way the image should be read. The value that's needed for loading an image in grayscale is cv2.IMREAD_GRAYSCALE:
# The function cv2.imshow() is used to display an image in a window
# The first argument of this function is the window name
# The second argument of this function is the image to be shown.
# In this case, the second argument is needed because we want to load the image in grayscale.
# Second argument is a flag specifying the way the image should be read.
# Value needed for loading an image in grayscale: 'cv2.IMREAD_GRAYSCALE'.
# load OpenCV logo image:
gray_img = cv2.imread('logo.png', cv2.IMREAD_GRAYSCALE)
In this case, we store the image in the gray_img variable. If we get the dimensions of the image (using gray_img.shape), we will get only two values that is, rows and columns. In grayscale images, the channel information is not provided:
# To get the dimensions of the image use img.shape
# If color image, img.shape returns returns a tuple of number of rows, columns and channels
# If grayscale, returns a tuple of number of rows and columns.
# So, it can be used to check if the loaded image is grayscale or color image.
# Get the shape of the image (in this case only two components!):
dimensions = gray_img.shape
img.shape will return the dimensions of the image in a tuple, like this—(99, 82).
A pixel value can be accessed by row and column coordinates. In grayscale images, only one value is obtained (usually called the intensity of the pixel). For example, if we want to get the intensity of the pixel (x=40, y=6), we would use the following code:
# You can access a pixel value by row and column coordinates.
# For BGR image, it returns an array of (Blue, Green, Red) values.
# Get the value of the pixel (x=40, y=6):
i = gray_img[6, 40]
The pixel values of the image can be also modified in the same way. For example, if we want to change the value of the pixel (x=40, y=6) to black (intensity equals to 0), we would use the following code:
# You can modify the pixel values of the image in the same way.
# Set the pixel to black:
gray_img[6, 40] = 0
- UNIX編程藝術
- Python概率統計
- Android應用程序開發與典型案例
- 深入淺出Serverless:技術原理與應用實踐
- 自然語言處理Python進階
- Visual FoxPro程序設計習題集及實驗指導(第四版)
- Windows Embedded CE 6.0程序設計實戰
- Data Science Algorithms in a Week
- Appcelerator Titanium:Patterns and Best Practices
- Python 3快速入門與實戰
- Instant GLEW
- 零基礎學Java(第5版)
- Microsoft Windows Identity Foundation Cookbook
- PHP從入門到精通(微視頻精編版)
- iOS程序員面試筆試真題與解析