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

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

主站蜘蛛池模板: 天镇县| 吴川市| 朝阳县| 右玉县| 德钦县| 微山县| 台南县| 西平县| 宝坻区| 盐边县| 将乐县| 清涧县| 讷河市| 昭觉县| 施甸县| 大田县| 东明县| 综艺| 彰化县| 阿鲁科尔沁旗| 榆中县| 庆城县| 天祝| 泊头市| 永吉县| 西丰县| 永吉县| 四子王旗| 永和县| 富宁县| 梅州市| 宝兴县| 宝兴县| 四平市| 左云县| 凤翔县| 肇庆市| 库伦旗| 喀什市| 赤壁市| 新平|