欢迎光临
我们一直在努力

YOLO12代码实例:Python调用Ultralytics API实现批量检测

YOLO12代码实例:Python调用Ultralytics API实现批量检测

1. 项目概述

1.1 YOLO12模型简介

YOLO12是2025年发布的最新一代目标检测模型,采用了创新的注意力为中心架构。这个模型在保持实时推理速度的同时,实现了业界领先的检测精度,特别适合需要处理大量图像数据的应用场景。

想象一下,你有一个包含上千张图片的文件夹,需要快速找出所有包含特定物体的图片。传统方法可能需要人工一张张查看,费时费力。而使用YOLO12配合Python脚本,几分钟就能完成这个任务,还能生成详细的检测报告。

1.2 为什么选择批量检测

在实际项目中,我们很少只处理单张图片。更多时候需要:

  • 处理整个文件夹的图片
  • 批量分析监控录像帧
  • 自动化质检流水线
  • 大规模数据集标注

手动一张张处理既不现实也不高效。通过编程方式调用YOLO12的API,我们可以实现完全自动化的批量处理流程。

2. 环境准备与安装

2.1 基础环境要求

开始之前,确保你的环境满足以下要求:

  • Python 3.8或更高版本
  • 支持CUDA的GPU(推荐)或足够的CPU资源
  • 至少8GB内存(处理大批量图片时建议16GB以上)

如果你使用云服务器,选择配备RTX 4090或同等级GPU的实例会获得最佳性能。

2.2 安装必要库

打开终端或命令提示符,执行以下安装命令:

# 安装Ultralytics官方库
pip install ultralytics

# 安装其他辅助库
pip install opencv-python pillow tqdm

# 如果需要导出Excel报告
pip install pandas openpyxl

安装完成后,可以通过以下命令验证版本:

import ultralytics
print(ultralytics.__version__)

3. 基础单张图片检测

3.1 最简单的检测代码

让我们从最简单的例子开始,了解如何用几行代码实现目标检测:

from ultralytics import YOLO

# 加载预训练的YOLO12模型
model = YOLO('yolo12m.pt')

# 单张图片检测
results = model('image.jpg')

# 显示结果
results[0].show()

就是这么简单!四行代码就完成了图片加载、推理、结果可视化的全过程。

3.2 理解检测结果

检测返回的results对象包含丰富的信息:

# 获取第一个结果(单张图片)
result = results[0]

# 检测到的边界框信息
boxes = result.boxes
print(f"检测到 {len(boxes)} 个物体")

# 遍历每个检测结果
for box in boxes:
# 坐标信息
x1, y1, x2, y2 = box.xyxy[0].tolist()
# 置信度
confidence = box.conf[0].item()
# 类别ID和名称
class_id = box.cls[0].item()
class_name = result.names[class_id]

print(f"检测到 {class_name}, 置信度: {confidence:.2f}, 位置: [{x1:.1f}, {y1:.1f}, {x2:.1f}, {y2:.1f}]")

4. 实现批量图片检测

4.1 基本的批量处理脚本

现在我们来编写完整的批量检测脚本:

import os
from ultralytics import YOLO
from tqdm import tqdm
import cv2

class BatchYOLO12Detector:
def __init__(self, model_path='yolo12m.pt'):
"""初始化检测器"""
self.model = YOLO(model_path)
self.results = []

def process_folder(self, input_folder, output_folder, conf_threshold=0.25):
"""处理整个文件夹的图片"""
# 创建输出文件夹
os.makedirs(output_folder, exist_ok=True)

# 获取所有图片文件
image_extensions = ['.jpg', '.jpeg', '.png', '.bmp']
image_files = [
f for f in os.listdir(input_folder)
if os.path.splitext(f)[1].lower() in image_extensions
]

print(f"找到 {len(image_files)} 张图片待处理")

# 批量处理
for filename in tqdm(image_files, desc="处理图片"):
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename)

# 执行检测
results = self.model(input_path, conf=conf_threshold)
result = results[0]

# 保存带标注的图片
annotated_image = result.plot()
cv2.imwrite(output_path, annotated_image)

# 保存结果信息
self.results.append({
'filename': filename,
'boxes': result.boxes,
'original_size': result.orig_shape
})

