Skip to content

OpenCV cv2 API

OpenCV(cv2)提供图像读写、颜色转换、滤波、边缘检测与视频捕获等计算机视觉 API。

1 class · 8 methods

Image Operations

8 methods

图像读写、几何变换、滤波与轮廓检测的核心 API。

cv2.imread(path, flag)

从文件读取图像为 BGR 格式的 NumPy 数组。

Parameters

NameTypeDescription
pathstr图像文件路径
flagint读取模式,如 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

NameTypeDescription
pathstr输出文件路径
imagendarray待保存的图像

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

NameTypeDescription
imagendarray输入图像
codeint转换码,如 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

NameTypeDescription
imagendarray输入图像
sizetuple[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

NameTypeDescription
imagendarray输入图像
ksizetuple[int, int]高斯核大小,须为正奇数
sigmafloat高斯核标准差,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

NameTypeDescription
imagendarray输入(通常为灰度)图像
threshold1float滞后低阈值
threshold2float滞后高阈值

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

NameTypeDescription
imagendarray二值源图像
modeint轮廓检索模式,如 cv2.RETR_EXTERNAL
methodint轮廓近似方法,如 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

NameTypeDescription
indexint | 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()