Python 通过MobilenetSSD检测循环
我有一个问题可能很简单,但我发现代码中有一部分很难理解Python 通过MobilenetSSD检测循环,python,loops,for-loop,cv2,Python,Loops,For Loop,Cv2,我有一个问题可能很简单,但我发现代码中有一部分很难理解 for subdir, dirs, files in os.walk(directory): for file in files: filepath = subdir + os.sep + file image = cv2.imread(filepath) (h, w) = image.shape[:2] blob = cv2.dnn.blobFromImage(cv2
for subdir, dirs, files in os.walk(directory):
for file in files:
filepath = subdir + os.sep + file
image = cv2.imread(filepath)
(h, w) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5)
# pass the blob through the neural network
net.setInput(blob)
detections = net.forward()
# loop over the detections
for i in np.arange(0, detections.shape[2]):
# extract the confidence (i.e., the probability) associated with the prediction
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(label)
label2 = "{}".format(CLASSES[idx])
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)
if label2 == 'person':
cv2.imwrite('output/persons/pic' + str(number) + '.jpg', image)
number += 1
现在,脚本以不需要的方式运行。例如,如果图片有五个人,它会将同一张图片保存五次。如果我是对的,就是这个部分导致了问题,因为它循环了图片中的所有检测:
# loop over the detections
for i in np.arange(0, detections.shape[2]):
# extract the confidence (i.e., the probability) associated with the prediction
confidence = detections[0, 0, i, 2]
如果照片中有人,我想保存一次。我不知道如何修改脚本,因为np.arange(0,detections.shape[2])中I的I
:也用于置信度和idx
值中。所以仅仅把东西从循环中移出是行不通的。欢迎任何建议和帮助