请编写一个Python程序,使用yolo对图片识别昼夜、交通信号灯和车辆
时间: 2024-05-09 16:18:05 浏览: 6
好的,以下是Python程序,使用yolo对图片进行昼夜、交通信号灯和车辆识别:
```python
import cv2
import numpy as np
import time
# 加载yolo模型
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
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()]
# 加载图片
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)
# 将图片输入到yolo模型中进行识别
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_PLAIN
colors = np.random.uniform(0, 255, size=(len(classes), 3))
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
color = colors[class_ids[i]]
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, label, (x, y - 5), font, 1, color, 1)
# 显示识别结果
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,这个程序只是一个简单的示例,实际使用中需要根据具体情况进行修改和优化。同时,由于yolo模型的识别结果并不是完全准确的,可能会存在误判的情况,需要根据实际情况进行判断和处理。