这是一个使用OpenCV和DNN的人脸检测程序,我有两个外部文件(deploy.prototxt.txt)和caffe模型文件(res10_300x300_ssd_iter_140000.caffemodel)有什么方法可以包含该文件,这样我就不必通过每次都争论。 终端命令: $ python3 人脸检测.py --image image --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel
import numpy as np
import argparse
import cv2
print("Program running.....")
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="Path to input image")
ap.add_argument("-p", "--prototxt", required=True,
help="Path to Caffe 'Deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
help="Path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
help="Minimum probability to filter weak detections")
args = vars(ap.parse_args())
print("[INFO] loading model....")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
image = cv2.imread("Input_Images/image.jpeg")
(h, w) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,
(300, 300), (104.0, 177.0, 123.0))
print("[INFO] computing object detections...")
net.setInput(blob)
detections = net.forward()
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > args["confidence"]:
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
text = "{:.2f}%".format(confidence * 100)
y = startY - 10 if startY - 10 > 10 else startY + 10
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)
cv2.putText(image, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 255), 2)
cv2.imshow("Output", image)
cv2.waitKey(0)
程序运行得很好,我只想通过单击运行按钮来运行程序。
您可以使用默认值作为您的参数。
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="Path to input image" default="image")
ap.add_argument("-p", "--prototxt", required=True,
help="Path to Caffe 'Deploy' prototxt file", default="deploy.prototxt.txt")
ap.add_argument("-m", "--model", required=True,
help="Path to Caffe pre-trained model", default="res10_300x300_ssd_iter_140000.caffemodel")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
help="Minimum probability to filter weak detections")
args = vars(ap.parse_args())
另一种可能的解决方案是扫描当前目录以查找文件扩展名为
*.caffemodel
、*.prototxt.txt
的文件。from pathlib import Path
cwd = Path.cwd()
prototxt = cwd.glob('*.prototxt.txt')[0]
model = cwd.glob('*.caffemodel')[0]
请注意,如果在工作目录中找不到匹配的文件,此实现将引发索引错误。