yolov8 识别图片质心 代码
时间: 2023-11-20 19:55:58 浏览: 143
很抱歉,目前并不存在yolov8这个版本,但是YOLOv4是目前最新的版本,可以用于图像识别任务。下面是使用YOLOv4识别图片质心的Python代码:
```python
import cv2
import numpy as np
# 加载YOLOv4模型
net = cv2.dnn.readNet("yolov4.weights", "yolov4.cfg")
# 加载图片
img = cv2.imread("test.jpg")
# 获取图片尺寸
height, width, _ = img.shape
# 构建输入图像的blob
blob = cv2.dnn.blobFromImage(img, 1/255, (416, 416), swapRB=True, crop=False)
# 将blob输入到模型中进行前向推理
net.setInput(blob)
outs = net.forward(net.getUnconnectedOutLayersNames())
# 解析输出结果
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)
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
# 非极大值抑制
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制边界框和标签
for i in indices:
i = i[0]
box = boxes[i]
x, y, w, h = box
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.putText(img, 'Center', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 显示结果
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这段代码使用OpenCV的dnn模块加载YOLOv4模型,并对一张图片进行识别,最终在图片上绘制出识别出的目标的边界框和标签。其中,使用了Intersection over Union (IoU)算法进行非极大值抑制,可以有效地去除重叠的边界框。
阅读全文