python Copy code
import argparse
from ultralytics import YOLO
import cv2
import os
from pathlib import Path
import re
import numpy as np
def transform_string(input_str):
"""
将类似 "['Fire', ['Fire', 'fire']] 0.83" 的字符串转换为 "Fire 0.83"
参数:
input_str (str): 输入的字符串
返回:
str: 转换后的字符串
"""
pattern = r"\['(\w+)',\s*\[.*\]\]\s*([\d.]+)"
match = re.match(pattern, input_str)
if match:
word = match.group(1)
number = match.group(2)
return f"{word} {number}"
else:
return input_str
def parse_args():
parser = argparse.ArgumentParser(description='YOLOv8 Object Detection')
parser.add_argument('--modelname', type=str, required=True, help='Path to YOLOv8 model')
parser.add_argument('--image_path', type=str, required=True, help='Path to image folder')
return parser.parse_args()
def detect_objects(model_path, image_folder):
# 为不同类别定义颜色映射
COLOR_MAP = {
'Person': (0, 255, 0), # 绿色
'Vehicle': (255, 0, 0), # 蓝色
'Fire': (0, 0, 255), # 红色
'Smoke': (255, 128, 0), # 青色
'Phone': (128, 0, 255), # 紫色
'Boat': (0, 255, 255), # 黄色
'Garbage': (255, 255, 0), # 浅蓝色
'default': (0, 255, 0) # 默认绿色
}
model_path = model_path.replace(" ", "")
image_folder = image_folder.replace(" ", "")
result_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.webp']
for ext in result_extensions:
result_images = list(Path(image_folder).glob(f'*_result{ext}'))
result_images.extend(Path(image_folder).glob(f'*_result{ext.upper()}'))
for img_path in result_images:
try:
os.remove(img_path)
print(f"已删除旧的结果图片: {img_path}")
except Exception as e:
print(f"无法删除文件 {img_path}: {e}")
model = YOLO(model_path)
image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.webp']
image_files = []
for ext in image_extensions:
image_files.extend(Path(image_folder).glob(f'*{ext}'))
image_files.extend(Path(image_folder).glob(f'*{ext.upper()}'))
for img_path in image_files:
if '_result' in img_path.stem:
continue
img = cv2.imread(str(img_path))
if img is None:
print(f"无法读取图片: {img_path}")
continue
if "垃圾检测" in str(img_path):
results = model.predict(img, save=False, conf=0.1, iou=0.3)
elif "水面漂浮物" in str(img_path):
results = model.predict(img, save=False, conf=0.1, iou=0.3)
else:
results = model(img)
if "吸烟" in str(img_path):
if results[0].boxes.shape[0] < 1:
results = model.predict(img, save=True, classes=0, conf=0.02, iou=0.2)
else:
results = model.predict(img, save=True, classes=0, conf=0.28, iou=0.5)
if "打电话" in str(img_path):
if results[0].boxes.shape[0] < 1:
results = model.predict(img, conf=0.03, save=True, classes=0, iou=0.1)
else:
results = model.predict(img, conf=0.47, save=True, classes=0, iou=0.7)
result = results[0]
height, width = img.shape[:2]
# 如果是人员统计场景,初始化计数器
if "人员统计" in str(img_path):
person_count = 0
vehicle_count = 0
# 存储所有标签位置,用于避免重叠
label_positions = []
# 绘制边界框和标签
for box in result.boxes:
x1, y1, x2, y2 = box.xyxy[0]
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
conf = float(box.conf)
cls = int(box.cls)
class_name = result.names[cls]
if isinstance(class_name, list):
class_name = class_name[0]
elif not isinstance(class_name, str):
class_name = str(class_name)
# 获取对应的颜色
color = COLOR_MAP.get(class_name, COLOR_MAP['default'])
label = f"{class_name} {conf:.2f}"
label = transform_string(label)
if "人员倒地" in str(img_path):
if 'person' in label:
continue
elif 'down' in label:
if conf < 0.38:
continue
# 如果是人员统计场景,需要处理特殊逻辑
if "人员统计" in str(img_path):
if 'Person' in class_name:
if conf < 0.3:
continue
else:
person_count += 1
elif 'Vehicle' in class_name:
if conf > 0.4:
vehicle_count += 1
# 获取标签文本的大小
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
thickness = 2
(text_width, text_height), baseline = cv2.getTextSize(label, font, font_scale, thickness)
# 计算标签的初始位置
text_x = x1
text_y = y1 - 10
# 如果标签会超出图像上边界,则将其放在框内的顶部
if text_y - text_height < 0:
text_y = y1 + text_height + 5
# 如果标签会超出图像右边界,向左调整
if text_x + text_width > width:
text_x = width - text_width - 5
# 确保x坐标不会小于0
text_x = max(text_x, 5)
# 避免标签重叠
label_rect = [text_x, text_y - text_height, text_x + text_width, text_y + 5]
max_attempts = 100 # 最大尝试次数
attempt = 0
while any(self_intersects(label_rect, pos) for pos in label_positions):
text_y += text_height + 5
label_rect = [text_x, text_y - text_height, text_x + text_width, text_y + 5]
# 如果向下移动太多,尝试其他位置
if text_y > y2:
text_y = y1 - 10
text_x = x1 + 10
label_rect = [text_x, text_y - text_height, text_x + text_width, text_y + 5]
attempt += 1
if attempt >= max_attempts:
print("Warning: Unable to place label without overlap after several attempts.")
break
label_positions.append(label_rect)
# 绘制边界框
cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
# 绘制半透明背景
overlay = img.copy()
cv2.rectangle(overlay,
(int(label_rect[0]), int(label_rect[1])),
(int(label_rect[2]), int(label_rect[3])),
color, -1)
cv2.addWeighted(overlay, 0.6, img, 0.4, 0, img)
# 绘制文本
cv2.putText(img, label, (int(text_x), int(text_y)), font, font_scale, (255, 255, 255), thickness)
# 如果是人员统计场景,在右上角显示统计结果
if "人员统计" in str(img_path):
stats_text = f"Result: {person_count} Person, {vehicle_count} Vehicle"
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
thickness = 2
(text_width, text_height), _ = cv2.getTextSize(stats_text, font, font_scale, thickness)
text_x = width - text_width - 10
text_y = text_height + 10
text_x = max(text_x, 0)
text_y = max(text_y, text_height + 10)
# 绘制统计结果的半透明背景
overlay = img.copy()
cv2.rectangle(overlay,
(text_x - 5, text_y - text_height - 5),
(text_x + text_width + 5, text_y + 5),
(0, 0, 255), -1)
cv2.addWeighted(overlay, 0.6, img, 0.4, 0, img)
cv2.putText(img, stats_text, (text_x, text_y), font, font_scale, (255, 255, 255), thickness)
output_path = img_path.parent / f"{img_path.stem}_result{img_path.suffix}"
cv2.imwrite(str(output_path), img)
print(f"处理完成: {img_path} -> {output_path}")
def self_intersects(rect1, rect2):
"""检查两个矩形是否相交"""
return not (rect1[2] < rect2[0] or # rect1在rect2左侧
rect1[0] > rect2[2] or # rect1在rect2右侧
rect1[3] < rect2[1] or # rect1在rect2上方
rect1[1] > rect2[3]) # rect1在rect2下方
def main():
args = parse_args()
detect_objects(args.modelname, args.image_path)
#detect_objects(r"C:\models\普通监控场景-10_消防通道占用检测\1118消防通道占用检测权重文件与测试代码\det_in960_out4_best_pt20241118_yoloworldm.pt", #r"C:\pictures\03_普通监控场景(10类)\1")
if __name__ == "__main__":
main()