yolov8实时检测推理Python代码
时间: 2023-09-28 12:11:17 浏览: 46
你好,以下是 YOLOv8 实时检测推理 Python 代码的示例:
```
import cv2
import numpy as np
# Load YOLOv8 model
net = cv2.dnn.readNet("yolov8.weights", "yolov8.cfg")
# Load input image
img = cv2.imread("input.jpg")
# Resize image to input size of the model
img = cv2.resize(img, (416, 416))
# Create a blob from the image
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
# Feed the blob to the model
net.setInput(blob)
# Get the output layer names of the model
layer_names = net.getLayerNames()
layer_names = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# Perform forward pass to get detections
detections = net.forward(layer_names)
# Get the detections from the output
detections = np.squeeze(detections)
# Get the class IDs and confidences for each detection
class_ids, confidences, boxes = [], [], []
for detection in detections:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x, center_y, w, h = (detection[0:4] * np.array([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])).astype('int')
x, y = int(center_x - w / 2), int(center_y - h / 2)
boxes.append([x, y, int(w), int(h)])
confidences.append(float(confidence))
class_ids.append(class_id)
# Perform non-maximum suppression to get the final detections
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# Draw the detections on the image
for i in indices:
i = i[0]
box = boxes[i]
x, y, w, h = box[0], box[1], box[2], box[3]
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Display the image
cv2.imshow("detections", img)
cv2.waitKey()
cv2.destroyAllWindows()
```
希望这对你有帮助。
阅读全文