灰度图处理与图片保存¶
1. 读取BGR图(默认读取)¶
In [1]:
import cv2 #opencv的缩写为cv2
import matplotlib.pyplot as plt # matplotlib库用于绘图展示
import numpy as np # numpy数值计算工具包
# 魔法指令,直接展示图,Jupyter notebook特有
%matplotlib inline
In [2]:
img = cv2.imread('01_Picture/01_cat.jpg')
img.shape # (h,w,c) c表示 3 通道,这个 3 通道被 opencv 读进来是 BGR 的先后顺序的 3 通道
Out[2]:
(414, 500, 3)
2. 读取灰度图(设置读取)¶
In [3]:
img_gray = cv2.imread('01_Picture/01_cat.jpg',cv2.IMREAD_GRAYSCALE)
#img_gray = cv2.imread('01_Picture/01_cat.jpg',cv2.IMREAD_COLOR) # BGR图
img_gray # 只有一个通道,同样是 uint8 类型
Out[3]:
array([[153, 157, 162, ..., 174, 173, 172],
[119, 124, 129, ..., 173, 172, 171],
[120, 124, 130, ..., 172, 171, 170],
...,
[187, 182, 167, ..., 202, 191, 170],
[165, 172, 164, ..., 185, 141, 122],
[179, 179, 146, ..., 197, 142, 141]], dtype=uint8)
In [4]:
print('type(img_gray):',type(img_gray))
print('img_gray.size: ',img_gray.size) # 414 × 500 = 20700
print('img_gray.dtype:',img_gray.dtype)
print('img_gray.shape:',img_gray.shape) # 只有一个通道
type(img_gray): <class 'numpy.ndarray'> img_gray.size: 207000 img_gray.dtype: uint8 img_gray.shape: (414, 500)
3. 显示图片¶
In [5]:
def cv_show(name,img):
cv2.imshow(name,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv_show('image_cat_gray',img_gray)
4. 保存图片¶
In [6]:
cv2.imwrite('01_Picture/02_cat_gray.jpg',img_gray) # 保存图片
Out[6]:
True