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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| import tensorrt as trt import pycuda.driver as cuda import pycuda.autoinit import numpy as np import cv2
class YOLO26TRT: """ YOLO26 TensorRT 推理类 """ def __init__(self, engine_path: str): self.logger = trt.Logger(trt.Logger.INFO) self.engine = self.load_engine(engine_path) self.context = self.engine.create_execution_context() self.inputs, self.outputs = self.allocate_buffers() def load_engine(self, engine_path: str): """加载 TensorRT 引擎""" with open(engine_path, 'rb') as f: runtime = trt.Runtime(self.logger) return runtime.deserialize_cuda_engine(f.read()) def allocate_buffers(self): """分配输入输出缓冲区""" inputs = [] outputs = [] for binding in self.engine: size = trt.volume(self.engine.get_binding_shape(binding)) dtype = trt.nptype(self.engine.get_binding_dtype(binding)) host_mem = cuda.pagelocked_empty(size, dtype) device_mem = cuda.mem_alloc(host_mem.nbytes) if self.engine.binding_is_input(binding): inputs.append({'host': host_mem, 'device': device_mem}) else: outputs.append({'host': host_mem, 'device': device_mem}) return inputs, outputs def infer(self, image: np.ndarray) -> list: """ 执行推理 Args: image: BGR 图像 (H, W, 3) Returns: detections: 检测结果列表 """ input_tensor = self.preprocess(image) np.copyto(self.inputs[0]['host'], input_tensor.ravel()) cuda.memcpy_htod(self.inputs[0]['device'], self.inputs[0]['host']) self.context.execute_v2([inp['device'] for inp in self.inputs] + [out['device'] for out in self.outputs]) cuda.memcpy_dtoh(self.outputs[0]['host'], self.outputs[0]['device']) return self.postprocess(self.outputs[0]['host']) def preprocess(self, image: np.ndarray) -> np.ndarray: """预处理""" resized = cv2.resize(image, (640, 640)) normalized = resized.astype(np.float32) / 255.0 transposed = normalized.transpose(2, 0, 1) return np.expand_dims(transposed, 0) def postprocess(self, output: np.ndarray) -> list: """后处理""" detections = [] for det in output[0]: x, y, w, h, conf, cls = det if conf > 0.25: detections.append({ 'bbox': [x - w/2, y - h/2, x + w/2, y + h/2], 'confidence': float(conf), 'class': int(cls) }) return detections
if __name__ == "__main__": model = YOLO26TRT("yolo26n_int8.engine") image = cv2.imread("test.jpg") detections = model.infer(image) for det in detections: x1, y1, x2, y2 = det['bbox'] cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2) cv2.putText(image, f"{det['class']}: {det['confidence']:.2f}", (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1) cv2.imwrite("result.jpg", image) print(f"检测到 {len(detections)} 个目标")
|