How do I fix “RuntimeError: Unable to open shape_predictor_68_face_landmarks.dat” while using google colab?

烈酒焚心 提交于 2021-02-11 15:18:12

问题


I am writing the following Python code in Google Colaboratory and get an error:

Code:

import cv2
import dlib

cap = cv2.VideoCapture(0)

hog_face_detector = dlib.get_frontal_face_detector()

dlib_facelandmark = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

while True: _,
frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

faces = hog_face_detector(gray)
for face in faces:

    face_landmarks = dlib_facelandmark(gray, face)

    for n in range(0, 16):
        x = face_landmarks.part(n).x
        y = face_landmarks.part(n).y
        cv2.circle(frame, (x, y), 1, (0, 255, 255), 1)


cv2.imshow("Face Landmarks", frame)

key = cv2.waitKey(1)
if key == 27:
    break
cap.release()
cv2.destroyAllWindows()

Error:

RuntimeError Traceback (most recent call last) in () 6 hog_face_detector = dlib.get_frontal_face_detector() 7 ----> 8 dlib_facelandmark = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") 9 10 while True:

RuntimeError: Unable to open shape_predictor_68_face_landmarks.dat


回答1:


Your notebook is unable to open the file shape_predictor_68_face_landmarks.dat. This may happen because the file isn't uploaded on your notebook, or because the path you specified in dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") is wrong.

The following is an edit of your code that automatically downloads the bzip2 file, extracts it and sets it as your shape predictor. You can use different .dat files by changing the link of !wget.

Cell 1:

!wget   http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2 # DOWNLOAD LINK

!bunzip2 /content/shape_predictor_68_face_landmarks.dat.bz2

datFile =  "/content/shape_predictor_68_face_landmarks.dat"

Cell 2:

import cv2 
import dlib

cap = cv2.VideoCapture(0)

hog_face_detector = dlib.get_frontal_face_detector()

dlib_facelandmark = dlib.shape_predictor(datFile)

while True: _, 
frame = cap.read() 
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

faces = hog_face_detector(gray)
for face in faces:

    face_landmarks = dlib_facelandmark(gray, face)

    for n in range(0, 16):
        x = face_landmarks.part(n).x
        y = face_landmarks.part(n).y
        cv2.circle(frame, (x, y), 1, (0, 255, 255), 1)


cv2.imshow("Face Landmarks", frame)

key = cv2.waitKey(1)
if key == 27:
    break
cap.release() 
cv2.destroyAllWindows()

Moreover, be aware that if you use cv2.VideoCapture(0) on a Jupyter notebook to open a camera it won't work, since the code is running on some remote server, and not on you computer. Look at the snippet here for an example on how to access your local webcam in Colab.



来源:https://stackoverflow.com/questions/64643440/how-do-i-fix-runtimeerror-unable-to-open-shape-predictor-68-face-landmarks-dat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!