实时口罩检测-通用保姆级教程:解决Gradio CORS跨域问题与HTTPS证书配置

📅 发布时间:2026/7/9 5:41:04 👁️ 浏览次数:
实时口罩检测-通用保姆级教程:解决Gradio CORS跨域问题与HTTPS证书配置
实时口罩检测-通用保姆级教程解决Gradio CORS跨域问题与HTTPS证书配置1. 项目简介与价值实时口罩检测是一个实用的计算机视觉应用能够自动识别图像中的人脸并判断是否佩戴口罩。这个功能在公共卫生、安防监控、智能门禁等场景中都有重要应用价值。本项目基于DAMO-YOLO目标检测框架这是一个专门为工业落地设计的高性能检测模型。与传统的YOLO系列相比DAMO-YOLO在保持极快推理速度的同时大幅提升了检测精度特别适合实时应用场景。模型的核心优势检测速度快支持实时视频流处理准确率高能够精确识别口罩佩戴状态多脸支持单张图片可同时检测多个人脸简单易用提供友好的Web界面无需编程基础2. 环境准备与快速部署2.1 系统要求与依赖安装在开始之前请确保你的系统满足以下基本要求Python 3.7或更高版本至少4GB可用内存支持CUDA的GPU可选但推荐使用以获得更好性能安装必要的依赖包pip install torch torchvision pip install modelscope pip install gradio pip install opencv-python pip install numpy2.2 模型下载与加载通过ModelScope快速加载口罩检测模型from modelscope.pipelines import pipeline from modelscope.utils.constant import Tasks # 创建口罩检测pipeline mask_detection pipeline( Tasks.domain_specific_object_detection, modeldamo/cv_tinynas_object-detection_damoyolo_facemask )3. Gradio Web界面部署3.1 基础界面搭建Gradio提供了一个简单的方式来创建Web界面让用户可以通过浏览器上传图片并查看检测结果。创建基本的Web界面代码import gradio as gr import cv2 import numpy as np def detect_mask(image): 对上传的图片进行口罩检测 # 调用模型进行预测 result mask_detection(image) # 在图像上绘制检测结果 output_image image.copy() for detection in result[boxes]: x1, y1, x2, y2 detection[:4] label 佩戴口罩 if detection[4] 1 else 未佩戴口罩 color (0, 255, 0) if detection[4] 1 else (0, 0, 255) # 绘制边界框 cv2.rectangle(output_image, (int(x1), int(y1)), (int(x2), int(y2)), color, 2) # 添加标签 cv2.putText(output_image, label, (int(x1), int(y1)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2) return output_image # 创建Gradio界面 interface gr.Interface( fndetect_mask, inputsgr.Image(label上传图片), outputsgr.Image(label检测结果), title实时口罩检测系统, description上传包含人脸的图片系统将自动检测是否佩戴口罩 )3.2 启动Web服务运行以下命令启动Gradio服务python webui.py服务启动后你会在终端看到类似这样的输出Running on local URL: http://127.0.0.1:7860在浏览器中打开这个地址就能看到口罩检测的Web界面了。4. 解决CORS跨域问题4.1 理解CORS问题当你在本地开发时可能不会遇到CORS跨源资源共享问题但当你将应用部署到服务器或者尝试从其他域名访问Gradio服务时浏览器会阻止这些跨域请求这是出于安全考虑。常见的CORS错误提示No Access-Control-Allow-Origin header is presentCross origin requests are only supported for protocol schemes4.2 Gradio中的CORS解决方案Gradio内置了CORS支持可以通过简单的配置启用import gradio as gr from fastapi.middleware.cors import CORSMiddleware # 创建Gradio应用 app gr.Blocks() # 添加CORS中间件 app.server.add_middleware( CORSMiddleware, allow_origins[*], # 允许所有域名生产环境建议指定具体域名 allow_credentialsTrue, allow_methods[*], # 允许所有方法 allow_headers[*], # 允许所有头 ) # 你的界面代码 with app: gr.Markdown(# 实时口罩检测系统) # ... 其他界面组件 # 启动应用 if __name__ __main__: app.launch(server_name0.0.0.0, server_port7860, shareFalse)4.3 替代方案使用反向代理如果上述方法不适用可以考虑使用Nginx作为反向代理来解决CORS问题# nginx.conf 配置 server { listen 80; server_name your-domain.com; location / { proxy_pass http://localhost:7860; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; # CORS headers add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods GET, POST, OPTIONS; add_header Access-Control-Allow-Headers DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range; if ($request_method OPTIONS) { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods GET, POST, OPTIONS; add_header Access-Control-Allow-Headers DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range; add_header Access-Control-Max-Age 1728000; add_header Content-Type text/plain; charsetutf-8; add_header Content-Length 0; return 204; } } }5. HTTPS证书配置指南5.1 为什么需要HTTPS在现代Web应用中HTTPS不再是可选项而是必需项保护数据传输安全防止中间人攻击浏览器对HTTP网站标记为不安全某些Web API如摄像头访问要求HTTPS提升用户信任度5.2 使用Lets Encrypt免费证书Lets Encrypt提供了免费的SSL证书可以通过Certbot工具自动获取和更新# 安装Certbot sudo apt update sudo apt install certbot python3-certbot-nginx # 获取证书如果你使用Nginx sudo certbot --nginx -d your-domain.com # 获取证书如果你不使用Nginx sudo certbot certonly --standalone -d your-domain.com5.3 Gradio配置HTTPSGradio原生支持HTTPS只需要提供证书路径app.launch( server_name0.0.0.0, server_port7860, ssl_certfile/path/to/fullchain.pem, ssl_keyfile/path/to/privkey.pem, ssl_verifyFalse )5.4 自动化证书更新Lets Encrypt证书每90天需要更新可以设置定时任务自动更新# 编辑crontab sudo crontab -e # 添加以下行每周一凌晨2点检查更新 0 2 * * 1 /usr/bin/certbot renew --quiet --deploy-hook systemctl reload nginx6. 完整部署示例6.1 整合所有配置的完整代码import gradio as gr from fastapi.middleware.cors import CORSMiddleware from modelscope.pipelines import pipeline from modelscope.utils.constant import Tasks import cv2 # 初始化模型 mask_detection pipeline( Tasks.domain_specific_object_detection, modeldamo/cv_tinynas_object-detection_damoyolo_facemask ) def detect_mask(image): 口罩检测函数 result mask_detection(image) output_image image.copy() for detection in result[boxes]: x1, y1, x2, y2 detection[:4] label 佩戴口罩 if detection[4] 1 else 未佩戴口罩 color (0, 255, 0) if detection[4] 1 else (0, 0, 255) cv2.rectangle(output_image, (int(x1), int(y1)), (int(x2), int(y2)), color, 2) cv2.putText(output_image, label, (int(x1), int(y1)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2) return output_image # 创建Gradio应用 app gr.Blocks() # 添加CORS支持 app.server.add_middleware( CORSMiddleware, allow_origins[*], allow_credentialsTrue, allow_methods[*], allow_headers[*], ) # 构建界面 with app: gr.Markdown(# 实时口罩检测系统) gr.Markdown(上传包含人脸的图片系统将自动检测是否佩戴口罩) with gr.Row(): with gr.Column(): input_image gr.Image(label上传图片, typenumpy) detect_btn gr.Button(开始检测) with gr.Column(): output_image gr.Image(label检测结果) detect_btn.click(fndetect_mask, inputsinput_image, outputsoutput_image) # 启动应用 if __name__ __main__: app.launch( server_name0.0.0.0, server_port7860, # 取消注释以下行启用HTTPS # ssl_certfile/etc/letsencrypt/live/your-domain.com/fullchain.pem, # ssl_keyfile/etc/letsencrypt/live/your-domain.com/privkey.pem, shareFalse )6.2 部署检查清单在完成部署后建议检查以下项目功能测试上传测试图片验证检测功能正常CORS测试尝试从不同域名访问API接口HTTPS测试确保证书正确安装浏览器显示安全锁标志性能测试检查响应时间确保满足实时性要求错误处理测试各种异常情况下的系统行为7. 常见问题与解决方案7.1 模型加载问题问题模型下载失败或加载缓慢解决方案# 设置镜像源加速下载 import os os.environ[MODELSCOPE_CACHE] ./model_cache os.environ[MODELSCOPE_ENDPOINT] https://mirrors.aliyun.com/modelscope/7.2 内存不足问题问题处理大图片时内存溢出解决方案def detect_mask(image): # 调整图片大小以减少内存使用 height, width image.shape[:2] if max(height, width) 1024: scale 1024 / max(height, width) new_size (int(width * scale), int(height * scale)) image cv2.resize(image, new_size) # 进行检测...7.3 检测精度优化问题在某些场景下检测效果不理想解决方案# 调整置信度阈值 def detect_mask(image, confidence_threshold0.5): result mask_detection(image) output_image image.copy() for detection in result[boxes]: confidence detection[5] # 置信度分数 if confidence confidence_threshold: continue # 跳过低置信度检测 # 绘制检测结果... return output_image8. 总结通过本教程你已经学会了如何部署一个完整的实时口罩检测系统并解决了在实际部署中常见的CORS跨域问题和HTTPS证书配置问题。关键要点回顾模型选择DAMO-YOLO提供了优秀的速度与精度平衡快速部署使用Gradio可以快速构建友好的Web界面跨域解决通过CORS中间件或反向代理解决跨域问题安全加固使用HTTPS保护数据传输安全问题排查提供了常见问题的解决方案这个口罩检测系统不仅可以用于演示目的经过适当优化后完全可以投入实际应用场景。你可以进一步扩展功能比如添加实时视频流处理、批量图片处理、统计报表生成等特性。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。