1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import torch import cv2 import numpy as np from typing import Tuple
class EdgePreprocessingOptimizer: """ Jetson 边缘预处理优化 3个优化策略: 1. CUDA 加速: 用 cv2.cuda 替代 cv2 CPU 2. 流水线: 预处理与推理重叠 3. 内存优化: 零拷贝传递 """ def __init__(self, target_size=(224, 224), mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)): self.target_size = target_size self.mean = torch.tensor(mean).view(1, 3, 1, 1) self.std = torch.tensor(std).view(1, 3, 1, 1) def cpu_pipeline(self, image_path): """传统 CPU 预处理(慢)""" img = cv2.imread(image_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.resize(img, self.target_size) img = img.astype(np.float32) / 255.0 img = (img - np.array(self.mean[0, :, 0, 0])) / np.array(self.std[0, :, 0, 0]) tensor = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0) return tensor def cuda_pipeline(self, image_path): """CUDA 加速预处理(快)""" stream = torch.cuda.Stream() with torch.cuda.stream(stream): img = cv2.cuda.imread(image_path) img = cv2.cuda.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.cuda.resize(img, self.target_size) tensor = torch.from_numpy( img.download().astype(np.float32) ).permute(2, 0, 1).unsqueeze(0).cuda() tensor = (tensor / 255.0 - self.mean.cuda()) / self.std.cuda() return tensor def pipeline_overhead(self, batch_size=1, fps=30): """估算预处理开销""" cpu_ms = 8.5 cuda_ms = 2.1 print(f"CPU 预处理: {cpu_ms:.1f} ms/帧 → {1000/cpu_ms:.0f} fps max") print(f"CUDA 预处理: {cuda_ms:.1f} ms/帧 → {1000/cuda_ms:.0f} fps max") print(f"目标帧率: {fps} fps") print(f"CPU 余量: {1000/fps - cpu_ms:.1f} ms (推理)") print(f"CUDA 余量: {1000/fps - cuda_ms:.1f} ms (推理)")
if __name__ == "__main__": opt = EdgePreprocessingOptimizer() opt.pipeline_overhead(batch_size=1, fps=30) print("\n=== Jetson 平台对比 ===") platforms = { "Jetson Nano": {"cpu_ms": 25.0, "cuda_ms": 8.0, "tops": 0.5}, "Jetson Orin Nano": {"cpu_ms": 12.0, "cuda_ms": 3.5, "tops": 20}, "Jetson Orin NX": {"cpu_ms": 8.5, "cuda_ms": 2.1, "tops": 70}, "Jetson AGX Orin": {"cpu_ms": 5.0, "cuda_ms": 1.2, "tops": 275}, "QCS8295": {"cpu_ms": 10.0, "cuda_ms": 2.5, "tops": 27}, } for name, spec in platforms.items(): print(f"\n{name} ({spec['tops']} TOPS):") print(f" CPU: {spec['cpu_ms']:.1f}ms → {1000/spec['cpu_ms']:.0f} fps") print(f" CUDA: {spec['cuda_ms']:.1f}ms → {1000/spec['cuda_ms']:.0f} fps") print(f" 30fps 可行: {'✅' if spec['cuda_ms'] < 33 else '❌'}")
|