上传文件至 /
这个提交包含在:
111
export_data.py
普通文件
111
export_data.py
普通文件
@ -0,0 +1,111 @@
|
|||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from datetime import datetime
|
||||||
|
from config import *
|
||||||
|
from utils import create_directory, draw_detection
|
||||||
|
|
||||||
|
|
||||||
|
def export_detection_data(detection_data, filename):
|
||||||
|
"""导出检测数据到CSV文件"""
|
||||||
|
create_directory(EXPORT_DIR)
|
||||||
|
|
||||||
|
filepath = os.path.join(EXPORT_DIR, filename)
|
||||||
|
|
||||||
|
with open(filepath, 'w', newline='') as csvfile:
|
||||||
|
fieldnames = ['frame', 'timestamp', 'object_id', 'x', 'y', 'width', 'height']
|
||||||
|
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
||||||
|
|
||||||
|
writer.writeheader()
|
||||||
|
for data in detection_data:
|
||||||
|
writer.writerow(data)
|
||||||
|
|
||||||
|
print(f"检测数据已导出到: {filepath}")
|
||||||
|
|
||||||
|
|
||||||
|
def export_detection_summary(detection_data, filename):
|
||||||
|
"""导出检测摘要到JSON文件"""
|
||||||
|
create_directory(EXPORT_DIR)
|
||||||
|
|
||||||
|
# 计算摘要统计信息
|
||||||
|
total_frames = max([d['frame'] for d in detection_data]) if detection_data else 0
|
||||||
|
total_objects = len(detection_data)
|
||||||
|
unique_objects = len(set([d['object_id'] for d in detection_data]))
|
||||||
|
|
||||||
|
# 计算平均检测大小
|
||||||
|
avg_width = sum([d['width'] for d in detection_data]) / total_objects if total_objects > 0 else 0
|
||||||
|
avg_height = sum([d['height'] for d in detection_data]) / total_objects if total_objects > 0 else 0
|
||||||
|
|
||||||
|
summary = {
|
||||||
|
"export_date": datetime.now().isoformat(),
|
||||||
|
"total_frames": total_frames,
|
||||||
|
"total_detections": total_objects,
|
||||||
|
"unique_objects": unique_objects,
|
||||||
|
"average_width": avg_width,
|
||||||
|
"average_height": avg_height,
|
||||||
|
"detection_data": detection_data
|
||||||
|
}
|
||||||
|
|
||||||
|
filepath = os.path.join(EXPORT_DIR, filename)
|
||||||
|
|
||||||
|
with open(filepath, 'w') as jsonfile:
|
||||||
|
json.dump(summary, jsonfile, indent=4)
|
||||||
|
|
||||||
|
print(f"检测摘要已导出到: {filepath}")
|
||||||
|
|
||||||
|
|
||||||
|
def export_frames_with_detections(video_path, detection_data, output_dir):
|
||||||
|
"""导出包含检测结果的帧图像"""
|
||||||
|
create_directory(output_dir)
|
||||||
|
|
||||||
|
cap = cv2.VideoCapture(video_path)
|
||||||
|
|
||||||
|
if not cap.isOpened():
|
||||||
|
print(f"错误: 无法打开视频文件 {video_path}")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 获取检测帧的集合
|
||||||
|
detection_frames = set([d['frame'] for d in detection_data])
|
||||||
|
|
||||||
|
frame_count = 0
|
||||||
|
saved_count = 0
|
||||||
|
|
||||||
|
while True:
|
||||||
|
ret, frame = cap.read()
|
||||||
|
if not ret:
|
||||||
|
break
|
||||||
|
|
||||||
|
frame_count += 1
|
||||||
|
|
||||||
|
if frame_count in detection_frames:
|
||||||
|
# 绘制检测框
|
||||||
|
frame_detections = [d for d in detection_data if d['frame'] == frame_count]
|
||||||
|
for detection in frame_detections:
|
||||||
|
frame = draw_detection(
|
||||||
|
frame,
|
||||||
|
detection['x'],
|
||||||
|
detection['y'],
|
||||||
|
detection['width'],
|
||||||
|
detection['height'],
|
||||||
|
f"Obj_{detection['object_id']}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 保存帧
|
||||||
|
filename = os.path.join(output_dir, f"frame_{frame_count}.jpg")
|
||||||
|
cv2.imwrite(filename, frame, [cv2.IMWRITE_JPEG_QUALITY, EXPORT_IMAGE_QUALITY])
|
||||||
|
saved_count += 1
|
||||||
|
|
||||||
|
cap.release()
|
||||||
|
print(f"已导出 {saved_count} 个包含检测结果的帧到 {output_dir}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 示例用法
|
||||||
|
sample_data = [
|
||||||
|
{"frame": 1, "timestamp": 0.1, "object_id": 0, "x": 100, "y": 100, "width": 50, "height": 50},
|
||||||
|
{"frame": 2, "timestamp": 0.2, "object_id": 0, "x": 105, "y": 105, "width": 55, "height": 55},
|
||||||
|
{"frame": 2, "timestamp": 0.2, "object_id": 1, "x": 200, "y": 200, "width": 60, "height": 60},
|
||||||
|
]
|
||||||
|
|
||||||
|
export_detection_data(sample_data, "sample_detection.csv")
|
||||||
|
export_detection_summary(sample_data, "sample_summary.json")
|
||||||
87
realtime_detection.py
普通文件
87
realtime_detection.py
普通文件
@ -0,0 +1,87 @@
|
|||||||
|
import cv2
|
||||||
|
import time
|
||||||
|
from config import *
|
||||||
|
from utils import draw_detection, preprocess_image
|
||||||
|
from export_data import export_detection_data
|
||||||
|
|
||||||
|
|
||||||
|
def realtime_detection():
|
||||||
|
"""实时摄像头检测"""
|
||||||
|
# 加载训练好的分类器
|
||||||
|
cascade = cv2.CascadeClassifier(MODEL_PATH)
|
||||||
|
|
||||||
|
if cascade.empty():
|
||||||
|
print("错误: 无法加载分类器文件")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 打开摄像头
|
||||||
|
cap = cv2.VideoCapture(0)
|
||||||
|
|
||||||
|
if not cap.isOpened():
|
||||||
|
print("错误: 无法访问摄像头")
|
||||||
|
return
|
||||||
|
|
||||||
|
print("实时检测已启动,按 'q' 退出,按 's' 保存当前帧")
|
||||||
|
|
||||||
|
detection_data = []
|
||||||
|
frame_count = 0
|
||||||
|
|
||||||
|
while True:
|
||||||
|
ret, frame = cap.read()
|
||||||
|
if not ret:
|
||||||
|
break
|
||||||
|
|
||||||
|
frame_count += 1
|
||||||
|
timestamp = time.time()
|
||||||
|
|
||||||
|
# 预处理图像
|
||||||
|
gray = preprocess_image(frame)
|
||||||
|
|
||||||
|
# 检测物体
|
||||||
|
objects = cascade.detectMultiScale(
|
||||||
|
gray,
|
||||||
|
scaleFactor=SCALE_FACTOR,
|
||||||
|
minNeighbors=MIN_NEIGHBORS,
|
||||||
|
minSize=MIN_SIZE,
|
||||||
|
maxSize=MAX_SIZE
|
||||||
|
)
|
||||||
|
|
||||||
|
# 绘制检测结果
|
||||||
|
for i, (x, y, w, h) in enumerate(objects):
|
||||||
|
frame = draw_detection(frame, x, y, w, h, "Object")
|
||||||
|
|
||||||
|
# 记录检测数据
|
||||||
|
detection_data.append({
|
||||||
|
"frame": frame_count,
|
||||||
|
"timestamp": timestamp,
|
||||||
|
"object_id": i,
|
||||||
|
"x": x,
|
||||||
|
"y": y,
|
||||||
|
"width": w,
|
||||||
|
"height": h
|
||||||
|
})
|
||||||
|
|
||||||
|
# 显示结果
|
||||||
|
cv2.imshow('Real-time Object Detection', frame)
|
||||||
|
|
||||||
|
# 键盘操作
|
||||||
|
key = cv2.waitKey(1) & 0xFF
|
||||||
|
if key == ord('q'):
|
||||||
|
break
|
||||||
|
elif key == ord('s'):
|
||||||
|
# 保存当前帧
|
||||||
|
filename = f"exports/frame_{frame_count}.jpg"
|
||||||
|
cv2.imwrite(filename, frame)
|
||||||
|
print(f"已保存: {filename}")
|
||||||
|
|
||||||
|
# 释放资源
|
||||||
|
cap.release()
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
|
||||||
|
# 导出检测数据
|
||||||
|
export_detection_data(detection_data, "realtime_detection.csv")
|
||||||
|
print("检测数据已导出到 exports/realtime_detection.csv")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
realtime_detection()
|
||||||
2
requirements.txt
普通文件
2
requirements.txt
普通文件
@ -0,0 +1,2 @@
|
|||||||
|
opencv-python>=4.5.0
|
||||||
|
numpy>=1.19.0
|
||||||
49
train_model.py
普通文件
49
train_model.py
普通文件
@ -0,0 +1,49 @@
|
|||||||
|
import cv2
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
from config import *
|
||||||
|
from utils import create_directory
|
||||||
|
|
||||||
|
|
||||||
|
def create_samples():
|
||||||
|
"""创建正样本向量文件"""
|
||||||
|
create_directory("models")
|
||||||
|
|
||||||
|
cmd = [
|
||||||
|
"opencv_createsamples",
|
||||||
|
"-info", "positive.txt",
|
||||||
|
"-num", str(NUM_POSITIVE_SAMPLES),
|
||||||
|
"-w", str(OBJECT_WIDTH),
|
||||||
|
"-h", str(OBJECT_HEIGHT),
|
||||||
|
"-vec", "positives.vec"
|
||||||
|
]
|
||||||
|
|
||||||
|
print("执行命令:", " ".join(cmd))
|
||||||
|
subprocess.run(cmd)
|
||||||
|
print("正样本向量文件已创建: positives.vec")
|
||||||
|
|
||||||
|
|
||||||
|
def train_cascade():
|
||||||
|
"""训练级联分类器"""
|
||||||
|
cmd = [
|
||||||
|
"opencv_traincascade",
|
||||||
|
"-data", "models",
|
||||||
|
"-vec", "positives.vec",
|
||||||
|
"-bg", "negatives.txt",
|
||||||
|
"-numPos", str(NUM_POSITIVE_SAMPLES // 2), # 使用一半的正样本
|
||||||
|
"-numNeg", str(NUM_NEGATIVE_SAMPLES // 2), # 使用一半的负样本
|
||||||
|
"-numStages", str(NUM_STAGES),
|
||||||
|
"-w", str(OBJECT_WIDTH),
|
||||||
|
"-h", str(OBJECT_HEIGHT),
|
||||||
|
"-featureType", "HAAR"
|
||||||
|
]
|
||||||
|
|
||||||
|
print("执行命令:", " ".join(cmd))
|
||||||
|
print("训练可能需要很长时间,请耐心等待...")
|
||||||
|
subprocess.run(cmd)
|
||||||
|
print("训练完成! 模型保存在 models/cascade.xml")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
create_samples()
|
||||||
|
train_cascade()
|
||||||
在新工单中引用
屏蔽一个用户