
cv_resnet101_face-detection_cvpr22papermogface代码实例自定义置信度颜色映射与动态标注你是不是也遇到过这样的问题在处理人脸检测任务时模型输出的结果虽然准确但展示方式却千篇一律——绿色的框、黑色的字所有检测结果看起来都一样。当图片中有多个人脸时你很难一眼看出哪些是模型高度确信的哪些是可能存在误判的。今天我要分享的就是如何为MogFace人脸检测工具添加一个实用功能自定义置信度颜色映射与动态标注。通过这个功能你可以让检测结果“开口说话”——用不同的颜色告诉你每个检测框的可靠程度让数据可视化变得更加直观和智能。1. 项目快速上手从零部署MogFace检测工具1.1 环境准备与一键安装首先让我们快速搭建运行环境。你只需要准备一个支持CUDA的GPU环境如果没有GPUCPU也能运行只是速度会慢一些。# 创建并激活虚拟环境可选但推荐 python -m venv mogface_env source mogface_env/bin/activate # Linux/Mac # 或 mogface_env\Scripts\activate # Windows # 安装核心依赖 pip install modelscope1.8.4 pip install opencv-python4.8.1 pip install torch2.0.1 torchvision0.15.2 pip install streamlit1.28.0 pip install Pillow10.0.0 pip install numpy1.24.3如果你有NVIDIA显卡建议安装对应版本的torch CUDA版本这样可以大幅提升检测速度。1.2 模型下载与配置MogFace模型需要从ModelScope获取。这里我提供一个完整的下载和配置脚本# download_model.py import os from modelscope import snapshot_download # 指定模型保存路径 model_dir /root/ai-models/iic/cv_resnet101_face-detection_cvpr22papermogface # 如果目录不存在则创建 os.makedirs(model_dir, exist_okTrue) # 下载模型 print(正在下载MogFace模型...) model_path snapshot_download( damo/cv_resnet101_face-detection_cvpr22papermogface, cache_dirmodel_dir ) print(f模型已下载到: {model_path})运行这个脚本模型就会自动下载到指定目录。整个过程可能需要几分钟取决于你的网络速度。1.3 基础应用代码解析让我们先看看基础版本的应用代码结构# app_basic.py - 基础版本 import streamlit as st from modelscope.pipelines import pipeline from modelscope.utils.constant import Tasks import cv2 import numpy as np from PIL import Image import json # 设置页面布局 st.set_page_config(layoutwide) st.title(️ MogFace 人脸检测工具) # 加载模型使用缓存避免重复加载 st.cache_resource def load_model(): model_path /root/ai-models/iic/cv_resnet101_face-detection_cvpr22papermogface face_detection pipeline(Tasks.face_detection, modelmodel_path) return face_detection # 初始化模型 face_detection load_model() # 创建两列布局 col1, col2 st.columns(2) with col1: st.header( 上传图片) uploaded_file st.file_uploader(选择图片文件, type[jpg, png, jpeg]) if uploaded_file is not None: # 读取图片 image Image.open(uploaded_file) image_np np.array(image) st.image(image, caption原始图片, use_column_widthTrue) with col2: st.header( 检测结果) if uploaded_file is not None: if st.button( 开始检测, typeprimary): # 执行人脸检测 result face_detection(image_np) # 绘制检测框 result_image image_np.copy() faces result[boxes] scores result[scores] for box, score in zip(faces, scores): x1, y1, x2, y2 map(int, box[:4]) # 绘制绿色矩形框 cv2.rectangle(result_image, (x1, y1), (x2, y2), (0, 255, 0), 2) # 添加置信度文本 label f{score:.2f} cv2.putText(result_image, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # 显示结果 st.image(result_image, captionf检测到 {len(faces)} 个人脸, use_column_widthTrue) # 显示原始数据 with st.expander(查看JSON原始数据): st.json(result)这个基础版本已经能够完成基本的人脸检测功能但所有的检测框都是绿色的无法直观地区分不同置信度的检测结果。2. 核心功能升级自定义置信度颜色映射2.1 为什么需要颜色映射在多人脸场景中不同的检测框可能具有不同的置信度得分。比如清晰的正脸置信度通常很高0.95以上侧脸或遮挡脸置信度可能中等0.7-0.9远处或模糊的人脸置信度可能较低0.5-0.7如果所有框都用同一种颜色你就无法快速识别哪些是高质量检测哪些可能需要人工复核。2.2 实现智能颜色映射函数让我们创建一个智能的颜色映射系统根据置信度自动选择合适的颜色# color_mapping.py - 颜色映射核心功能 import cv2 import numpy as np def get_color_by_confidence(confidence, colormaprainbow): 根据置信度得分返回对应的颜色 参数: confidence: 置信度得分 (0-1之间) colormap: 颜色映射方案可选 rainbow, heat, traffic_light 返回: (B, G, R) 格式的颜色元组 # 确保置信度在0-1范围内 confidence max(0.0, min(1.0, confidence)) if colormap rainbow: # 彩虹色映射低置信度-紫色高置信度-红色 # 将0-1映射到0-240OpenCV的HSV范围 hue int(confidence * 240) # 创建HSV颜色 color_hsv np.uint8([[[hue, 255, 255]]]) # 转换为BGR color_bgr cv2.cvtColor(color_hsv, cv2.COLOR_HSV2BGR)[0][0] return tuple(map(int, color_bgr)) elif colormap heat: # 热力图映射低置信度-蓝色高置信度-红色 if confidence 0.33: # 蓝色到青色 r 0 g int(255 * (confidence * 3)) b 255 elif confidence 0.66: # 青色到黄色 r int(255 * ((confidence - 0.33) * 3)) g 255 b int(255 * (1 - (confidence - 0.33) * 3)) else: # 黄色到红色 r 255 g int(255 * (1 - (confidence - 0.66) * 3)) b 0 return (b, g, r) elif colormap traffic_light: # 交通灯映射直观的颜色提示 if confidence 0.7: return (0, 0, 255) # 红色低置信度 elif confidence 0.9: return (0, 255, 255) # 黄色中等置信度 else: return (0, 255, 0) # 绿色高置信度 else: # 默认返回绿色 return (0, 255, 0) def draw_detection_with_color(image, boxes, scores, colormaprainbow, show_scoreTrue, thickness2): 使用颜色映射绘制检测框 参数: image: 原始图像 (numpy数组) boxes: 检测框列表每个框为 [x1, y1, x2, y2] scores: 对应的置信度列表 colormap: 颜色映射方案 show_score: 是否显示置信度文本 thickness: 框线粗细 返回: 绘制后的图像 result_image image.copy() for box, score in zip(boxes, scores): x1, y1, x2, y2 map(int, box[:4]) # 根据置信度获取颜色 color get_color_by_confidence(score, colormap) # 绘制矩形框 cv2.rectangle(result_image, (x1, y1), (x2, y2), color, thickness) # 如果需要显示置信度 if show_score: # 根据框的大小动态调整文本大小 box_height y2 - y1 font_scale max(0.3, min(0.8, box_height / 200)) # 创建文本标签 label f{score:.3f} # 获取文本大小 (text_width, text_height), baseline cv2.getTextSize( label, cv2.FONT_HERSHEY_SIMPLEX, font_scale, 1) # 绘制文本背景提高可读性 cv2.rectangle(result_image, (x1, y1 - text_height - 5), (x1 text_width, y1), color, -1) # -1表示填充 # 绘制文本 cv2.putText(result_image, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), # 白色文字 1) return result_image2.3 颜色映射效果对比让我们通过一个简单的示例来看看不同颜色映射方案的效果# color_demo.py - 颜色映射演示 import cv2 import numpy as np import matplotlib.pyplot as plt # 创建一个演示图像 demo_image np.ones((200, 600, 3), dtypenp.uint8) * 255 # 模拟不同置信度的检测框 confidences [0.3, 0.5, 0.7, 0.85, 0.95] boxes [ [50, 50, 150, 150], [150, 50, 250, 150], [250, 50, 350, 150], [350, 50, 450, 150], [450, 50, 550, 150] ] # 测试不同的颜色映射 colormaps [rainbow, heat, traffic_light] fig, axes plt.subplots(1, 3, figsize(15, 5)) for idx, colormap in enumerate(colormaps): # 创建副本 img_copy demo_image.copy() # 绘制带颜色的检测框 for i, (box, conf) in enumerate(zip(boxes, confidences)): x1, y1, x2, y2 box color get_color_by_confidence(conf, colormap) cv2.rectangle(img_copy, (x1, y1), (x2, y2), color, -1) # 填充矩形 # 添加置信度文本 label f{conf:.2f} cv2.putText(img_copy, label, (x110, y130), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2) # 显示 axes[idx].imshow(cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB)) axes[idx].set_title(f{colormap} 颜色映射) axes[idx].axis(off) plt.tight_layout() plt.show()这个演示会生成一个对比图直观展示三种颜色映射方案的效果。你可以根据自己的需求选择最合适的方案。3. 完整应用集成动态标注功能3.1 升级版Streamlit应用现在让我们把颜色映射功能集成到完整的Streamlit应用中# app_enhanced.py - 完整增强版应用 import streamlit as st from modelscope.pipelines import pipeline from modelscope.utils.constant import Tasks import cv2 import numpy as np from PIL import Image import json import plotly.graph_objects as go import pandas as pd # 设置页面布局 st.set_page_config(layoutwide, page_titleMogFace智能人脸检测) st.title(️ MogFace 智能人脸检测系统) st.markdown(---) # 侧边栏配置 with st.sidebar: st.header(⚙️ 检测配置) # 颜色映射选择 colormap_option st.selectbox( 选择颜色映射方案, [rainbow, heat, traffic_light, custom], index0, help不同方案用不同颜色表示置信度高低 ) # 自定义颜色阈值如果选择custom if colormap_option custom: st.subheader(自定义颜色阈值) low_threshold st.slider(低置信度阈值, 0.0, 1.0, 0.7, 0.05) high_threshold st.slider(高置信度阈值, 0.0, 1.0, 0.9, 0.05) # 自定义颜色选择 col1, col2, col3 st.columns(3) with col1: low_color st.color_picker(低置信度颜色, #FF0000) with col2: mid_color st.color_picker(中置信度颜色, #FFFF00) with col3: high_color st.color_picker(高置信度颜色, #00FF00) # 显示选项 show_scores st.checkbox(显示置信度分数, valueTrue) box_thickness st.slider(框线粗细, 1, 5, 2) # 统计选项 show_stats st.checkbox(显示统计图表, valueTrue) st.markdown(---) st.header(ℹ️ 模型信息) st.info( **模型**: MogFace (CVPR 2022) **骨干网络**: ResNet101 **特点**: 对遮挡、侧脸、小尺寸人脸有优秀检测能力 ) # 重置按钮 if st.button( 重置应用, typesecondary): st.cache_resource.clear() st.rerun() # 加载模型带缓存 st.cache_resource def load_detection_model(): model_path /root/ai-models/iic/cv_resnet101_face-detection_cvpr22papermogface return pipeline(Tasks.face_detection, modelmodel_path) # 自定义颜色映射函数增强版 def get_enhanced_color(confidence, colormap, custom_settingsNone): 增强版颜色映射支持自定义设置 if colormap custom and custom_settings: low_thresh custom_settings[low_threshold] high_thresh custom_settings[high_threshold] if confidence low_thresh: # 解析十六进制颜色 color_hex custom_settings[low_color].lstrip(#) return tuple(int(color_hex[i:i2], 16) for i in (4, 2, 0)) # RGB转BGR elif confidence high_thresh: color_hex custom_settings[mid_color].lstrip(#) return tuple(int(color_hex[i:i2], 16) for i in (4, 2, 0)) else: color_hex custom_settings[high_color].lstrip(#) return tuple(int(color_hex[i:i2], 16) for i in (4, 2, 0)) # 使用预定义的颜色映射 return get_color_by_confidence(confidence, colormap) # 主应用区域 col1, col2 st.columns([1, 1]) with col1: st.header( 上传与预览) # 上传方式选择 upload_method st.radio(选择上传方式, [上传文件, 使用示例图片]) if upload_method 上传文件: uploaded_file st.file_uploader( 选择图片文件, type[jpg, png, jpeg, bmp], help支持常见图片格式建议尺寸不超过4K ) if uploaded_file: image Image.open(uploaded_file) image_np np.array(image) st.image(image, caption原始图片, use_column_widthTrue) else: # 示例图片选择 example_option st.selectbox( 选择示例图片, [单人正脸, 多人合照, 侧脸示例, 遮挡测试] ) # 这里可以加载预置的示例图片 # 实际使用时需要准备对应的示例图片文件 st.info(示例图片功能需要预置图片文件) with col2: st.header( 检测结果) if image_np in locals() and image_np is not None: if st.button( 开始智能检测, typeprimary, use_container_widthTrue): with st.spinner(正在检测人脸...): # 加载模型 face_detection load_detection_model() # 执行检测 result face_detection(image_np) # 提取结果 boxes result[boxes] scores result[scores] # 准备自定义设置 custom_settings None if colormap_option custom: custom_settings { low_threshold: low_threshold, high_threshold: high_threshold, low_color: low_color, mid_color: mid_color, high_color: high_color } # 绘制检测结果 result_image image_np.copy() for i, (box, score) in enumerate(zip(boxes, scores)): x1, y1, x2, y2 map(int, box[:4]) # 获取颜色 color get_enhanced_color(score, colormap_option, custom_settings) # 绘制框 cv2.rectangle(result_image, (x1, y1), (x2, y2), color, box_thickness) # 绘制置信度 if show_scores: label f{score:.3f} # 动态调整字体大小 font_scale max(0.3, min(0.7, (y2-y1)/150)) cv2.putText(result_image, label, (x1, y1-5), cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, 1) # 显示结果 st.image(result_image, captionf检测到 {len(boxes)} 个人脸, use_column_widthTrue) # 显示统计信息 st.subheader( 检测统计) col_stat1, col_stat2, col_stat3 st.columns(3) with col_stat1: st.metric(总人脸数, len(boxes)) with col_stat2: avg_score np.mean(scores) if scores else 0 st.metric(平均置信度, f{avg_score:.3f}) with col_stat3: max_score max(scores) if scores else 0 st.metric(最高置信度, f{max_score:.3f}) # 显示统计图表 if show_stats and scores: st.subheader( 置信度分布) # 创建DataFrame用于分析 df_scores pd.DataFrame({ 置信度: scores, 序号: range(1, len(scores)1) }) # 直方图 fig_hist go.Figure() fig_hist.add_trace(go.Histogram( xscores, nbinsx10, name置信度分布, marker_colorlightblue )) fig_hist.update_layout( title置信度分布直方图, xaxis_title置信度, yaxis_title数量, bargap0.1 ) st.plotly_chart(fig_hist, use_container_widthTrue) # 散点图按检测顺序 fig_scatter go.Figure() fig_scatter.add_trace(go.Scatter( xdf_scores[序号], ydf_scores[置信度], modemarkerslines, name置信度变化, markerdict( size10, colordf_scores[置信度], colorscaleRainbow, showscaleTrue, colorbardict(title置信度) ) )) fig_scatter.update_layout( title检测顺序与置信度关系, xaxis_title检测序号, yaxis_title置信度, yaxisdict(range[0, 1.1]) ) st.plotly_chart(fig_scatter, use_container_widthTrue) # 显示原始数据 with st.expander( 查看详细检测数据, expandedFalse): # 创建详细数据表格 data_list [] for i, (box, score) in enumerate(zip(boxes, scores), 1): x1, y1, x2, y2 map(int, box[:4]) width x2 - x1 height y2 - y1 area width * height data_list.append({ 序号: i, 左上X: x1, 左上Y: y1, 右下X: x2, 右下Y: y2, 宽度: width, 高度: height, 面积: area, 置信度: f{score:.4f}, 宽高比: f{width/height:.2f} if height 0 else N/A }) df_detections pd.DataFrame(data_list) st.dataframe(df_detections, use_container_widthTrue) # 提供数据下载 csv df_detections.to_csv(indexFalse) st.download_button( label 下载CSV数据, datacsv, file_nameface_detection_results.csv, mimetext/csv ) # JSON格式数据 st.subheader(JSON原始数据) st.json(result) # JSON下载 json_str json.dumps(result, indent2) st.download_button( label 下载JSON数据, datajson_str, file_nameface_detection_results.json, mimeapplication/json ) else: st.info(请先上传或选择一张图片) # 底部说明区域 st.markdown(---) st.markdown( ### 使用建议 1. **颜色映射解读** - **彩虹映射**紫色→蓝色→绿色→黄色→红色置信度从低到高 - **热力图映射**蓝色→绿色→红色直观显示热度 - **交通灯映射**红黄绿三色快速识别质量等级 2. **性能优化** - 对于实时应用建议使用交通灯映射计算量最小 - 处理高清图片时适当降低框线粗细以提高渲染速度 - 批量处理时可以关闭统计图表显示 3. **数据利用** - 下载的CSV数据可直接导入Excel进行进一步分析 - JSON数据包含原始坐标方便与其他系统集成 )3.2 动态标注的进阶功能除了基本的颜色映射我们还可以添加更多动态标注功能# advanced_annotation.py - 进阶标注功能 import cv2 import numpy as np def draw_advanced_annotations(image, boxes, scores, show_confidenceTrue, show_idTrue, show_sizeTrue, highlight_top_n3): 绘制进阶标注ID编号、尺寸信息、高亮显示等 参数: image: 原始图像 boxes: 检测框列表 scores: 置信度列表 show_confidence: 是否显示置信度 show_id: 是否显示ID编号 show_size: 是否显示尺寸信息 highlight_top_n: 高亮显示置信度最高的前N个框 返回: 标注后的图像 result_image image.copy() # 按置信度排序用于高亮显示 sorted_indices np.argsort(scores)[::-1] # 降序排列 for idx, box_idx in enumerate(sorted_indices): box boxes[box_idx] score scores[box_idx] x1, y1, x2, y2 map(int, box[:4]) # 判断是否为高亮框 is_highlighted idx highlight_top_n # 设置框的样式 if is_highlighted: color (0, 255, 255) # 黄色高亮 thickness 3 else: # 根据置信度选择颜色 if score 0.9: color (0, 255, 0) # 绿色 elif score 0.7: color (255, 255, 0) # 青色 else: color (0, 165, 255) # 橙色 thickness 2 # 绘制主框 cv2.rectangle(result_image, (x1, y1), (x2, y2), color, thickness) # 准备标注文本 annotations [] if show_id: annotations.append(fID: {idx1}) if show_confidence: annotations.append(fConf: {score:.3f}) if show_size: width x2 - x1 height y2 - y1 annotations.append(fSize: {width}x{height}) # 绘制标注文本 if annotations: text | .join(annotations) # 计算文本大小 font_scale 0.5 (text_width, text_height), baseline cv2.getTextSize( text, cv2.FONT_HERSHEY_SIMPLEX, font_scale, 1) # 文本背景位置 text_bg_x1 x1 text_bg_y1 y1 - text_height - 10 text_bg_x2 x1 text_width 10 text_bg_y2 y1 # 确保文本背景在图像范围内 if text_bg_y1 0: text_bg_y1 y2 text_bg_y2 y2 text_height 10 # 绘制文本背景 cv2.rectangle(result_image, (text_bg_x1, text_bg_y1), (text_bg_x2, text_bg_y2), color, -1) # 绘制文本 cv2.putText(result_image, text, (x1 5, text_bg_y1 text_height 5), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 0, 0), # 黑色文字 1) # 如果是高亮框添加角标 if is_highlighted: # 绘制四个角的标记 corner_size 15 # 左上角 cv2.line(result_image, (x1, y1), (x1 corner_size, y1), color, 3) cv2.line(result_image, (x1, y1), (x1, y1 corner_size), color, 3) # 右上角 cv2.line(result_image, (x2, y1), (x2 - corner_size, y1), color, 3) cv2.line(result_image, (x2, y1), (x2, y1 corner_size), color, 3) # 左下角 cv2.line(result_image, (x1, y2), (x1 corner_size, y2), color, 3) cv2.line(result_image, (x1, y2), (x1, y2 - corner_size), color, 3) # 右下角 cv2.line(result_image, (x2, y2), (x2 - corner_size, y2), color, 3) cv2.line(result_image, (x2, y2), (x2, y2 - corner_size), color, 3) return result_image def create_confidence_heatmap(image, boxes, scores, blur_size15): 创建置信度热力图叠加 参数: image: 原始图像 boxes: 检测框列表 scores: 置信度列表 blur_size: 高斯模糊核大小 返回: 热力图叠加图像 # 创建热力图图层 heatmap np.zeros(image.shape[:2], dtypenp.float32) for box, score in zip(boxes, scores): x1, y1, x2, y2 map(int, box[:4]) # 在检测框位置添加置信度值 center_x (x1 x2) // 2 center_y (y1 y2) // 2 # 创建高斯分布 radius max((x2 - x1) // 2, (y2 - y1) // 2) y_indices, x_indices np.ogrid[:image.shape[0], :image.shape[1]] # 计算距离 distance np.sqrt((x_indices - center_x)**2 (y_indices - center_y)**2) # 创建高斯权重 gaussian np.exp(-distance**2 / (2 * (radius/2)**2)) # 叠加到热力图 heatmap gaussian * score # 归一化到0-1范围 if heatmap.max() 0: heatmap heatmap / heatmap.max() # 应用颜色映射 heatmap_colored cv2.applyColorMap((heatmap * 255).astype(np.uint8), cv2.COLORMAP_JET) # 调整热力图透明度 alpha 0.5 blended cv2.addWeighted(image, 1-alpha, heatmap_colored, alpha, 0) return blended4. 实际应用场景与效果展示4.1 场景一安防监控中的人脸检测在安防监控场景中我们经常需要处理低光照、遮挡、侧脸等复杂情况。使用我们的增强版MogFace工具可以# security_monitoring_demo.py - 安防监控应用示例 def analyze_security_footage(image_path): 分析安防监控画面中的人脸检测结果 # 读取监控画面 image cv2.imread(image_path) # 使用MogFace进行检测 face_detection load_detection_model() result face_detection(image) # 使用交通灯颜色映射快速识别 annotated_image draw_detection_with_color( image, result[boxes], result[scores], colormaptraffic_light, show_scoreTrue ) # 统计结果 total_faces len(result[boxes]) high_confidence sum(1 for s in result[scores] if s 0.9) medium_confidence sum(1 for s in result[scores] if 0.7 s 0.9) low_confidence sum(1 for s in result[scores] if s 0.7) print(f检测到总人脸数: {total_faces}) print(f高置信度(0.9): {high_confidence}个) print(f中置信度(0.7-0.9): {medium_confidence}个) print(f低置信度(0.7): {low_confidence}个) # 对于低置信度检测可能需要人工复核 if low_confidence 0: print(f⚠️ 有{low_confidence}个低置信度检测建议人工复核) return annotated_image4.2 场景二社交媒体图片分析在社交媒体内容分析中我们需要处理各种自拍、合照等场景# social_media_analysis.py - 社交媒体图片分析 def analyze_social_media_image(image, min_face_size50): 分析社交媒体图片中的人脸特征 # 检测人脸 result face_detection(image) if not result[boxes]: return None # 创建分析报告 analysis { total_faces: len(result[boxes]), face_sizes: [], confidence_stats: { min: min(result[scores]), max: max(result[scores]), avg: np.mean(result[scores]), std: np.std(result[scores]) }, composition_analysis: None } # 分析每个人脸 for i, (box, score) in enumerate(zip(result[boxes], result[scores])): x1, y1, x2, y2 map(int, box[:4]) width x2 - x1 height y2 - y1 # 计算人脸大小 face_size width * height analysis[face_sizes].append({ id: i1, width: width, height: height, area: face_size, confidence: float(score), aspect_ratio: width/height if height 0 else 0 }) # 分析构图如果有多个人脸 if len(result[boxes]) 1: # 计算人脸中心点 centers [] for box in result[boxes]: x1, y1, x2, y2 box[:4] center_x (x1 x2) / 2 center_y (y1 y2) / 2 centers.append((center_x, center_y)) # 计算分布特征 centers_array np.array(centers) analysis[composition_analysis] { spread: np.std(centers_array, axis0).tolist(), centroid: np.mean(centers_array, axis0).tolist() } return analysis def generate_social_media_report(image_path): 生成社交媒体图片分析报告 image cv2.imread(image_path) analysis analyze_social_media_image(image) if analysis: print( * 50) print(社交媒体图片分析报告) print( * 50) print(f总人脸数: {analysis[total_faces]}) print(f\n置信度统计:) print(f 最低: {analysis[confidence_stats][min]:.3f}) print(f 最高: {analysis[confidence_stats][max]:.3f}) print(f 平均: {analysis[confidence_stats][avg]:.3f}) print(f 标准差: {analysis[confidence_stats][std]:.3f}) print(f\n人脸大小分析:) for face in analysis[face_sizes]: print(f 人脸{face[id]}: {face[width]}x{face[height]} f(面积: {face[area]}, 置信度: {face[confidence]:.3f})) if analysis[composition_analysis]: print(f\n构图分析:) print(f 人脸分布标准差: {analysis[composition_analysis][spread]}) print(f 人脸中心点: {analysis[composition_analysis][centroid]}) # 质量评估 avg_confidence analysis[confidence_stats][avg] if avg_confidence 0.9: quality 优秀 elif avg_confidence 0.7: quality 良好 else: quality 一般 print(f\n 图片质量评估: {quality}) print(f 平均置信度: {avg_confidence:.3f}) return analysis else: print(未检测到人脸) return None4.3 场景三人脸检测质量评估对于需要评估模型性能的场景我们可以提供更详细的分析# quality_assessment.py - 人脸检测质量评估 def assess_detection_quality(image_path, ground_truthNone): 评估人脸检测质量 image cv2.imread(image_path) result face_detection(image) # 基础质量指标 quality_metrics { detection_count: len(result[boxes]), confidence_distribution: { excellent: sum(1 for s in result[scores] if s 0.95), good: sum(1 for s in result[scores] if 0.8 s 0.95), fair: sum(1 for s in result[scores] if 0.6 s 0.8), poor: sum(1 for s in result[scores] if s 0.6) }, size_distribution: [], position_analysis: None } # 分析人脸大小分布 sizes [] for box in result[boxes]: x1, y1, x2, y2 box[:4] width x2 - x1 height y2 - y1 area width * height sizes.append(area) if sizes: quality_metrics[size_distribution] { min: min(sizes), max: max(sizes), avg: np.mean(sizes), std: np.std(sizes) } # 位置分布分析 if result[boxes]: centers [] for box in result[boxes]: x1, y1, x2, y2 box[:4] center_x (x1 x2) / 2 / image.shape[1] # 归一化 center_y (y1 y2) / 2 / image.shape[0] centers.append([center_x, center_y]) centers_array np.array(centers) quality_metrics[position_analysis] { centers: centers, mean_position: np.mean(centers_array, axis0).tolist(), position_std: np.std(centers_array, axis0).tolist() } # 生成质量报告 generate_quality_report(quality_metrics, result[scores]) return quality_metrics def generate_quality_report(metrics, scores): 生成详细的质量评估报告 print( * 60) print(人脸检测质量评估报告) print( * 60) print(f\n 检测统计:) print(f 检测到人脸数: {metrics[detection_count]}) print(f\n 置信度分布:) conf_dist metrics[confidence_distribution] total sum(conf_dist.values()) for category, count in conf_dist.items(): percentage (count / total * 100) if total 0 else 0 print(f {category.capitalize()}: {count}个 ({percentage:.1f}%)) print(f\n 人脸大小分析:) if metrics[size_distribution]: size_info metrics[size_distribution] print(f 最小面积: {size_info[min]:.0f} 像素) print(f 最大面积: {size_info[max]:.0f} 像素) print(f 平均面积: {size_info[avg]:.0f} 像素) print(f 面积标准差: {size_info[std]:.0f} 像素) print(f\n 位置分布:) if metrics[position_analysis]: pos_info metrics[position_analysis] print(f 平均位置: ({pos_info[mean_position][0]:.3f}, {pos_info[mean_position][1]:.3f})) print(f 位置标准差: ({pos_info[position_std][0]:.3f}, {pos_info[position_std][1]:.3f})) # 总体质量评分 avg_score np.mean(scores) if scores else 0 if avg_score 0.9: overall_quality 优秀 recommendation 检测结果非常可靠可直接使用 elif avg_score 0.7: overall_quality 良好 recommendation 检测结果基本可靠建议对低置信度结果进行复核 elif avg_score 0.5: overall_quality 一般 recommendation 检测结果存在不确定性建议人工复核 else: overall_quality 较差 recommendation 检测结果不可靠建议重新采集或使用其他方法 print(f\n⭐ 总体质量评估: {overall_quality}) print(f 平均置信度: {avg_score:.3f}) print(f 建议: {recommendation}) # 可视化建议 print(f\n 可视化建议:) if metrics[detection_count] 5: print( - 使用彩虹色映射便于区分多人脸) elif avg_score 0.7: print( - 使用交通灯映射快速识别低质量检测) else: print( - 使用热力图映射直观显示置信度分布)5. 总结与最佳实践5.1 核心功能回顾通过本文的代码实例我们为MogFace人脸检测工具添加了强大的自定义功能智能颜色映射系统根据置信度自动选择颜色让检测结果一目了然动态标注功能支持ID编号、尺寸显示、高亮标记等进阶功能完整可视化界面基于Streamlit的交互式Web应用数据分析能力提供详细的统计图表和数据导出功能多场景适配针对安防、社交媒体、质量评估等不同场景的优化5.2 使用建议与最佳实践在实际使用中我建议你根据具体需求选择合适的配置对于实时监控场景使用traffic_light颜色映射快速识别低质量检测关闭复杂的统计图表提高响应速度设置适当的置信度阈值过滤掉不可靠的检测对于图片分析场景使用rainbow颜色映射获得最佳的视觉效果开启所有统计功能获得全面的分析报告导出CSV数据便于后续处理和分析对于质量评估场景使用heat颜色映射直观显示置信度分布开启高级标注功能获得详细信息定期运行质量评估脚本监控模型性能变化5.3 性能优化建议如果你在处理大量图片或需要实时处理可以考虑以下优化# performance_optimization.py - 性能优化建议 def optimize_for_batch_processing(image_paths, batch_size4): 批量处理优化建议 optimizations { 硬件层面: [ 确保使用GPU加速CUDA, 调整batch_size以适应显存大小, 使用半精度FP16推理加速 ], 软件层面: [ 预处理图片到统一尺寸, 使用模型缓存避免重复加载, 并行处理多个图片 ], 算法层面: [ 根据场景调整置信度阈值, 对远小人脸使用专门的小目标检测策略, 使用非极大值抑制NMS优化检测框 ] } return optimizations def real_time_optimization_settings(): 实时处理优化设置 settings { 颜色映射: traffic_light, # 计算量最小 显示选项: { show_scores: True, show_id: False, # 关闭ID显示减少计算 show_size: False, # 关闭尺寸显示减少计算 box_thickness: 1 # 使用最细的框线 }, 图像处理: { resize_to: (640, 480), # 降低分辨率 use_gray: False, # 保持彩色但可以尝试灰度化 jpeg_quality: 85 # 适当压缩 }, 模型推理: { confidence_threshold: 0.6, # 适当降低阈值 nms_threshold: 0.3, # 优化非极大值抑制 use_fp16: True # 使用半精度 } } return settings5.4 扩展与定制这个工具框架非常灵活你可以根据自己的需求进行扩展添加新功能如人脸属性分析年龄、性别、情绪等集成其他模型结合人脸识别、关键点检测等模型开发API接口将功能封装为REST API供其他系统调用构建自动化流程与工作流引擎集成实现自动化处理最重要的是这个工具的核心思想——通过可视化让数据说话——可以应用到很多其他计算机视觉任务中。无论是目标检测、图像分割还是其他任务合适的可视化都能大大提升工作效率和理解深度。希望这个MogFace增强版工具能帮助你在人脸检测任务中取得更好的效果。如果你有任何问题或改进建议欢迎在评论区交流讨论获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。