帮我写一段使用yolo进行图像分析的代码
时间: 2023-06-09 13:03:06 浏览: 50
好的,以下是使用yolo进行图像分析的代码示例:
```python
import cv2
import numpy as np
import wget
# 下载yolo预训练模型
url = 'https://github.com/pjreddie/darknet/blob/master/data/coco.names?'
wget.download(url, 'coco.names')
url = 'https://github.com/pjreddie/darknet/blob/master/cfg/yolov3.cfg?'
wget.download(url, 'yolov3.cfg')
url = 'https://pjreddie.com/media/files/yolov3.weights'
wget.download(url, 'yolov3.weights')
# 加载yolo预训练模型
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
# 加载类别标签
classes = []
with open('coco.names', 'r') as f:
classes = [line.strip() for line in f.readlines()]
# 加载图像并进行预处理
img = cv2.imread('image.jpg')
blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False)
# 将预处理后的图像发送给yolo模型
net.setInput(blob)
# 运行yolo模型并获取检测结果
outs = net.forward(net.getUnconnectedOutLayersNames())
boxes = []
confidences = []
class_ids = []
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] * img.shape[1])
center_y = int(detection[1] * img.shape[0])
width = int(detection[2] * img.shape[1])
height = int(detection[3] * img.shape[0])
left = int(center_x - width / 2)
top = int(center_y - height / 2)
boxes.append([left, top, width, height])
confidences.append(float(confidence))
class_ids.append(class_id)
# 非极大值抑制
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 在图像中绘制检测结果
for i in indices:
i = i[0]
box = boxes[i]
left = box[0]
top = box[1]
width = box[2]
height = box[3]
cv2.rectangle(img, (left, top), (left + width, top + height), (0, 255, 0), 2)
label = f'{classes[class_ids[i]]}: {confidences[i]:.2f}'
cv2.putText(img, label, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
# 显示图像
cv2.imshow('Image', img)
cv2.waitKey(0)
```