第八章:案例综合与行业应用
本章将结合具体案例,展示OpenCV在多个行业中的应用,并提供完整代码和解决方案。
8.1 自动驾驶中的应用
8.1.1 车道线检测
思路:
- 读取行车视频并将图像转换为灰度图。
- 使用Canny边缘检测提取边缘。
- 通过霍夫变换检测直线,识别车道线。
示例代码:
python
import cv2
import numpy as np
def region_of_interest(img, vertices):
mask = np.zeros_like(img)
cv2.fillPoly(mask, vertices, 255)
return cv2.bitwise_and(img, mask)
def draw_lines(img, lines):
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 5)
cap = cv2.VideoCapture("driving.mp4")
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
height, width = edges.shape
roi_vertices = np.array([[(0, height), (width//2, height//2), (width, height)]], dtype=np.int32)
cropped_edges = region_of_interest(edges, roi_vertices)
lines = cv2.HoughLinesP(cropped_edges, 1, np.pi/180, 50, minLineLength=50, maxLineGap=200)
if lines is not None:
draw_lines(frame, lines)
cv2.imshow("Lane Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
8.2 医疗图像处理
8.2.1 X光图像异常检测
思路:
- 对X光图像进行预处理,如直方图均衡化。
- 使用卷积神经网络(CNN)检测异常区域。
- 将结果可视化。
示例代码:
python
import cv2
# 加载X光图像
img = cv2.imread("xray.jpg", cv2.IMREAD_GRAYSCALE)
# 直方图均衡化
equalized_img = cv2.equalizeHist(img)
# 边缘检测
edges = cv2.Canny(equalized_img, 50, 150)
# 显示结果
cv2.imshow("Original X-Ray", img)
cv2.imshow("Equalized X-Ray", equalized_img)
cv2.imshow("Edges", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
8.3 工业自动化中的质量检测
8.3.1 产品表面瑕疵检测
思路:
- 使用模板匹配找到参考区域。
- 通过像素差异判断表面是否存在瑕疵。
示例代码:
python
template = cv2.imread("template.jpg", cv2.IMREAD_GRAYSCALE)
product = cv2.imread("product.jpg", cv2.IMREAD_GRAYSCALE)
# 模板匹配
result = cv2.matchTemplate(product, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
top_left = max_loc
h, w = template.shape
bottom_right = (top_left[0] + w, top_left[1] + h)
# 标注瑕疵区域
cv2.rectangle(product, top_left, bottom_right, 255, 2)
cv2.imshow("Product Inspection", product)
cv2.waitKey(0)
cv2.destroyAllWindows()
8.4 智能安防系统
8.4.1 人脸识别与跟踪
示例代码:
python
import cv2
# 加载人脸检测模型
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Face Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
8.5 机器人导航与避障
8.5.1 激光雷达模拟与路径规划
示例代码:
python
import cv2
import numpy as np
# 创建空白地图
map_size = 500
map_img = np.zeros((map_size, map_size, 3), dtype=np.uint8)
# 随机生成障碍物
for _ in range(50):
x, y = np.random.randint(0, map_size, 2)
cv2.circle(map_img, (x, y), 5, (255, 255, 255), -1)
# 路径规划 (A*算法可嵌入此处)
start = (50, 50)
goal = (450, 450)
cv2.circle(map_img, start, 10, (0, 255, 0), -1)
cv2.circle(map_img, goal, 10, (0, 0, 255), -1)
cv2.imshow("Robot Navigation Map", map_img)
cv2.waitKey(0)
cv2.destroyAllWindows()