2

我正在 Google Colaboratory中编写以下 Python 代码并收到错误消息:

代码

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()

错误

() 6 hog_face_detector = dlib.get_frontal_face_detector() 7 ----> 8 dlib_facelandmark = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") 9 10 中的 RuntimeError Traceback (最近一次调用最后一次) 为真:

RuntimeError:无法打开 shape_predictor_68_face_landmarks.dat

4

2 回答 2

1

您的笔记本无法打开该文件shape_predictor_68_face_landmarks.dat。这可能是因为文件没有上传到您的笔记本上,或者您指定的路径dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")错误。

以下是您的代码的编辑,它会自动下载bzip2文件、提取文件并将其设置为您的形状预测器。.dat您可以通过更改链接来使用不同的文件!wget

单元格 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"

单元格 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()

此外,请注意,如果您cv2.VideoCapture(0)在 Jupyter 笔记本上使用打开相机,它将无法工作,因为代码运行在某个远程服务器上,而不是在您的计算机上。查看此处的代码片段,了解如何在 Colab 中访问本地网络摄像头的示例。

于 2020-11-02T11:06:39.693 回答
0

对我来说,解决类似问题的方法是下载 Anaconda 3 并按照此处的指导安装 dlib:https ://learnopencv.com/install-dlib-on-windows/

我还将项目解释器更改为 Anaconda(我使用 PyCharm)

于 2021-03-15T11:11:07.703 回答