在Google Cloud Function中部署训练好的YoloV7模型
部署YOLOv7模型到Google Cloud Function实现目标检测
一、前期准备
- 精简YOLOv7的推理代码,移除训练相关冗余模块,只保留检测核心逻辑。
- 将你的自定义
.pt模型上传至Google Cloud Storage(GCS)指定路径(比如gs://your-bucket/models/yolov7-custom.pt),Cloud Function本地存储空间有限,需从GCS加载模型。 - 确认Cloud Function使用Python 3.8及以上版本,尽量与训练模型时的Python版本一致,减少依赖冲突。
二、构建Cloud Function代码结构
1. 依赖配置(requirements.txt)
torch==1.12.1+cpu -f https://download.pytorch.org/whl/cpu/torch_stable.html torchvision==0.13.1+cpu -f https://download.pytorch.org/whl/cpu/torch_stable.html opencv-python>=4.5.5 pillow>=9.0.0 google-cloud-storage>=2.0.0
注:指定CPU版本的预编译Torch包,避免Cloud Function环境下的编译错误。
2. 主函数代码(main.py)
import os import torch import numpy as np import cv2 from PIL import Image from google.cloud import storage # 初始化GCS客户端 storage_client = storage.Client() # 全局加载YOLOv7模型(仅函数初始化时加载一次,降低冷启动耗时) def load_yolov7_model(): bucket_name = "your-bucket-name" model_blob = storage_client.bucket(bucket_name).blob("models/yolov7-custom.pt") temp_model_path = "/tmp/yolov7-custom.pt" model_blob.download_to_filename(temp_model_path) # 加载模型并设置为推理模式 model = torch.load(temp_model_path, map_location=torch.device('cpu'))['model'].float().fuse().eval() return model model = load_yolov7_model() def detect_objects(request): # 解析请求参数 request_json = request.get_json() if not request_json or 'image_gcs_path' not in request_json: return {"error": "缺少必要参数:image_gcs_path"} image_gcs_path = request_json['image_gcs_path'] image_name = request_json.get('image_name', 'unknown.jpg') # 从GCS下载图片到临时目录 bucket_name, blob_path = image_gcs_path.replace("gs://", "").split("/", 1) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(blob_path) temp_image_path = f"/tmp/{image_name}" blob.download_to_filename(temp_image_path) # 图片预处理(适配YOLOv7输入要求) img = cv2.imread(temp_image_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = Image.fromarray(img).resize((640, 640)) img = np.array(img) / 255.0 img = np.transpose(img, (2, 0, 1)) img = np.expand_dims(img, 0) img = torch.tensor(img).float() # 执行目标检测 with torch.no_grad(): outputs = model(img) # 解析检测结果 detections = [] for output in outputs: boxes = output[:, :4].cpu().numpy() # [x1, y1, x2, y2] confidences = output[:, 4].cpu().numpy() class_ids = output[:, 5].cpu().numpy() for box, conf, cls_id in zip(boxes, confidences, class_ids): if conf > 0.5: # 过滤低置信度结果 detections.append({ "box": [float(coord) for coord in box], "confidence": float(conf), "class_id": int(cls_id) }) return {"image_name": image_name, "detections": detections}
三、部署与配置
- 内存分配:建议给Cloud Function分配至少2GB内存,避免加载模型或推理时出现内存不足错误。
- 权限设置:为Cloud Function的服务账号添加GCS对象读取权限,确保能访问模型文件和待检测图片。
- 部署命令:使用gcloud工具部署(替换占位符为你的实际信息):
gcloud functions deploy detect_objects \ --runtime python39 \ --trigger-http \ --memory 2048MB \ --service-account your-service-account@your-project.iam.gserviceaccount.com
四、测试函数
发送POST请求验证功能:
curl -X POST https://[REGION]-[PROJECT_ID].cloudfunctions.net/detect_objects \ -H "Content-Type: application/json" \ -d '{"image_gcs_path": "gs://your-bucket/images/test.jpg", "image_name": "test.jpg"}'
内容的提问来源于stack exchange,提问作者Natty Minds
相关产品推荐
相关产品推荐

