#边缘检测与轮廓提取:Canny 算子、霍夫变换
#1. Canny 边缘检测
import cv2
import numpy as np
img = cv2.imread("photo.jpg", 0)
# Canny 边缘检测
edges = cv2.Canny(img, 100, 200)
cv2.imshow("Edges", edges)
cv2.waitKey(0)#2. 霍夫变换
#2.1 直线检测
import cv2
import numpy as np
img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
# 霍夫直线变换
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=100, maxLineGap=10)
# 绘制直线
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.imshow("Lines", img)
cv2.waitKey(0)#2.2 圆检测
import cv2
import numpy as np
img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 霍夫圆检测
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20,
param1=50, param2=30, minRadius=0, maxRadius=0)
if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2)
cv2.imshow("Circles", img)
cv2.waitKey(0)#3. 轮廓提取
import cv2
import numpy as np
img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)
cv2.imshow("Contours", img)
cv2.waitKey(0)#4. 小结
边缘检测三大工具:
1. Canny:最常用的边缘检测算子
2. 霍夫变换:检测直线和圆
3. 轮廓提取:获取对象的轮廓
应用场景:
- 物体检测 → 轮廓提取
- 车道线检测 → 霍夫直线
- 圆形物体检测 → 霍夫圆💡 记住:边缘检测是目标检测的前置步骤。
🔗 扩展阅读

