第九章:OpenCV项目实战与代码整合
本章通过完整的项目案例,讲解如何从需求分析到代码实现、测试和优化,完成实际的计算机视觉项目。
9.1 项目一:智能监控入侵检测系统
9.1.1 项目需求
- 目标:实现一个智能监控系统,能够检测是否有物体进入特定区域,并触发警报。
- 功能要求:
- 检测视频中的移动目标。
- 判断目标是否进入指定区域。
- 在入侵区域高亮显示目标并记录时间。
9.1.2 系统设计
1. 数据流设计
- 视频输入 → 背景建模 → 移动目标检测 → 区域判断 → 触发警报
2. 技术选型
- 背景建模:使用
cv2.createBackgroundSubtractorMOG2
实现动态背景分离。 - 入侵区域:通过多边形顶点定义ROI(感兴趣区域)。
9.1.3 实现步骤
1. 视频流读取与背景分离
python
import cv2
import numpy as np
cap = cv2.VideoCapture("surveillance.mp4")
bg_subtractor = cv2.createBackgroundSubtractorMOG2(history=500, varThreshold=50)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 背景分离
fg_mask = bg_subtractor.apply(frame)
fg_mask = cv2.medianBlur(fg_mask, 5) # 去噪
cv2.imshow("Foreground Mask", fg_mask)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
2. 检测入侵区域
python
# 定义入侵区域
polygon = np.array([[100, 200], [300, 200], [300, 400], [100, 400]])
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
fg_mask = bg_subtractor.apply(frame)
fg_mask = cv2.medianBlur(fg_mask, 5)
# 查找轮廓
contours, _ = cv2.findContours(fg_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 500: # 忽略小目标
continue
x, y, w, h = cv2.boundingRect(contour)
centroid = (x + w // 2, y + h // 2)
# 判断目标是否在入侵区域
if cv2.pointPolygonTest(polygon, centroid, False) >= 0:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.putText(frame, "Intrusion Detected!", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
# 显示入侵区域
cv2.polylines(frame, [polygon], isClosed=True, color=(0, 255, 0), thickness=2)
cv2.imshow("Intrusion Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
9.1.4 功能扩展
- 触发警报:在检测到入侵时播放音效或发送警报邮件。
- 数据记录:在文件中记录入侵事件时间和位置信息。
触发警报代码示例
python
import winsound
def trigger_alarm():
winsound.Beep(1000, 500) # 播放警报声
# 在入侵检测代码中调用此函数
trigger_alarm()
数据记录代码示例
python
from datetime import datetime
with open("intrusion_log.txt", "a") as log_file:
log_file.write(f"Intrusion detected at {datetime.now()} in region {centroid}\n")
9.2 项目二:商品价格标签自动检测与识别
9.2.1 项目需求
- 目标:检测超市货架上的价格标签,并自动识别价格。
- 功能要求:
- 定位货架上的价格标签。
- 使用OCR技术提取价格文字信息。
9.2.2 系统设计
1. 处理步骤
- 图像预处理 → 标签检测 → OCR识别 → 数据输出
2. 技术选型
- 图像预处理:通过形态学操作增强边缘特征。
- 标签检测:使用轮廓检测。
- OCR识别:使用
pytesseract
库进行文字识别。
9.2.3 实现步骤
1. 检测价格标签
python
import cv2
img = cv2.imread("shelf.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
# 形态学操作
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
edges = cv2.dilate(edges, kernel, iterations=1)
# 查找轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
if 50 < w < 200 and 20 < h < 100: # 根据标签尺寸过滤
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("Price Tags", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2. 价格识别
python
import pytesseract
# 设置tesseract路径
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
# 对每个检测到的标签区域进行OCR
roi = img[y:y+h, x:x+w]
text = pytesseract.image_to_string(roi, config="--psm 7")
print(f"Detected Price: {text}")