yolov3一次检测多张图片python
时间: 2023-04-26 11:02:25 浏览: 66
您好,要一次检测多张图片,可以使用以下步骤:
1. 导入yolov3模型和相关库
2. 定义要检测的图片路径列表
3. 循环遍历图片路径列表,读取每张图片并进行检测
4. 将检测结果保存到指定的输出路径
具体实现可以参考以下代码:
```
import cv2
import numpy as np
import os
# 导入yolov3模型和相关库
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_folder = "images"
img_paths = [os.path.join(img_folder, img_name) for img_name in os.listdir(img_folder)]
# 循环遍历图片路径列表,读取每张图片并进行检测
for img_path in img_paths:
# 读取图片
img = cv2.imread(img_path)
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_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 + 30), font, 3, color, 3)
# 将检测结果保存到指定的输出路径
output_path = os.path.join("output", os.path.basename(img_path))
cv2.imwrite(output_path, img)
```
其中,`img_folder`为要检测的图片所在文件夹路径,`yolov3.weights`、`yolov3.cfg`和`coco.names`为yolov3模型和类别名称文件的路径,`output`为检测结果保存的文件夹路径。运行以上代码即可一次检测多张图片。