代码拉取完成,页面将自动刷新
同步操作将从 欧红旭/车辆特征信息提取 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
import tensorflow as tf
import os
import cv2 as cv
import numpy as np
import cv2
import time
weightsPath = "./yolo/yolov3.weights"
configPath = "./yolo/yolov3.cfg"
labelsPath = "./yolo/coco.names"
rootdir = "./detection_img" # 图像读取地址
savepath = "./detection_out_img" # 图像保存地址
# 初始化一些参数
LABELS = open(labelsPath).read().strip().split("\n") # 物体类别
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8") # 颜色
filelist = os.listdir(rootdir) # 打开对应的文件夹
total_num = len(filelist) # 得到文件夹中图像的个数
print("图片数量:"+str(total_num))
# 如果输出的文件夹不存在,创建即可
if not os.path.isdir(savepath):
os.makedirs(savepath)
with tf.Graph().as_default() as graph:
with tf.compat.v1.Session().as_default() as sess:
for (dirpath, dirnames, filenames) in os.walk(rootdir):
startTime = time.time()
for filename in filenames:
# 必须将boxes在遍历新的图片后初始化
boxes = []
confidences = []
classIDs = []
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
path = os.path.join(dirpath, filename)
image = cv.imread(path)
try:
(H, W) = image.shape[:2]
except:
print(path)
else:
# 得到 YOLO需要的输出层
ln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 从输入图像构造一个blob,然后通过加载的模型,给我们提供边界框和相关概率
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
layerOutputs = net.forward(ln)
# 在每层输出上循环
for output in layerOutputs:
# 对每个检测进行循环
for detection in output:
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
# 过滤掉那些置信度较小的检测结果
if confidence > 0.7:
mytype = "{}".format(LABELS[classID])
if mytype == "car" or mytype == "bus" or mytype == "truck" or mytype == "motorbike" or mytype == "bicycle":
# 框后接框的宽度和高度
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
# 边框的左上角
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
# 更新检测出来的框
# 批量检测图片注意此处的boxes在每一次遍历的时候要初始化,否则检测出来的图像框会叠加
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
# 极大值抑制
idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.2, 0.3)
k = -1
if len(idxs) > 0:
# for k in range(0,len(boxes)):
for i in idxs.flatten():
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
# 在原图上绘制边框和类别
color = [int(c) for c in COLORS[classIDs[i]]]
# image是原图, 左上点坐标, 右下点坐标, 颜色, 画线的宽度
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
text = "{}".format(LABELS[classIDs[i]])
if text == "car" or text == "bus" or text == "truck":
text="car"
# 各参数依次是:图片,添加的文字,左上角坐标(整数),字体, 字体大小,颜色,字体粗细
cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
cv2.imwrite(savepath + "/" + filename.split(".")[0] + ".jpg", image)
endTime = time.time()
print("程序运行时间:%.8s s" % (endTime-startTime))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。