在Google Colab用cv2做视频人脸识别时遇cv2_imshow未定义错误求解决
Google Colab中cv2_imshow未定义的解决方法
你遇到的NameError: name 'cv2_imshow' is not defined错误,是因为cv2_imshow并非OpenCV原生函数,它是Google Colab为适配云端环境提供的专用显示函数,必须手动导入才能使用。
解决步骤
- 导入Colab专用的
cv2_imshow函数
在代码开头的import cv2之后添加一行导入语句:
from google.colab.patches import cv2_imshow
修改后的完整代码如下:
import cv2 from google.colab.patches import cv2_imshow # Load the cascade face_cascade = cv2.CascadeClassifier('/content/drive/MyDrive/haarcascade_frontalface_default.xml') # To capture video from webcam. #cap = cv2.VideoCapture(0) # To use a video file as input cap = cv2.VideoCapture('/content/drive/MyDrive/deepfake-detection-master/test_videos/aassnaulhq.mp4') while True: # Read the frame _, img = cap.read() # 新增判断:视频读完后自动终止循环 if img is None: break # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect the faces faces = face_cascade.detectMultiScale(gray, 1.1, 4) # Draw the rectangle around each face for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) # Display cv2_imshow(img) # Release the VideoCapture object cap.release()
补充说明
Colab是云端环境,OpenCV原生的cv2.imshow()函数会导致内核崩溃,因此必须使用cv2_imshow。另外,原代码中的cv2.waitKey()在Colab中无法响应本地键盘按键,建议通过判断img是否为空来自动终止循环,避免无限等待。
内容的提问来源于stack exchange,提问作者Sanjiro
相关产品推荐
相关产品推荐

