导读 :模版匹配用滑窗找最相似区域;霍夫变换在边缘图里投票检出直线与圆。本文讲清灰度
matchTemplate+minMaxLoc,以及HoughLines与HoughLinesP的差异,并补上霍夫圆分段检测实战。
上一篇
一、模版匹配
(一)、原理
模版匹配:在给定大图中查找与模版最相似的区域。输入是模版 + 待搜索图;思路是滑窗:从左到右、从上到下每次移动一个像素,计算该位置与模版的相似度,取最优位置。
若大图大小为 (W, H)、模版为 (w, h),则结果矩阵 R 大小为 (W-w+1, H-h+1)。把 R 可视化后,峰值(或谷值,取决于方法)对应最佳匹配位置:

(二)、实现
python
res = cv.matchTemplate(img, template, method)
img:待搜索图像template:模版method:相似度度量,常见有:- 平方差
TM_SQDIFF/TM_SQDIFF_NORMED:最好匹配接近 0,越大越差 → 取 最小值 - 相关
TM_CCORR/TM_CCORR_NORMED:数值越大越好;非归一化版易受亮度、背景干扰,峰值可能漂移 - 相关系数
TM_CCOEFF/TM_CCOEFF_NORMED:1 完美,-1 最差 → 取 最大值
- 平方差
匹配完成后用 cv.minMaxLoc(res) 取极值位置:
- 平方差类 → 用
min_loc - 相关 / 相关系数类 → 用
max_loc
实务建议:始终用灰度图做匹配,再把框画回彩色图。
示例:在大图中找 C 罗头像。

模版:

python
def show_template_matcher():
"""演示模版匹配"""
img = cv.imread(get_image_path("cluo.png"))
if img is None:
print("错误:无法读取图像 cluo.png")
return
img_t = cv.imread(get_image_path("cluo-T.png"))
if img_t is None:
print("错误:无法读取图像 cluo-T.png")
return
h_t, w_t = img_t.shape[:2]
img_bak = img.copy()
# 灰度配准更稳
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
img_tgray = cv.cvtColor(img_t, cv.COLOR_BGR2GRAY)
res = cv.matchTemplate(img_gray, img_tgray, cv.TM_CCORR_NORMED)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
# 归一化相关:取最大值位置
top_left = max_loc
bottom_right = (int(top_left[0] + w_t), int(top_left[1] + h_t))
cv.rectangle(img_bak, top_left, bottom_right, (0, 255, 0), 2)
plt.figure(figsize=(8, 5))
plt.subplot(2, 2, 1)
plt.imshow(img[:, :, ::-1])
plt.title("original Image")
plt.axis("off")
plt.subplot(2, 2, 2)
plt.imshow(img_t[:, :, ::-1])
plt.title("template Image")
plt.axis("off")
plt.subplot(2, 2, 3)
plt.imshow(res, cmap=plt.cm.gray)
plt.title("res")
plt.subplot(2, 2, 4)
plt.imshow(img_bak[:, :, ::-1])
plt.title("res Image")
plt.axis("off")
plt.tight_layout()
plt.show()

拓展:模版匹配不支持尺度变化、视角变化。这类场景应改用关键点匹配(SIFT、SURF 等):先分别提点,再匹配,对缩放、旋转、视角、光照更稳。
二、霍夫检测
(一)、原理
霍夫变换(Hough Transform)基于投票机制,在边缘二值图里检测可用数学描述的形状。OpenCV 主要用来检直线、圆。
核心:对偶映射 + 投票统计------把图像空间(x-y)里"找共线 / 共圆点"的难题,变换到参数空间,变成找峰值。
(二)、霍夫线检测
1、早期形式:斜率截距 y = kx + b
- 图像空间:点是
(x, y);直线由(k, b)确定 - 固定一点
(x0, y0),把(k, b)当变量 → 映射到参数空间的一条直线 - 缺点:竖线斜率无穷大,工程上已少用
2、标准形式:ρ-θ 极坐标
ρ = x cos θ + y sin θ \rho = x\cos\theta + y\sin\theta ρ=xcosθ+ysinθ
ρ:原点到直线的垂直距离θ:法线与 x 轴夹角(0~180°)
映射规则:
- 图像空间一个点
(x0, y0):θ 遍历 0~180°,得到一串 ρ → 在(θ, ρ)空间画一条正弦曲线 - 同一直线上多个点:各自一条正弦曲线,交于同一
(θ0, ρ0) - 该交点就是原图直线的参数


