处理灰度图片
读入图像
OpenCV可以读入不同类型的图像 (PNG, JPG, etc)。可以上传灰度图片、彩色图片或者带Alpha通道的图片。使用cv2.imread()
函数,语法规则见下:
retval = cv2.imread( filename [, flags])
retval
:成功载入的图片,否则为None
。当路径不对或者图片损坏时会发生。
该函数有一个必须的输入参数和一个可选择参数。
1、filename
:可以是绝对路径,也可以是相对路径。这是必须传入的参数
2、Flags
:这个参数用来表示用哪种特定格式读入一张图片(如,灰度/彩色/带有alpha通道)。这是一个可选参数,默认值为cv2.IMREAD_COLOR
或1
,代表作为彩色图片载入。
Flags
1、cv2.IMREAD_GRAYSCALE
或0
:以灰度模式载入图片。
2、cv2.IMREAD_COLOR
或1
:以彩图模式载入图片,图片的透明度会被忽略,这是默认值。
3、cv2.IMREAD_UNCHANGED
或-1
:包含alpha通道载入图片
OpenCV Documentation
Imread
:https://docs.opencv.org/4.5.1/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56
ImreadModes
:https://docs.opencv.org/4.5.1/d8/d6a/group__imgcodecs__flags.html#ga61d9b0126a3e57d9277ac48327799c80
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Read image as gray scale
cb_img = cv2.imread('checkerboard_18x18.png', 0)
# Print the image data (pixel values), element of a 2D numpy array
# Each pixel value is 8-bit2 [0, 255]
print(cb_img)
打印图片属性
# Print the size of image
print('Image size is ', cb_img.shape)
# Print data-type of image
print('Data type of image is ', cb_img.dtype)
'''
Image size is (18, 18)
Data type of image is uint8
'''
用matplotlib展示图片
# Display image.
plt.imshow(cb_img)
尽管图片以灰度图片的方式被读入,当使用imshow()
的时候不一定按照灰度图的方式展示。matplotlib使用不同的color map,可能没有设置灰度color map。
# Set color map to gray scale for proper rendering.
plt.imshow(cb_img, cmap='gray')
另一实例
# Read images as gray scale.
cb_img_fuzzy = cv2.imread("checkerboard_fuzzy_18x18.jpg", 0)
# Print image.
print(cb_img_fuzzy)
# Display image.
plt.imshow(cb_img_fuzzy, cmap='gray')
处理彩色图片
读入和展示图片
# Read in image.
coke_img = cv2.imread("coca-cola-logo.png", 1)
# Print the size of image
print