OpenCV 初识图像 September 11, 2018 [TOC] # 初识图像 ## cv.imread() 该函数第一个参数为路径,第二个参数有三个选项: - cv.IMREAD_COLOR (1):忽略透明通道 - cv.IMREAD_GRAYSCALE (0):灰度模式读取 - cv.IMREAD_UNCHANGED (-1):读取包含alpha(透明)通道的图像 ```python import numpy as np import cv2 as cv img = cv.imread('', 0) print(img) ``` None 路径不正确是,imread函数返回None ```python jpg = cv.imread('jpg.jpg') print(jpg.shape) jpg = cv.imread('jpg.jpg', cv.IMREAD_COLOR) print(jpg.shape) jpg = cv.imread('jpg.jpg', cv.IMREAD_GRAYSCALE) print(jpg.shape) jpg = cv.imread('jpg.jpg', cv.IMREAD_UNCHANGED) print(jpg.shape) png = cv.imread('png.png') print(png.shape) png = cv.imread('png.png', cv.IMREAD_COLOR) print(png.shape) png = cv.imread('png.png', cv.IMREAD_GRAYSCALE) print(png.shape) png = cv.imread('png.png', cv.IMREAD_UNCHANGED) print(png.shape) ``` (300, 300, 3) (300, 300, 3) (300, 300) (300, 300, 3) (512, 512, 3) (512, 512, 3) (512, 512) (512, 512, 4) 观察发现,imread第二个参数,默认为`cv.IMREAD_COLOR`,即使对`jpg`格式文件以`IMREAD_UNCHANGED`模式读取,也没有透明通道,但是对`png`格式图像有,因为该格式本身就含有透明通道。 ## cv.imshow() 显示图像 ```python cv.imshow('png',jpg) cv.imshow('jpg',png) # 获取任何按键都会继续向下执行 cv.waitKey(0) # 关闭所有打开的窗口 # cv.destroyAllWindows() # 传入窗口名,关闭指定窗口 cv.destroyWindow("png") import time time.sleep(3) cv.destroyWindow("jpg") ``` ```python # 窗口最大化以后,图片会随着最大化 cv.namedWindow('jpg1', cv.WINDOW_NORMAL) # 默认cv.WINDOW_AUTOSIZE,窗口最大化之后,图像还是原来大小 cv.imshow('jpg',jpg) cv.imshow('jpg1',jpg) cv.waitKey(0) cv.destroyAllWindows() ``` ## cv.imwrite() 写入图像 ```python # 可以通过imwrite转格式 cv.imwrite('1.png',jpg) cv.imwrite('1.jpg',png) # 控制jpg压缩质量 # 取值0~100,质量从低到高 q = 0 cv.imwrite("jpg_0.jpg", jpg, [int(cv.IMWRITE_JPEG_QUALITY), q]) q=100 cv.imwrite("jpg_100.jpg", jpg, [int(cv.IMWRITE_JPEG_QUALITY), q]) ``` True ## Using Matplotlib ```python from matplotlib import pyplot as plt # https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html # cmap设定色彩模式,这里jpg是彩色的,就算设定了还是显示彩色的 # interpolation 插值模式 plt.imshow(jpg, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() jpg1 = cv.imread('jpg.jpg', cv.IMREAD_GRAYSCALE) plt.imshow(jpg1, cmap = 'gray', interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() ``` ![](/images/2018/09/92167392.png) ![](/images/2018/09/2009710338.png) 注意上面彩色显示的并不正确,因为`plt.imshow`按照`RGB`格式显示图像,`imread`函数返回的`numpy`数组按照BGR(A)格式返回 ## cv.split() and cv.merge() 分割通道与合并通道 ```python B, G, R = cv.split(jpg) new_jpg = cv.merge([R, G, B]) plt.imshow(new_jpg) plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() ``` ![](/images/2018/09/4086813739.png)