yolov8实例分割代码
时间: 2023-10-15 08:26:43 浏览: 243
以下是一个使用YOLOv8进行实例分割的示例代码:
```python
import cv2
import numpy as np
# 加载模型和权重
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
# 获取输出层的名称
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 加载类标签
classes = []
with open('coco.names', 'r') as f:
classes = [line.strip() for line in f.readlines()]
# 加载图像
image = cv2.imread('image.jpg')
# 图像预处理
blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
# 解析结果
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] * image.shape[1])
center_y = int(detection[1] * image.shape[0])
width = int(detection[2] * image.shape[1])
height = int(detection[3] * image.shape[0])
# 边框坐标
x = int(center_x - width / 2)
y = int(center_y - height / 2)
boxes.append([x, y, width, height])
confidences.append(float(confidence))
class_ids.append(class_id)
# NMS抑制
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制边框和类标签
font = cv2.FONT_HERSHEY_PLAIN
colors = np.random.uniform(0, 255, size=(len(classes), 3))
if len(indexes) > 0:
for i in indexes.flatten():
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
confidence = str(round(confidences[i], 2))
color = colors[i]
cv2.rectangle(image, (x, y), (x+w, y+h), color, 2)
cv2.putText(image, label + ' ' + confidence, (x, y+30), font, 3, color, 3)
# 显示结果
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请确保将YOLOv8的配置文件(.cfg)、权重文件(.weights)和类标签文件(.names)放在正确的路径下,并将图像文件命名为`image.jpg`。
这段代码使用了OpenCV库加载YOLOv8模型和权重,对图像进行预处理,然后解析模型输出,应用非最大抑制(NMS)来去除重叠的边框,最后绘制边框和类标签并显示结果图像。
阅读全文