OpenCV yolov5目标检测
时间: 2023-09-27 12:11:18 浏览: 61
要使用OpenCV YOLOv5目标检测,您需要安装OpenCV、NumPy和YOLOv5模型。以下是一些基本步骤:
1. 安装OpenCV和NumPy:
```
pip install opencv-python numpy
```
2. 下载YOLOv5模型:
```
git clone https://github.com/ultralytics/yolov5.git
```
3. 加载YOLOv5模型:
```python
import cv2
import numpy as np
net = cv2.dnn.readNet("yolov5s.pt", "yolov5s.yaml")
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
```
4. 运行目标检测:
```python
img = cv2.imread("test.jpg")
height, width, channels = img.shape
blob = cv2.dnn.blobFromImage(img, 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] * 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)
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
font = cv2.FONT_HERSHEY_SIMPLEX
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
color = (0, 255, 0)
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, label, (x, y - 5), font, 0.5, color, 2)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这将加载YOLOv5模型,读取输入图像,运行目标检测并在图像上绘制边界框。您可以将此代码作为脚本运行或将其集成到您的项目中。