OpenCV - Python api 笔记
Opencv-python是OpenCv的python API,包括数百种计算机视觉算法。这个页面记录了一些常用的Opencv-python函数,以便作为我的快速参考。
1. 安装和使用 Installation and Usage
- 安装
1 | pip install opencv-python |
事实上一共有四种不同的packages,安装其中一个即可,四个packages都用同一个名字cv2(对于其他的packages,详见Documentation)。
2. OpenCV中的GUI特性
2.1 图像基本操作(读取,显示,保存)
三个函数cv.imread(), cv.imshow(), cv.imwrite()分别用于读取;显示和保存图像。
cv.imread():读取图像
1
retval = cv.imread(filename[, flags])
参数 Parameters:
- filename: 文件名 (Name of file to be loaded.)
- flags: 定义读取图片的方式,如彩色或灰色等 (takes values of cv::ImreadModes specified the way image should be read.){
cv::IMREAD_UNCHANGED = -1,
cv::IMREAD_GRAYSCALE = 0,
cv::IMREAD_COLOR = 1,
cv::IMREAD_ANYDEPTH = 2,
cv::IMREAD_ANYCOLOR = 4,
cv::IMREAD_LOAD_GDAL = 8,
…}
例子 Example:
1
2
3
4import numpy as np
import cv2 as cv
# Load an color image in grayscale
img = cv.imread('messi5.jpg', 0)
cv.imshow():显示图像
1
None = cv.imshow(winname, mat)
- 参数 parameters:
- winname:显示窗的名字 (Name of the window.)
- mat: 要显示的图像名 (Image to be shown.)
- 例子 Example:
1
cv.imshow('image',img)
- 参数 parameters:
cv.imwrite():保存图像
1
retval = cv.imwrite(filename, img[, params])
- 参数 Parameters:
- filename:文件名(Name of the file.)
- img:要保存的图像名(Image to be saved.)
- params:Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, … .) see cv::ImwriteFlags
- 例子 Example:
1
cv.imwrite('messigray.png',img)
- 参数 Parameters:
2.2 色彩通道转换(Color conversions):RGB - Gray
RGB ↔ GRAY 除了RGB channel到灰度Y channel的转换,还有其他通道的转换,例如RGB ↔ CIE XYZ.Rec 709 with D65 white point; RGB ↔ YCrCb JPEG (or YCC)等等,详见Documentation。
RGB空间内的变换,例如添加/删除Alpha通道,反转通道顺序,转换为16位RGB颜色(R5:G6:B5或R5:G5:B5),以及转换为灰度/从灰度转换使用以下方式:
$$ \text{RGB[A] to Gray: Y←0.299⋅R+0.587⋅G+0.114⋅B} $$and
$$ \text{Gray to RGB[A]: R←Y,G←Y,B←Y,A←max(}ChannelRange\text{)} $$1 | cvtColor(src, dst, code, dstCn = 0) |
参数 Parameters:
- src:输入图像 (input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision floating-point.)
- dst:输出图像 (output image of the same size and depth as src.)
- code:转换方式代码 (color space conversion code (see cv::ColorConversionCodes).){
cv2.COLOR_RGB2GRAY,
cv2.COLOR_GRAY2RGB,
cv2.COLOR_BGR2GRAY,
cv2.COLOR_RGB2GRAY,
…
} - dstCn:目标图像中的通道数;如果参数为0,则从src和代码自动导出通道数 (number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code.)
例子 Examples:
1
2
3
4
5
6import numpy as np
import cv2 as cv
# Load an color image in grayscale
img = cv.imread('messi5.jpg', 0)
# Convert image from Y channel to RGB channel
img2 = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
Additional Reading
OpenCV官方教程中文版(For Python),段力辉 译(搬运自:https://www.linuxidc.com/Linux/2015-08/121400.htm)
- Title: OpenCV - Python api 笔记
- Author: Zhanhang (Matthew) ZENG
- Link: https://zengzhanhang.com/2019/05/12/OpenCV-Cheat-Sheet/
- Released Date: 2019-05-12
- Last update: 2020-05-17
- Statement: All articles in this blog, unless otherwise stated, are based on the CC BY-NC-SA 4.0 license.