DAMOYOLO-S模型推理结果可视化与报告生成教程 DAMOYOLO-S模型推理结果可视化与报告生成教程你是不是刚用DAMOYOLO-S模型跑完一批图片看着终端里密密麻麻的坐标和类别数字有点头疼这些数字虽然精确但既不直观也不方便拿给同事或老板看。我们做目标检测最终目的不是为了得到一堆数据而是为了“看见”和理解模型看到了什么。今天我就手把手带你搞定这件事把DAMOYOLO-S冷冰冰的推理结果变成一目了然的可视化图片、清晰的统计图表最后还能打包成一份可以直接拿去汇报的PDF报告。整个过程不需要复杂的工具就用我们最熟悉的Python。跟着做一遍你就能掌握一套从结果到展示的完整工作流。1. 准备工作理清思路与安装环境在开始写代码之前我们先花两分钟把整个流程想清楚。DAMOYOLO-S模型推理后通常会给我们每张图片的检测结果包括边界框物体在图片中的位置。类别物体是什么。置信度模型有多确定这个判断。我们的目标是把这些信息变成三样东西带标注的可视化图在原图上把框和标签画出来一眼就知道检测得对不对。统计图表看看哪些类别检测得多整体置信度如何把握整体情况。综合报告把前两者加上一些关键文字说明整合到一个PDF里。接下来把需要的“工具”准备好。打开你的终端或命令行创建一个新的Python虚拟环境是个好习惯然后安装下面几个库pip install opencv-python matplotlib numpy reportlab Pillow简单解释一下它们的分工opencv-python (cv2)用来读图片、画框、写文字最后保存可视化结果。它处理图片又快又方便。matplotlib numpy这对好搭档负责生成各种统计图表比如直方图、饼图。reportlab Pillow (PIL)它们是制作PDF报告的核心。reportlab用来创建和编辑PDFPIL则帮助我们把图片插入到PDF里。环境搞定我们就可以进入正题了。2. 第一步绘制带标注的可视化检测图假设我们已经有了推理结果。通常这个结果可能是一个列表里面每个元素对应一张图片的检测信息。我们写一个函数来处理它。2.1 用OpenCV绘制基础检测框我们先从最基础的开始用OpenCV把框和类别标签画到图片上。OpenCV速度快适合批量处理。import cv2 import numpy as np def visualize_detections_opencv(image_path, detections, class_names, conf_threshold0.5): 使用OpenCV可视化检测结果。 参数: image_path: 原始图片路径。 detections: 检测结果列表每个元素为 [x1, y1, x2, y2, conf, class_id]。 class_names: 类别名称列表索引对应class_id。 conf_threshold: 置信度阈值低于此值的检测框不显示。 返回: 绘制好检测框的图片 (numpy数组格式)。 # 1. 读取图片 img cv2.imread(image_path) if img is None: print(f警告: 无法读取图片 {image_path}) return None # 为了在图上画彩色框我们先复制一份原图 img_draw img.copy() # 2. 定义一些颜色和字体 (OpenCV使用BGR格式) colors [(0, 255, 0), (255, 0, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255)] # 绿蓝红青紫 font cv2.FONT_HERSHEY_SIMPLEX font_scale 0.6 thickness 2 # 3. 遍历每个检测框 for det in detections: # det格式假设为 [x1, y1, x2, y2, conf, class_id] x1, y1, x2, y2, conf, cls_id map(int, det[:6]) # 坐标和类别ID取整 if conf conf_threshold: continue # 跳过低置信度检测 # 为不同类别选择颜色 color colors[cls_id % len(colors)] # 4. 画矩形框 cv2.rectangle(img_draw, (x1, y1), (x2, y2), color, thickness) # 5. 准备标签文本类别名 置信度 label f{class_names[cls_id]}: {conf:.2f} # 计算文字背景框的大小让文字更清晰 (text_width, text_height), baseline cv2.getTextSize(label, font, font_scale, thickness) cv2.rectangle(img_draw, (x1, y1 - text_height - 10), (x1 text_width, y1), color, -1) # -1表示填充 cv2.putText(img_draw, label, (x1, y1 - 5), font, font_scale, (255, 255, 255), thickness) # 白色文字 return img_draw # 假设我们有一个检测结果示例 # detections [[100, 100, 200, 200, 0.95, 0], [150, 150, 250, 250, 0.87, 1]] # 格式示例 # class_names [person, car] # result_img visualize_detections_opencv(your_image.jpg, detections, class_names) # cv2.imwrite(result_with_boxes.jpg, result_img)这个函数做了几件事读取图片为每个超过置信度阈值的检测框选择一个颜色画出矩形并在框的顶部加上类别和置信度标签。你可以调整颜色、字体大小和线条粗细来匹配你的审美。2.2 进阶用Matplotlib绘制更美观的图如果你需要更精细的控制或者想生成直接用于PPT的图片Matplotlib是更好的选择。它可以输出更高质量的图像并且和后面的统计图表风格统一。import matplotlib.pyplot as plt import matplotlib.patches as patches from PIL import Image def visualize_detections_matplotlib(image_path, detections, class_names, conf_threshold0.5, save_pathNone): 使用Matplotlib可视化检测结果适合生成高质量展示图。 参数: image_path: 原始图片路径。 detections: 检测结果列表。 class_names: 类别名称列表。 conf_threshold: 置信度阈值。 save_path: 图片保存路径如果为None则显示图片。 # 1. 用PIL打开图片并转换为RGB (Matplotlib使用RGB) img_pil Image.open(image_path).convert(RGB) img_array np.array(img_pil) # 2. 创建图形 fig, ax plt.subplots(1, figsize(12, 8)) ax.imshow(img_array) # 3. 隐藏坐标轴 ax.axis(off) # 4. 定义颜色循环 colors plt.cm.tab10(np.linspace(0, 1, len(class_names))) # 使用tab10色彩映射 # 5. 遍历检测框 for det in detections: x1, y1, x2, y2, conf, cls_id det[:6] if conf conf_threshold: continue # 计算框的宽度和高度 width x2 - x1 height y2 - y1 # 创建矩形补丁 rect patches.Rectangle((x1, y1), width, height, linewidth2, edgecolorcolors[cls_id], facecolornone, alpha0.8) ax.add_patch(rect) # 添加文本标签 label f{class_names[int(cls_id)]}: {conf:.2f} ax.text(x1, y1 - 5, label, colorwhite, fontsize10, weightbold, bboxdict(facecolorcolors[cls_id], alpha0.8, edgecolornone, pad1)) plt.tight_layout() if save_path: plt.savefig(save_path, dpi150, bbox_inchestight, pad_inches0.1) print(f可视化图片已保存至: {save_path}) else: plt.show() plt.close(fig) # 使用示例 # visualize_detections_matplotlib(your_image.jpg, detections, class_names, save_pathmatplotlib_result.png)用Matplotlib画出来的图边框和文字背景的透明效果通常更好看也更容易统一图表风格。3. 第二步生成统计图表洞察整体结果看完了单张图片的效果我们再来看看整体数据集上的表现。统计图表能帮你快速回答这些问题哪个类别最常见检测的置信度整体高不高3.1 生成类别分布直方图这是最常用的图表之一一眼就能看出模型在哪些类别上检测得多。def plot_class_distribution(all_detections, class_names, conf_threshold0.5, save_pathNone): 绘制检测结果的类别分布直方图。 参数: all_detections: 所有图片的检测结果列表的列表。 class_names: 类别名称列表。 conf_threshold: 置信度阈值。 save_path: 图表保存路径。 # 1. 初始化一个计数器记录每个类别的检测数量 class_counts {name: 0 for name in class_names} # 2. 遍历所有图片的所有检测框 for dets_per_image in all_detections: for det in dets_per_image: _, _, _, _, conf, cls_id det[:6] if conf conf_threshold: class_name class_names[int(cls_id)] class_counts[class_name] 1 # 3. 准备绘图数据 classes list(class_counts.keys()) counts list(class_counts.values()) # 4. 创建图表 fig, ax plt.subplots(figsize(10, 6)) bars ax.bar(classes, counts, colorplt.cm.Set3(np.arange(len(classes)))) # 5. 添加数值标签 for bar, count in zip(bars, counts): height bar.get_height() ax.text(bar.get_x() bar.get_width()/2., height 0.5, f{count}, hacenter, vabottom, fontsize9) ax.set_xlabel(物体类别, fontsize12) ax.set_ylabel(检测数量, fontsize12) ax.set_title(DAMOYOLO-S检测结果类别分布, fontsize14, weightbold) plt.xticks(rotation45, haright) # 旋转类别标签防止重叠 plt.tight_layout() if save_path: plt.savefig(save_path, dpi150) print(f类别分布图已保存至: {save_path}) else: plt.show() plt.close(fig) # 使用示例all_detections 是一个列表每个元素是一张图片的detections列表 # plot_class_distribution(all_detections, class_names, save_pathclass_distribution.png)3.2 生成置信度分布直方图这个图能告诉你模型对自己的判断有多“自信”。如果大量检测框的置信度都集中在低区间可能需要调整模型阈值或检查数据。def plot_confidence_distribution(all_detections, conf_threshold0.5, save_pathNone): 绘制所有检测框的置信度分布直方图。 参数: all_detections: 所有图片的检测结果列表的列表。 conf_threshold: 置信度阈值用于过滤。 save_path: 图表保存路径。 # 1. 收集所有高于阈值的置信度 confidences [] for dets_per_image in all_detections: for det in dets_per_image: conf det[4] if conf conf_threshold: confidences.append(conf) if not confidences: print(没有高于阈值的检测框用于绘制置信度分布。) return # 2. 创建图表 fig, ax plt.subplots(figsize(10, 6)) # 绘制直方图分20个区间 n, bins, patches ax.hist(confidences, bins20, edgecolorblack, alpha0.7, colorskyblue) # 3. 添加平均置信度线 mean_conf np.mean(confidences) ax.axvline(mean_conf, colorred, linestyle--, linewidth2, labelf平均置信度: {mean_conf:.3f}) ax.set_xlabel(置信度, fontsize12) ax.set_ylabel(检测框数量, fontsize12) ax.set_title(检测框置信度分布, fontsize14, weightbold) ax.legend() ax.grid(True, alpha0.3) plt.tight_layout() if save_path: plt.savefig(save_path, dpi150) print(f置信度分布图已保存至: {save_path}) else: plt.show() plt.close(fig)4. 第三步组装一份专业的PDF分析报告最后我们把前面生成的所有好东西——可视化图片、统计图表、再加上一些关键数据——打包成一份漂亮的PDF报告。这里我们用reportlab库来创建PDF。from reportlab.lib.pagesizes import A4 from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, PageBreak from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import inch from reportlab.lib import colors from datetime import datetime def generate_pdf_report(output_pdf_path, title, summary_text, image_paths, chart_paths): 生成包含图片和图表的PDF报告。 参数: output_pdf_path: 输出的PDF文件路径。 title: 报告标题。 summary_text: 报告摘要文本。 image_paths: 可视化图片路径列表。 chart_paths: 统计图表路径列表。 # 1. 创建PDF文档 doc SimpleDocTemplate(output_pdf_path, pagesizeA4, rightMargin72, leftMargin72, topMargin72, bottomMargin18) Story [] styles getSampleStyleSheet() # 2. 添加标题 title_style ParagraphStyle(CustomTitle, parentstyles[Heading1], fontSize24, spaceAfter30, alignment1) # 1代表居中 Story.append(Paragraph(title, title_style)) Story.append(Spacer(1, 0.2*inch)) # 3. 添加报告生成时间 time_style ParagraphStyle(CustomTime, parentstyles[Normal], fontSize10, textColorcolors.grey) current_time datetime.now().strftime(%Y-%m-%d %H:%M:%S) Story.append(Paragraph(f报告生成时间: {current_time}, time_style)) Story.append(Spacer(1, 0.3*inch)) # 4. 添加摘要 Story.append(Paragraph(摘要, styles[Heading2])) Story.append(Spacer(1, 0.1*inch)) Story.append(Paragraph(summary_text, styles[Normal])) Story.append(Spacer(1, 0.3*inch)) # 5. 添加统计图表部分 Story.append(Paragraph(整体结果分析, styles[Heading2])) Story.append(Spacer(1, 0.2*inch)) for chart_path in chart_paths: try: # 调整图片大小以适应页面 img Image(chart_path, width6*inch, height4*inch) img.hAlign CENTER Story.append(img) Story.append(Spacer(1, 0.2*inch)) # 添加图表说明从文件名提取或自定义 chart_name chart_path.split(/)[-1].replace(.png, ).replace(_, ).title() Story.append(Paragraph(fi图表: {chart_name}/i, styles[Italic])) Story.append(Spacer(1, 0.3*inch)) except Exception as e: print(f无法添加图表 {chart_path}: {e}) # 6. 添加可视化样例部分 Story.append(PageBreak()) # 另起一页 Story.append(Paragraph(检测结果可视化样例, styles[Heading2])) Story.append(Spacer(1, 0.2*inch)) for i, img_path in enumerate(image_paths): try: img Image(img_path, width5.5*inch, height4*inch) # 控制图片大小 img.hAlign CENTER Story.append(img) Story.append(Spacer(1, 0.1*inch)) Story.append(Paragraph(fi样例 {i1}/i, styles[Italic])) Story.append(Spacer(1, 0.3*inch)) # 每两张图片后加个分隔避免太挤 if (i1) % 2 0: Story.append(Spacer(1, 0.2*inch)) except Exception as e: print(f无法添加图片 {img_path}: {e}) # 7. 生成PDF doc.build(Story) print(fPDF报告已生成: {output_pdf_path}) # 使用示例 # summary 本次对XX数据集的推理共检测到物体150个平均置信度为0.82。其中‘车辆’类别占比最高。 # image_list [result1.jpg, result2.jpg] # chart_list [class_distribution.png, confidence_dist.png] # generate_pdf_report(DAMOYOLO_检测报告.pdf, DAMOYOLO-S模型推理分析报告, summary, image_list, chart_list)这个函数创建了一个结构清晰的PDF标题、时间、摘要、统计图表、可视化样例。你可以根据需要调整样式、添加更多章节如“结论与建议”或表格。5. 把它们串起来一个完整的示例工作流现在我们把上面的所有步骤组合成一个完整的脚本。假设你有一个包含多张图片的文件夹并且已经用DAMOYOLO-S模型得到了推理结果这里我们用模拟数据代替。import os import glob import random # 模拟配置和数据 class_names [人, 自行车, 汽车, 摩托车, 公交车] image_dir ./sample_images # 你的图片文件夹 output_dir ./visualization_output os.makedirs(output_dir, exist_okTrue) # 假设的推理结果生成函数 (你需要替换成加载你真实结果的代码) def mock_detections_for_image(image_path): 模拟为一张图片生成检测结果。实际使用时请替换为加载你模型输出的代码。 # 这里随机生成1-3个检测框作为示例 num_dets random.randint(1, 3) dets [] img_w, img_h 640, 480 # 假设图片尺寸 for _ in range(num_dets): x1 random.randint(50, img_w-150) y1 random.randint(50, img_h-150) w random.randint(50, 120) h random.randint(50, 120) conf random.uniform(0.6, 0.98) cls_id random.randint(0, len(class_names)-1) dets.append([x1, y1, x1w, y1h, conf, cls_id]) return dets # 主流程 all_detections_list [] image_paths_for_report [] chart_paths [] # 1. 处理每张图片生成可视化结果 image_files glob.glob(os.path.join(image_dir, *.jpg))[:5] # 处理前5张作为示例 for idx, img_path in enumerate(image_files): print(f处理图片: {os.path.basename(img_path)}) detections mock_detections_for_image(img_path) all_detections_list.append(detections) # 使用Matplotlib生成可视化图片 output_img_path os.path.join(output_dir, fvis_{idx1}.png) visualize_detections_matplotlib(img_path, detections, class_names, save_pathoutput_img_path) image_paths_for_report.append(output_img_path) # 2. 生成统计图表 class_dist_chart os.path.join(output_dir, class_distribution.png) plot_class_distribution(all_detections_list, class_names, save_pathclass_dist_chart) chart_paths.append(class_dist_chart) conf_dist_chart os.path.join(output_dir, confidence_distribution.png) plot_confidence_distribution(all_detections_list, save_pathconf_dist_chart) chart_paths.append(conf_dist_chart) # 3. 生成报告摘要文本 (这里计算一些简单统计) total_detections sum([len(dets) for dets in all_detections_list]) summary_text f 本次对 {len(image_files)} 张样例图片进行了推理分析。 共检测到目标物体 b{total_detections}/b 个。 可视化结果与统计图表如下所示可用于进一步分析和汇报。 # 4. 生成PDF报告 report_path os.path.join(output_dir, DAMOYOLO_S_推理分析报告.pdf) generate_pdf_report(report_path, DAMOYOLO-S模型目标检测可视化报告, summary_text, image_paths_for_report[:3], # 报告中只放前3张可视化图 chart_paths) print(\n所有处理完成) print(f可视化图片保存在: {output_dir}) print(fPDF报告位于: {report_path})运行这个脚本你会在output_dir文件夹里得到所有带标注的图片、统计图表和一份完整的PDF报告。整个过程是自动化的你只需要准备好图片和真实的推理结果数据。6. 总结走完这一趟你应该已经掌握了将DAMOYOLO-S模型推理结果“变活”的整套方法。从最基础的用OpenCV画框到用Matplotlib制作更精美的可视化图和统计图表最后用reportlab把它们整合成一份专业的报告每一步的代码都不复杂但组合起来威力很大。这套流程的价值在于它把技术结果转化成了任何人都能理解的视觉信息。无论是自己分析模型表现还是向团队展示工作成果一份图文并茂的报告远比一堆数据文件有说服力。你可以根据自己的需求随意调整比如更换颜色主题、在PDF里加入模型性能指标表格、或者将多个模型的检测结果进行对比。工具已经交给你了接下来就看你如何发挥创意用它们更好地讲述你的模型故事了。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。