10 基于深度学习的目标检测
首次完成时间:2024 年 11月 20 日
1. 使用OpenCV的dnn模块实现图像分类。
1)程序代码:
import numpy as np
import cv2
# 解析标签文件
row = open("model1/synset_words.txt").read().strip().split("\n")
class_label = [r[r.find(" "):].split(",")[0] for r in row]
# 载入caffe所需的配置文件
net = cv2.dnn.readNetFromCaffe("model1/bvlc_googlenet.prototxt",
"model1/bvlc_googlenet.caffemodel")
# 读取待分类图像
img = cv2.imread("photos/cat.jpg") # 确保这里的路径是正确的
# 转换格式
blob = cv2.dnn.blobFromImage(img, 1, (224, 224), (104, 117, 123))
# 加载图像
net.setInput(blob)
# 预测
preds = net.forward()
# 排序,取概率最大的结果
idx = np.argsort(preds[0])[-1]
# 获取图片的原始尺寸
(h, w) = img.shape[:2]
# 等比例缩减图片大小
resized_img = cv2.resize(img, (w // 4, h // 4))
# 可视化处理,显示图像类别、置信度等信息
text = "label: {}-{:.2f}%".format(class_label[idx], preds[0][idx] * 100)
cv2.putText(resized_img, text, (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0))
# 显示缩减后的图片
cv2.imshow("resized_result", resized_img)
# 保存缩减后的图片
cv2.imwrite("photos/resized_result.jpg", resized_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2)代码分析:
2. 使用OpenCV实现目标检测,实现发现不明车辆或行人进入检测区,即进行报警。
1)程序代码:
import numpy as np
import cv2
def prepareDataSet():
# 准备数据集
args = {}
args["prototxt"] = "model2/MobileNetSSD_deploy.prototxt"
args["model"] = "model2/MobileNetSSD_deploy.caffemodel"
return args
def createNet():
# 构建网络模型对象
args = prepareDataSet()
# load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
return net
if __name__ == "__main__":
# 定义类别名称序列
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog",
"horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
# 定义边框颜色序列
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
# 打开摄像头或视频文件
camera = cv2.VideoCapture("videos/12686501_3840_2160_60fps.mp4")
# 构建网络模型
net = createNet()
while True:
ret, frame = camera.read()
if ret:
# 将帧的尺寸调整为1080p
frame = cv2.resize(frame, (1920, 1080))
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(
frame, (300, 300)), 0.007843, (300, 300), 127.5)
net.setInput(blob)
detections = net.forward()
# 遍历结果
for i in np.arange(0, detections.shape[2]):
# 获得置信度
confidence = detections[0, 0, i, 2]
# 根据置信度阈值过滤执行度
if confidence > 0.2:
# 根据最大置信度获取类别下标
idx = int(detections[0, 0, i, 1])
# 获取位置信息
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
# 显示类别信息和位置边框
label = "{}: {:.2f}%".format(CLASSES[idx], confidence * 100)
print("[INFO] {}".format(label))
cv2.rectangle(frame, (startX, startY), (endX, endY), COLORS[idx], 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(frame, label, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
if CLASSES[idx] == "person":
print("raise the alarm")
# 显示结果
cv2.imshow("result", frame)
# 按下空格退出 or esc
if cv2.waitKey(1) == ord(' ') or cv2.waitKey(1) == 27:
break
else:
break
camera.release()
cv2.destroyAllWindows()