return self.results

# 使用示例
if __name__ == "__main__":
detector = BatchYOLO12Detector()
results = detector.process_folder(
input_folder='./input_images',
output_folder='./output_images',
conf_threshold=0.3
)

4.2 高级批量处理功能

对于更复杂的需求,我们可以添加更多功能:

import json
import pandas as pd
from datetime import datetime

class AdvancedBatchDetector(BatchYOLO12Detector):
def __init__(self, model_path='yolo12m.pt'):
super().__init__(model_path)
self.detection_stats = []

def process_folder_advanced(self, input_folder, output_folder,
conf_threshold=0.25, save_json=True,
save_excel=True):
"""增强的批量处理方法"""
results = self.process_folder(input_folder, output_folder, conf_threshold)

if save_json:
self.save_results_json(results)

if save_excel:
self.generate_excel_report(results)

return results

def save_results_json(self, results):
"""保存详细结果到JSON文件"""
output_data = []

for result in results:
file_data = {
'filename': result['filename'],
'detections': [],
'detection_count': len(result['boxes']) if result['boxes'] else 0
}

if result['boxes'] is not None:
for box in result['boxes']:
detection = {
'class_id': int(box.cls[0].item()),
'class_name': self.model.names[int(box.cls[0].item())],
'confidence': float(box.conf[0].item()),
'bbox': box.xyxy[0].tolist()
}
file_data['detections'].append(detection)

output_data.append(file_data)

# 保存JSON文件
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
json_path = f'detection_results_{timestamp}.json'
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(output_data, f, ensure_ascii=False, indent=2)

print(f"详细结果已保存到: {json_path}")

def generate_excel_report(self, results):
"""生成Excel格式的检测报告"""
report_data = []

for result in results:
if result['boxes'] is not None:
for box in result['boxes']:
report_data.append({
'文件名': result['filename'],
'物体类别': self.model.names[int(box.cls[0].item())],
'置信度': round(box.conf[0].item(), 3),
'左上X': round(box.xyxy[0][0].item(), 1),
'左上Y': round(box.xyxy[0][1].item(), 1),
'右下X': round(box.xyxy[0][2].item(), 1),
'右下Y': round(box.xyxy[0][3].item(), 1)
})

if report_data:
df = pd.DataFrame(report_data)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
excel_path = f'detection_report_{timestamp}.xlsx'
df.to_excel(excel_path, index=False)
print(f"Excel报告已生成: {excel_path}")

5. 实用技巧与优化建议

5.1 性能优化技巧

处理大量图片时,性能优化很重要:

def optimize_detection_performance():
"""性能优化配置示例"""
model = YOLO('yolo12m.pt')

# 优化配置
results = model(
'image.jpg',
conf=0.25, # 置信度阈值
iou=0.45, # IOU阈值
imgsz=640, # 推理尺寸(较小尺寸更快)
half=True, # 使用半精度浮点数(GPU)
device='0', # 指定GPU设备
verbose=False, # 减少输出信息
max_det=100, # 每张图片最大检测数量
agnostic_nms=False, # 类别无关的NMS
)

5.2 内存管理策略

处理超大图片集时,需要注意内存管理:

class MemoryEfficientDetector:
"""内存友好的批量检测器"""

def process_large_dataset(self, input_folder, output_folder, batch_size=10):
"""分批处理大量图片,避免内存溢出"""
# 获取所有图片文件
image_files = [f for f in os.listdir(input_folder)
if f.lower().endswith(('.png', '.jpg', '.jpeg'))]

# 分批处理
for i in range(0, len(image_files), batch_size):
batch_files = image_files[i:i+batch_size]
print(f"处理批次 {i//batch_size + 1}/{(len(image_files)-1)//batch_size + 1}")

for filename in batch_files:
# 处理单张图片并立即释放资源
self.process_single_image(
os.path.join(input_folder, filename),
os.path.join(output_folder, filename)
)

def process_single_image(self, input_path, output_path):
"""处理单张图片并保存结果"""
# 每次重新创建模型(如果内存紧张)
model = YOLO('yolo12m.pt')
results = model(input_path)

