python实现目标检测代码
时间: 2023-07-22 12:41:41 浏览: 51
以下是使用Python实现目标检测的示例代码,基于YOLOv3算法和OpenCV库:
```python
import cv2
import numpy as np
# 加载模型和权重文件
model = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
# 加载类别标签和颜色
classes = []
with open('coco.names', 'r') as f:
classes = [line.strip() for line in f.readlines()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))
# 加载待检测的图像
image = cv2.imread('image.jpg')
# 对图像进行预处理和变换
blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)
# 使用模型对处理后的图像进行预测和检测
model.setInput(blob)
layer_names = model.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in model.getUnconnectedOutLayers()]
outputs = model.forward(output_layers)
# 对检测结果进行后处理和筛选
boxes = []
confidences = []
class_ids = []
for output in outputs:
for detection in output:
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])
w = int(detection[2] * image.shape[1])
h = int(detection[3] * image.shape[0])
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)
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[0], box[1], box[2], box[3]
color = colors[class_ids[i]]
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
text = f"{classes[class_ids[i]]}: {confidences[i]:.2f}"
cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# 将结果可视化并输出
cv2.imshow('Object Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
需要注意的是,上述代码仅为示例代码,实际应用中需要根据具体情况进行调整和优化。