安装

pip install opencv-python

读写与显示

import cv2

img = cv2.imread('photo.jpg')        # BGR 格式
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

cv2.imwrite('gray.jpg', gray)
cv2.imshow('window', img)
cv2.waitKey(0)

常用处理

# 高斯模糊降噪
blur = cv2.GaussianBlur(img, (5, 5), 0)

# 阈值二值化
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# 自适应阈值(光照不均更好)
binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                               cv2.THRESH_BINARY, 11, 2)

# Canny 边缘检测
edges = cv2.Canny(blur, 50, 150)

轮廓查找

contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
                               cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    area = cv2.contourArea(c)
    if area > 100:               # 过滤小噪点
        x, y, w, h = cv2.boundingRect(c)
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

图像缩放与旋转

resized = cv2.resize(img, (640, 480))
rotated = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
经验:工业视觉常用流程:灰度 → 滤波 → 二值化 → 形态学 → 轮廓/特征提取 → 判定。