"15个YOLO算法的Python代码示例集合:简单级示例"

需积分: 1 10 下载量 11 浏览量 更新于2024-04-15 收藏 37KB DOCX 举报
15个YOLO算法的python代码示例集合包括了对图片进行目标检测的代码示例。其中,使用YOLOv3算法对图片进行目标检测并返回检测结果的代码示例如下: ```python import cv2 import numpy as np # Load YOLO net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg") layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] # Load image image = cv2.imread("image.jpg") height, width, channels = image.shape # Preprocess image blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False) net.setInput(blob) # Forward pass outs = net.forward(output_layers) # Get bounding boxes class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) # Non-max suppression indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) # Draw bounding boxes font = cv2.FONT_HERSHEY_PLAIN colors = np.random.uniform(0, 255, size=(len(boxes), 3)) for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) color = colors[i] cv2.rectangle(image, (x, y), (x + w, y + h), color, 2) cv2.putText(image, label, (x, y + 30), font, 3, color, 3) # Show image cv2.imshow("Image", image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 以上代码示例演示了如何使用YOLOv3算法对图片进行目标检测,并在结果中绘制出检测到的边界框及类别标签。通过加载预训练的权重文件和配置文件,对输入图片进行预处理并进行前向传播,最终实现目标检测的功能。YOLO算法的python代码示例在15个不同的示例中展示了不同的用途和功能,为学习和使用YOLO算法提供了便利。