error: (-2:Unspecified error) FAILED: fs.is_open(). Can‘t open “res10_300x300_ssd_iter_140000_fp16.“

**

在做opencv dnn 人脸检测的时候一直遇到这个问题,翻遍了谷歌、csdn、Stack Overflow,毛都没有。最后自己摸索出来解决方案如下:

**
1、使用绝对路径
2、使用了绝对路径还不行,试试标注下参数,例如:

readNetFromCaffe(prototxt="D:\github\Opencv-Algorithm-summary\deploy.prototxt"

3、以上方法还是没解决,试试把“\”改为“\\”。
笔者这边正常运行的代码:

#coding=utf-8
import numpy as np
import cv2,os,time

def show_detections(image,detections):
    h,w,c=image.shape
    for i in range(0, detections.shape[2]):
        confidence = detections[0, 0, i, 2]
        if confidence >0.6:
            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, 255,0), 1)
            cv2.putText(image, text, (startX, y),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)
    return image
 
def detect_img(net,image):
    blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,
	(300, 300), (104.0, 177.0, 123.0))
    net.setInput(blob)
    start=time.time()
    detections = net.forward()
    end=time.time()
    print(end-start)
    return show_detections(image,detections)
 
def test_dir(net,dir="images"):
    files=os.listdir(dir)
    for file in files:
        filepath=dir+"/"+file
        img=cv2.imread(filepath)
        showimg=detect_img(net,img)
        cv2.imshow("img",showimg)
        cv2.waitKey()
 
def test_camera(net):
    cap=cv2.VideoCapture(0)
    while True:
        ret,img=cap.read()
        if not ret:
            break
        showimg=detect_img(net,img)
        cv2.imshow("img",showimg)
        cv2.waitKey(1)      
    
if __name__=="__main__":
    net = cv2.dnn.readNetFromCaffe(prototxt="D:\github\Opencv-Algorithm-summary\deploy.prototxt",caffeModel="D:\\github\\Opencv-Algorithm-summary\\res10_300x300_ssd_iter_140000_fp16.caffemodel")
    #net =cv2.dnn.readNetFromTensorflow(model="D:\opencv\opencv\sources\samples\dnn\face_detector\opencv_face_detector_uint8.pb",config="D:\opencv\opencv\sources\samples\dnn\face_detector\opencv_face_detector.pbtxt")
    #test_dir(net)
    test_camera(net)
### OpenCV 加载 prototxt 文件失败的原因分析与解决方法 OpenCV 中 `cv2.dnn.readNet` 或者 `cv2.dnn.readNetFromCaffe` 函数用于加载 Caffe 模型文件(`.caffemodel`)以及其对应的配置文件(`.prototxt`)。如果遇到错误提示 `cv2.error: (-2:Unspecified error) FAILED: fs.is_open()`,通常表示无法打开指定的模型或者配置文件。 #### 错误原因 此错误的主要原因是程序未能成功找到并读取所需的 `.prototxt` 配置文件或 `.caffemodel` 模型文件。可能的原因包括但不限于以下几点: 1. **文件路径不正确** 如果提供的路径不是目标文件的实际存储位置,则会引发该错误。相对路径可能导致运行环境不同而失效[^1]。 2. **文件不存在或损坏** 若指定路径下的文件缺失或已损坏,也会触发相同的错误消息[^2]。 3. **权限不足** 当前用户对目标文件所在的目录缺乏访问权限时,同样会出现此类问题[^3]。 4. **编码问题** 使用某些特殊字符定义路径可能会引起兼容性问题,在 Windows 平台尤其需要注意反斜杠 `\` 的转义处理[^4]。 #### 解决方案 以下是几种常见的解决策略: - **使用绝对路径代替相对路径** 绝对路径可以有效避免因工作目录变化而导致找不到文件的情况。例如: ```python ageProto = '/absolute/path/to/age_deploy.prototxt' ageModel = '/absolute/path/to/age_net.caffemodel' ageNet = cv2.dnn.readNet(ageModel, ageProto) ``` - **确认文件存在性和完整性** 在尝试加载之前,先验证所需文件确实存在于给定路径下,并且未被意外修改或破坏。 ```python import os if not os.path.isfile('/path/to/file'): raise FileNotFoundError('The specified file does not exist.') ``` - **调整参数声明方式** 对于部分版本可能存在解析差异的情况下,显式指明各参数有助于提高稳定性。比如采用如下形式调用函数: ```python net = cv2.dnn.readNetFromCaffe(prototxt='/full/path/deploy.prototxt', caffeModel='/full/path/res10_300x300_ssd_iter_140000.caffemodel') ``` - **检查操作系统特定需求** 特别是在跨平台开发过程中要注意路径分隔符的一致性。对于Windows系统推荐利用原始字符串(`r''`)来规避不必要的转义操作影响。 ```python protoPath = r"C:\Users\User\Desktop\model\deploy.prototxt" modelPath = r"C:\Users\User\Desktop\model\res10_300x300_ssd_iter_140000.caffemodel" detector = cv2.dnn.readNetFromCaffe(protoPath, modelPath) ``` 通过上述措施基本能够应对大部分由于路径设置不当所引起的加载失败情形。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值