Image Operations
8 methods图像读写、几何变换、滤波与轮廓检测的核心 API。
cv2.imread(path, flag)从文件读取图像为 BGR 格式的 NumPy 数组。
Parameters
| Name | Type | Description |
|---|---|---|
| path | str | 图像文件路径 |
| flag | int | 读取模式,如 cv2.IMREAD_GRAYSCALE |
Returns
ndarray — BGR 图像数组,失败返回 None
Example
opencv
import cv2
img = cv2.imread("photo.jpg", cv2.IMREAD_COLOR)
print(img.shape) # (H, W, 3)cv2.imwrite(path, img)将图像数组写入指定文件。
Parameters
| Name | Type | Description |
|---|---|---|
| path | str | 输出文件路径 |
| image | ndarray | 待保存的图像 |
Returns
bool — 是否写入成功
Example
opencv
import cv2
import numpy as np
img = np.zeros((100, 100, 3), dtype="uint8")
ok = cv2.imwrite("black.png", img)
print(ok)cv2.cvtColor(img, code)将图像从一个颜色空间转换到另一个(如 BGR 转 RGB/灰度)。
Parameters
| Name | Type | Description |
|---|---|---|
| image | ndarray | 输入图像 |
| code | int | 转换码,如 cv2.COLOR_BGR2GRAY |
Returns
ndarray — 转换后的图像
Example
opencv
import cv2
img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)cv2.resize(img, size)将图像缩放到指定尺寸。
Parameters
| Name | Type | Description |
|---|---|---|
| image | ndarray | 输入图像 |
| size | tuple[int, int] | 目标 (width, height) |
Returns
ndarray — 缩放后的图像
Example
opencv
import cv2
img = cv2.imread("photo.jpg")
small = cv2.resize(img, (100, 100))
print(small.shape)cv2.GaussianBlur(img, ksize, sigma)对图像应用高斯模糊。
Parameters
| Name | Type | Description |
|---|---|---|
| image | ndarray | 输入图像 |
| ksize | tuple[int, int] | 高斯核大小,须为正奇数 |
| sigma | float | 高斯核标准差,0 表示自动计算 |
Returns
ndarray — 模糊后的图像
Example
opencv
import cv2
img = cv2.imread("photo.jpg")
blur = cv2.GaussianBlur(img, (5, 5), 0)
cv2.imwrite("blur.jpg", blur)cv2.Canny(img, threshold1, threshold2)使用 Canny 算法检测图像边缘。
Parameters
| Name | Type | Description |
|---|---|---|
| image | ndarray | 输入(通常为灰度)图像 |
| threshold1 | float | 滞后低阈值 |
| threshold2 | float | 滞后高阈值 |
Returns
ndarray — 二值边缘图
Example
opencv
import cv2
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
edges = cv2.Canny(gray, 100, 200)
cv2.imwrite("edges.png", edges)cv2.findContours(img, mode, method)从二值图像中检测轮廓。
Parameters
| Name | Type | Description |
|---|---|---|
| image | ndarray | 二值源图像 |
| mode | int | 轮廓检索模式,如 cv2.RETR_EXTERNAL |
| method | int | 轮廓近似方法,如 cv2.CHAIN_APPROX_SIMPLE |
Returns
tuple — (contours, hierarchy)
Example
opencv
import cv2
gray = cv2.imread("shapes.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(
binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
print(len(contours))cv2.VideoCapture(index)打开摄像头或视频文件用于逐帧捕获。
Parameters
| Name | Type | Description |
|---|---|---|
| index | int | str | 摄像头索引(0)或视频文件路径 |
Returns
VideoCapture — 视频捕获对象
Example
opencv
import cv2
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
print(ret, frame.shape if ret else None)
cap.release()