3、API:HoughLines vs HoughLinesP
python
# 标准霍夫:输出无限长直线的 (rho, theta)
lines = cv.HoughLines(edges, rho=1, theta=np.pi / 180, threshold=400)
# 概率霍夫:直接输出线段端点 (x1,y1,x2,y2)
raw_lines = cv.HoughLinesP(
edges, rho=1, theta=np.pi / 180, threshold=50,
minLineLength=500, maxLineGap=150,
)
HoughLines |
HoughLinesP |
|
|---|---|---|
| 输出 | (ρ, θ),需自己画成贯穿图的直线 |
线段端点,可直接画有限长度 |
| 速度 | 相对慢(全图投票) | 更快(随机采样边缘点) |
| 独有参数 | --- | minLineLength、maxLineGap |
| 适用 | 要完整直线方程、主方向 | 要实际线段、边长测量 |
共用参数
rho:ρ 方向网格步长(像素)。常规1;调大更快但精度降theta:θ 方向步长(弧度)。常用np.pi/180(1°)threshold:累加器投票阈值(核心)。票数 ≈ 落在该直线上的边缘像素数- 调高:只留明显长边,弱线易漏
- 调低:短线、噪点、伪直线增多
HoughLinesP 独有
minLineLength:最短线段长度;过小会引入划痕碎线maxLineGap:同一直线上两段允许的最大空隙;过小会把断边拆成多段
python
def filter_main_segments(lines, top_k=2, ang_min=20, ang_max=40, rho_gap=30):
"""
从概率霍夫结果中筛出主轮廓线段:
1) 按角度保留接近金属条方向的线段;
2) 按法向偏移 rho 聚类,同一条边只留最长段;
3) 按长度取前 top_k 条。
"""
if lines is None:
return None
segs = []
for x1, y1, x2, y2 in lines.reshape(-1, 4):
length = float(np.hypot(x2 - x1, y2 - y1))
ang = float(np.degrees(np.arctan2(y2 - y1, x2 - x1)))
if ang > 90:
ang -= 180
if ang < -90:
ang += 180
if not (ang_min <= abs(ang) <= ang_max):
continue
mx, my = (x1 + x2) / 2.0, (y1 + y2) / 2.0
th = np.radians(ang)
rho = mx * (-np.sin(th)) + my * np.cos(th)
segs.append(((int(x1), int(y1), int(x2), int(y2)), length, rho))
if not segs:
return None
segs.sort(key=lambda s: -s[1])
clusters = []
for seg in segs:
placed = False
for cluster in clusters:
if abs(seg[2] - cluster[0][2]) < rho_gap:
cluster.append(seg)
placed = True
break
if not placed:
clusters.append([seg])
picked = [max(cluster, key=lambda s: s[1]) for cluster in clusters]
picked.sort(key=lambda s: -s[1])
picked = picked[:top_k]
return np.array([s[0] for s in picked], dtype=np.int32)
def hough_lines_detect():
"""标准霍夫:Canny 提边 → HoughLines 在 (rho, theta) 投票"""
img = cv.imread(get_image_path("hough_lines.jpeg"))
if img is None:
print("错误:无法读取图像 hough_lines.jpeg")
return
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 不模糊 + 较高 Canny 高阈值:压台面反光,留住金属条长边
edges = cv.Canny(gray, threshold1=50, threshold2=250)
lines = cv.HoughLines(edges, rho=1, theta=np.pi / 180, threshold=600)
line_count = 0 if lines is None else len(lines)
print(f"HoughLines 检测到直线数量:{line_count}")
img_lines = img.copy()
if lines is not None:
length = int(np.hypot(img.shape[0], img.shape[1]))
for line in lines:
rho, theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + length * (-b))
y1 = int(y0 + length * a)
x2 = int(x0 - length * (-b))
y2 = int(y0 - length * a)
cv.line(img_lines, (x1, y1), (x2, y2), (0, 255, 0), 3)
plt.figure(figsize=(10, 6))
plt.subplot(1, 3, 1)
plt.imshow(img[:, :, ::-1])
plt.title("original Image")
plt.axis("off")
plt.subplot(1, 3, 2)
plt.imshow(edges, cmap="gray")
plt.title("Canny edges")
plt.axis("off")
plt.subplot(1, 3, 3)
plt.imshow(img_lines[:, :, ::-1])
plt.title(f"HoughLines (count={line_count})")
plt.axis("off")
plt.tight_layout()
plt.show()
def hough_lines_p_detect():
"""概率霍夫:闭运算连断边 + 加大 maxLineGap,再按角度/偏移筛主边"""
img = cv.imread(get_image_path("hough_lines.jpeg"))
if img is None:
print("错误:无法读取图像 hough_lines.jpeg")
return
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
blur = cv.GaussianBlur(gray, (5, 5), 0)
edges = cv.Canny(blur, threshold1=50, threshold2=150)
edges = cv.morphologyEx(
edges, cv.MORPH_CLOSE, cv.getStructuringElement(cv.MORPH_RECT, (9, 9))
)
raw_lines = cv.HoughLinesP(
edges, rho=1, theta=np.pi / 180, threshold=50,
minLineLength=500, maxLineGap=150,
)
raw_count = 0 if raw_lines is None else len(raw_lines.reshape(-1, 4))
lines = filter_main_segments(raw_lines, top_k=2)
line_count = 0 if lines is None else len(lines.reshape(-1, 4))
print(f"HoughLinesP 原始线段:{raw_count},筛选后主边:{line_count}")
img_lines = img.copy()
if lines is not None:
for x1, y1, x2, y2 in lines.reshape(-1, 4):
cv.line(img_lines, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 3)
plt.figure(figsize=(10, 6))
plt.subplot(1, 3, 1)
plt.imshow(img[:, :, ::-1])
plt.title("original Image")
plt.axis("off")
plt.subplot(1, 3, 2)
plt.imshow(edges, cmap="gray")
plt.title("Canny + close")
plt.axis("off")
plt.subplot(1, 3, 3)
plt.imshow(img_lines[:, :, ::-1])
plt.title(f"HoughLinesP (count={line_count})")
plt.axis("off")
plt.tight_layout()
plt.show()