# 保存结果
annotated_image = results[0].plot()
cv2.imwrite(output_path, annotated_image)

# 显式释放资源
del model
del results

6. 实际应用案例

6.1 监控视频帧分析

假设你有一段监控视频,需要分析其中所有行人出现的帧:

def analyze_surveillance_footage(video_path, output_folder, target_class='person'):
"""分析监控视频,检测特定类别"""
import cv2

# 创建输出文件夹
os.makedirs(output_folder, exist_ok=True)

# 加载视频
cap = cv2.VideoCapture(video_path)
model = YOLO('yolo12m.pt')

frame_count = 0
detection_count = 0

while True:
ret, frame = cap.read()
if not ret:
break

# 每10帧处理一次(根据需求调整)
if frame_count % 10 == 0:
results = model(frame, classes=[0]) # 0通常是person类别

if len(results[0].boxes) > 0:
# 保存检测到目标的帧
output_path = os.path.join(output_folder, f"frame_{frame_count:06d}.jpg")
annotated_frame = results[0].plot()
cv2.imwrite(output_path, annotated_frame)
detection_count += 1

frame_count += 1

print(f"分析完成!在 {frame_count} 帧中检测到 {detection_count} 帧包含{target_class}")

cap.release()
return detection_count

6.2 产品质量检测

用于生产线上的产品缺陷检测:

def product_quality_inspection(image_folder, defect_classes=['scratch', 'dent', 'crack']):
"""产品质量自动检测"""
model = YOLO('yolo12m.pt')

# 获取所有产品图片
product_images = [f for f in os.listdir(image_folder)
if f.endswith(('.jpg', '.png'))]

inspection_results = []

for image_file in product_images:
image_path = os.path.join(image_folder, image_file)
results = model(image_path)

# 检查是否有缺陷
has_defect = False
defects_found = []

if results[0].boxes is not None:
for box in results[0].boxes:
class_id = int(box.cls[0].item())
class_name = model.names[class_id]

if class_name in defect_classes:
has_defect = True
defects_found.append(class_name)

# 记录结果
result = {
'product_id': image_file,
'has_defect': has_defect,
'defects': defects_found,
'inspection_time': datetime.now().isoformat()
}

inspection_results.append(result)

# 生成质检报告
self.generate_quality_report(inspection_results)

return inspection_results

7. 常见问题与解决方案

7.1 性能相关问题

问题:处理速度太慢

  • 解决方案:减小推理尺寸(imgsz=640),使用half精度,确保使用GPU

问题:内存不足

  • 解决方案:减小batch_size,使用分批处理,清理不再需要的变量

7.2 结果质量相关问题

问题:漏检太多物体

  • 解决方案:降低置信度阈值(conf=0.1),检查图片尺寸是否合适

问题:误检太多

  • 解决方案:提高置信度阈值(conf=0.5),调整IOU阈值

7.3 代码调试技巧

# 调试模式下的详细输出
results = model(
'image.jpg',
verbose=True, # 显示详细处理信息
save=True, # 自动保存结果
save_txt=True, # 保存文本标注
save_conf=True # 保存置信度
)

# 检查GPU是否可用
import torch
print(f"GPU可用: {torch.cuda.is_available()}")
print(f"GPU数量: {torch.cuda.device_count()}")
if torch.cuda.is_available():
print(f"当前GPU: {torch.cuda.get_device_name(0)}")

8. 总结

通过本文的代码实例,你应该已经掌握了使用Python调用YOLO12 Ultralytics API实现批量检测的核心技能。记住几个关键点:

  • 从小开始:先用少量图片测试,确保代码正常工作后再处理大批量数据
  • 内存管理:处理大量图片时注意内存使用,适当分批处理
  • 结果验证:总是检查部分结果,确保检测质量符合预期
  • 性能调优:根据实际需求调整参数,平衡速度和精度
  • YOLO12的强大功能加上Python的灵活性,为各种批量视觉检测任务提供了完美的解决方案。无论是学术研究还是工业应用,这个组合都能帮你节省大量时间和精力。


    获取更多AI镜像

    想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。

    赞(0)
    未经允许不得转载:171主机测评 » YOLO12代码实例:Python调用Ultralytics API实现批量检测
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址