官术网_书友最值得收藏!

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

主站蜘蛛池模板: 汾西县| 文成县| 凌云县| 江门市| 北宁市| 监利县| 开封市| 兴安县| 邵武市| 义马市| 汉中市| 项城市| 千阳县| 离岛区| 郯城县| 扎兰屯市| 洛宁县| 拜泉县| 昭觉县| 加查县| 马山县| 景东| 二连浩特市| 页游| 永城市| 邯郸市| 资中县| 旬邑县| 榆树市| 新邵县| 梁山县| 沽源县| 忻州市| 浦城县| 乌苏市| 衡水市| 彭州市| 丰都县| 讷河市| 海原县| 莎车县|