目标检测进阶:使用深度学习和 OpenCV 进行目标检测(2)
load our serialized model from disk
print(“[INFO] loading model…”)
net = cv2.dnn.readNetFromCaffe(prototxt, model_path)
加载输入图像并为图像构造一个输入blob
将大小调整为固定的300x300像素。
(注意:SSD模型的输入是300x300像素)
image = cv2.imread(image_name)
(h, w) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843,
(300, 300), 127.5)
通过网络传递blob并获得检测结果和
预测
print(“[INFO] computing object detections…”)
net.setInput(blob)
detections = net.forward()
从磁盘加载模型。
读取图片。
提取高度和宽度(第 35 行),并从图像中计算一个 300 x 300 像素的 blob。
将blob放入神经网络。
计算输入的前向传递,将结果存储为 detections。
循环检测结果
for i in np.arange(0, detections.shape[2]):
提取与数据相关的置信度(即概率)
预测
confidence = detections[0, 0, i, 2]
通过确保“置信度”来过滤掉弱检测
大于最小置信度
if confidence > confidence_ta:
从detections中提取类标签的索引,
然后计算物体边界框的 (x, y) 坐标
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(image, (startX, startY), (endX, endY),
COLORS[idx], 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(image, label, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
show the output image
cv2.imshow(“Output”, image)
cv2.imwrite(“output.jpg”, image)
cv2.waitKey(0)
循环检测,首先我们提取置信度值。
当置信度达到或超过预设阈值时
然后,提取框的 (x, y) 坐标,我们将很快使用它来绘制矩形和显示文本。
接下来,构建一个包含 CLASS 名称和置信度的文本标签。
应用标签,并将其输出至终端设备;接着结合历史获取的 (x, y) 坐标点,在对象周围绘制一个基于这些坐标的彩色矩形。
通常,在大多数情况下我们倾向于将希望标签放置在矩形的上方位置。然而,在缺乏足够的空间时,则会将其显示在矩形上方的右侧位置。
最后,使用刚刚计算的 y 值将彩色文本覆盖到图像上。
结果:

=========================================================================
打开一个新文件,将其命名为 video_object_detection.py ,并插入以下代码:
video_name = ‘12.mkv’
prototxt = ‘MobileNetSSD_deploy.prototxt.txt’
model_path = ‘MobileNetSSD_deploy.caffemodel’
confidence_ta = 0.2
initialize the list of class labels MobileNet SSD was trained to
detect, then generate a set of bounding box colors for each class
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))
load our serialized model from disk
print(“[INFO] loading model…”)
net = cv2.dnn.readNetFromCaffe(prototxt, model_path)
initialze the video stream, allow the camera to sensor to warmup,
and initlaize the FPS counter
print(‘[INFO] starting video stream…’)
vs = cv2.VideoCapture(video_name)
fps = 30 #保存视频的FPS,可以适当调整
size=(600,325)
fourcc=cv2.VideoWriter_fourcc(*‘XVID’)
videowrite=cv2.VideoWriter(‘output.avi’,fourcc,fps,size)
time.sleep(2.0)
定义全局参数:
video_name:输入视频的路径。
prototxt :Caffe prototxt 文件的路径。
model_path :预训练模型的路径。
confidence_ta :过滤弱检测的最小概率阈值。 默认值为 20%。
接下来,让我们初始化类标签和边界框颜色。
加载模型。
初始化VideoCapture对象。
创建VideoWriter对象并配置相关参数。其尺寸由以下代码确定,并且必须保持一致以确保视频能够被正确保存。

依次循环视频中的每一帧,并将其逐帧输入到检测器中进行图像识别过程。其逻辑流程与图像识别技术高度一致。代码如下:
loop over the frames from the video stream
while True:
ret_val, frame = vs.read()
if ret_val is False:
break
frame = imutils.resize(frame, width=1080)
print(frame.shape)
grab the frame dimentions and convert it to a blob
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 0.007843, (300, 300), 127.5)
Forwarding the blob through the network to receive detections and predictions.
Propagating the blob through to get detection and prediction results.
net.setInput(blob)
detections = net.forward()
loop over the detections
for i in np.arange(0, detections.shape[2]):
extract the confidence (i.e., probability) associated with
the prediction
confidence = detections[0, 0, i, 2]
filter out weak detections by ensuring the confidence is
greater than the minimum confidence
if confidence > confidence_ta:
extract the index of the class label from the
detections, then compute the (x, y)-coordinates of
the bounding box for the object
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”)
draw the prediction on the frame
label = “{}: {:.2f}%”.format(CLASSES[idx],
confidence * 100)
cv2.rectangle(frame, (startX, startY), (endX, endY),
COLORS[idx], 2)
y = \text{startY} - 15(当\text{startY} - 15 > 15时);否则y = \text{startY} + 15
许多Python工程师普遍面临职业发展困境:一方面渴望提升专业技能以实现职业突破另一方面却在选择自主学习与参加培训课程之间难以抉择。高昂的学费(通常在几千元以上)使得他们感到压力重重而缺乏系统化的学习路径导致自学效果低效且耗时漫长容易被技术瓶颈所限制无法实现真正的技术突破。
为此我特意汇编整理了一份《2024年Python开发全套学习资料》其目的在于为那些渴望自主提升技能却又感到迷茫不知所措的人群提供一份便捷的学习资源






不仅提供适合初学者入门的基础学习资料,
同时为有3年以上开发经验的专业人士提供了深入学习和能力提升的专业课程,
覆盖了前端开发领域的95%以上核心知识点,
真正具备系统性和全面性!
考虑到文件体积较大,在此仅作为参考提供部分目录大纲截图。具体包括大厂面经、学习笔记、源码讲义、实战项目以及讲解视频等内容,并后续内容也会持续补充中。
如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注Python)
g]()

不仅包含适合初学者入门学习的基础资源,
还设有针对有3年以上开发经验的专业人士提供的高级课程,
大致涵盖了所有前端开发所需的知识点,
真正具备系统性!
因为文件较大,在此处仅对目录大纲进行了简要截图,并涵盖以下内容:大厂面经、学习笔记、源码讲义、实战项目及讲解视频等资源;后续会不断更新和完善相关内容以提供更丰富的学习资源。
如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注Python)