(三)、霍夫圆检测
1、原理
圆方程:

圆心 (a, b) + 半径 r → 三维参数空间,直接投票很慢。OpenCV 使用霍夫梯度法,分成两阶段:

- 检圆心:圆心是圆周法线的交汇处;交汇直线数超过阈值 → 认为是圆心
- 定半径:圆心到圆周距离相同;相同距离的票数超过阈值 → 该距离为半径
2、API 与示例
python
circles = cv2.HoughCircles(
image, method, dp, minDist,
param1=100, param2=100, minRadius=0, maxRadius=0,
)
image:必须是灰度图method:固定cv2.HOUGH_GRADIENTdp:累加器分辨率反比;1精度高,2更快更粗;常规推荐1或1.2minDist:两圆心最小距离(核心)。太小假圆心扎堆;太大近邻真圆会漏param1:内部 Canny 高阈值,低阈值 =param1/2param2:圆心累加投票阈值。调高更严、易漏弱圆;调低易误检minRadius/maxRadius:半径上下限。已知大概尺寸时优先填,抑制假圆最有效
金属板有刷纹,且大孔 / 小孔半径差大时:中值滤波后按半径分段检测再合并,并做简单 NMS 去重。
python
def nms_circles(circles, dist_thresh=40):
"""相近圆心只保留半径更大的一个,简单去重"""
if not circles:
return []
kept = []
for x, y, r in sorted(circles, key=lambda c: -c[2]):
if any((x - kx) ** 2 + (y - ky) ** 2 < dist_thresh ** 2 for kx, ky, _ in kept):
continue
kept.append((x, y, r))
return kept
def hough_circles_detect():
"""霍夫圆:中值滤波压刷纹,大孔/小孔分段检测后合并"""
img = cv.imread(get_image_path("hough_circles.jpeg"))
if img is None:
print("错误:无法读取图像 hough_circles.jpeg")
return
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
blur = cv.medianBlur(gray, 15)
edges = cv.Canny(blur, threshold1=50, threshold2=150)
circles_large = cv.HoughCircles(
blur, cv.HOUGH_GRADIENT,
dp=1.2, minDist=250, param1=80, param2=35,
minRadius=250, maxRadius=380,
)
circles_small = cv.HoughCircles(
blur, cv.HOUGH_GRADIENT,
dp=1.2, minDist=100, param1=100, param2=45,
minRadius=60, maxRadius=220,
)
raw = []
for group in (circles_large, circles_small):
if group is None:
continue
for x, y, r in np.uint16(np.around(group))[0]:
raw.append((int(x), int(y), int(r)))
circles = nms_circles(raw)
circle_count = len(circles)
print(f"HoughCircles 检测到圆数量:{circle_count}")
for i, (x, y, r) in enumerate(circles, 1):
print(f" #{i}: center=({x}, {y}), radius={r}")
img_circles = img.copy()
for x, y, r in circles:
cv.circle(img_circles, (x, y), r, (0, 255, 0), 4)
cv.circle(img_circles, (x, y), 4, (0, 0, 255), -2)
plt.figure(figsize=(10, 6))
plt.subplot(1, 3, 1)
plt.imshow(img[:, :, ::-1])
plt.title("original Image")
plt.axis("off")
plt.subplot(1, 3, 2)
plt.imshow(edges, cmap="gray")
plt.title("median + Canny")
plt.axis("off")
plt.subplot(1, 3, 3)
plt.imshow(img_circles[:, :, ::-1])
plt.title(f"HoughCircles (count={circle_count})")
plt.axis("off")
plt.tight_layout()
plt.show()

三、总结与拓展
总结
- 模版匹配 :滑窗比相似度;适合固定尺度、固定角度;灰度 +
matchTemplate+minMaxLoc;不支持缩放 / 旋转 / 视角变化 - 霍夫线 :
HoughLines给(ρ, θ)无限直线;HoughLinesP给有限线段 +minLineLength/maxLineGap - 霍夫圆 :霍夫梯度法两阶段(圆心 → 半径);半径范围与
minDist是控假圆的关键
二者都是传统算法,在光照稳定、形变可控的工业场景落地简单。
业务拓展
- 模版匹配:固定位零件、二维码、印刷标识定位
- 霍夫:工件边线测量、圆孔定位、导轨 / 型材边线
- 有缩放 / 旋转 / 视角变化 → 换 SIFT 等特征点;更复杂场景可结合深度学习检测