You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCV项目中Video Capture模块无法正常工作的求助

OpenCV项目中Video Capture模块无法正常工作的求助

先看一下你提供的代码和问题描述:你说摄像头能启动但无法读取画面,且最后两行代码无效,我来帮你梳理下可能的问题点和解决办法。

首先,先贴出你当前的代码(已修正缩进,方便查看):

import face_recognition
import cv2
import numpy as np
import csv
import os
from datetime import datetime

video_capture = cv2.VideoCapture(0)

tata_img = face_recognition.load_image_file("photos/tata.jpg")
tata_encoding = face_recognition.face_encodings(tata_img)[0]

modi_img = face_recognition.load_image_file("photos/modi.jpg")
modi_encoding = face_recognition.face_encodings(modi_img)[0]

ambani_img = face_recognition.load_image_file("photos/ambani.jpg")
ambani_encoding = face_recognition.face_encodings(ambani_img)[0]

known_face_encoding = [tata_encoding, modi_encoding, ambani_encoding]
known_face_names = ["tata", "modi", "ambani"]

students = known_face_names.copy()

face_locations = []
face_encodings = []
face_names = []
s=True

now = datetime.now()
current_date = now.strftime("%Y-%m-%d")

f = open(current_date+'.csv','w+',newline = '')
lnwriter = csv.writer(f)

while True:
    _,frame = video_capture.read()
    small_frame = cv2.resize(frame,(0,0),fx=0.25,fy=0.25)
    rgb_small_frame = small_frame[:,:,::-1]

    if s:
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encoding = face_recognition.face_encodings(rgb_small_frame,face_locations)
        face_names = []
        for face_encoding in face_encodings:
            matches = face_recognition.compare_faces(known_face_encoding,face_encoding)
            name = ""
            face_distance = face_recognition.face_distance(known_face_encoding,face_encoding)
            best_match_index = np.argmin(face_distance)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]
            face_names.append(name)
            if name in known_face_names:
                if name in students:
                    students.remove(name)
                    print(students)
                    current_time = now.strftime("%H-%M-%S")
                    lnwriter.writerow([name, current_time])

    cv2.imshow("attendence system", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()
f.close()

# 以下是冗余的错误代码
_,frame = video_capture.read()
video_capture.release()

问题分析与解决办法

1. 冗余代码导致的错误

你代码最后两行_,frame = video_capture.read()和video_capture.release()是完全多余的:在循环结束后,你已经调用了video_capture.release()释放了摄像头资源,之后再调用read和release肯定会失败,直接删掉这两行即可。

2. 摄像头无法读取画面的核心问题

摄像头能启动但无法读取画面,大概率是以下几个原因:

  • 摄像头索引错误:cv2.VideoCapture(0)中的0不一定是你当前使用的摄像头索引。如果是笔记本有内置摄像头+外接摄像头,或者系统默认摄像头不是0,尝试把参数换成1或者-1(自动选择可用摄像头):
    video_capture = cv2.VideoCapture(1)  # 或者 cv2.VideoCapture(-1)
    
  • 权限问题:
    • Windows系统:检查是否允许Python访问摄像头(在系统设置→隐私→摄像头中确认权限开启)。
    • Linux/Mac系统:需要确保当前用户拥有摄像头访问权限,Linux下可以执行sudo usermod -aG video $USER添加用户到video组,然后重启终端。
  • OpenCV版本兼容性:虽然你安装了opencv-python和contrib,但版本可能存在冲突。建议卸载现有版本后重新安装稳定版:
    pip uninstall opencv-python opencv-contrib-python
    pip install opencv-python==4.5.5.62 opencv-contrib-python==4.5.5.62
    

3. 代码逻辑的其他小问题

除了摄像头的问题,你的代码还有几个逻辑小错误,会影响考勤功能:

  • 时间不更新:now = datetime.now()是在循环外定义的,只会获取程序启动时的时间,应该把current_time = datetime.now().strftime("%H-%M-%S")放在循环内,每次识别到人脸时获取当前时间。
  • 缩进错误:原来的if name in known_face_names:这段代码缩进不正确,应该放在for循环内部,否则逻辑会混乱(已经在上面的修正代码中调整)。

修正后的完整代码

这里给你整理了修正后的代码,解决了上述问题:

import face_recognition
import cv2
import numpy as np
import csv
import os
from datetime import datetime

# 尝试更换摄像头索引,0不行换1或-1
video_capture = cv2.VideoCapture(0)

tata_img = face_recognition.load_image_file("photos/tata.jpg")
tata_encoding = face_recognition.face_encodings(tata_img)[0]

modi_img = face_recognition.load_image_file("photos/modi.jpg")
modi_encoding = face_recognition.face_encodings(modi_img)[0]

ambani_img = face_recognition.load_image_file("photos/ambani.jpg")
ambani_encoding = face_recognition.face_encodings(ambani_img)[0]

known_face_encoding = [tata_encoding, modi_encoding, ambani_encoding]
known_face_names = ["tata", "modi", "ambani"]

students = known_face_names.copy()

face_locations = []
face_encodings = []
face_names = []
s=True

current_date = datetime.now().strftime("%Y-%m-%d")

f = open(current_date+'.csv','w+',newline = '')
lnwriter = csv.writer(f)

while True:
    # 检查read是否成功
    ret, frame = video_capture.read()
    if not ret:
        print("无法读取摄像头画面,请检查摄像头连接或索引")
        break
        
    small_frame = cv2.resize(frame,(0,0),fx=0.25,fy=0.25)
    rgb_small_frame = small_frame[:,:,::-1]

    if s:
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame,face_locations)
        face_names = []
        for face_encoding in face_encodings:
            matches = face_recognition.compare_faces(known_face_encoding,face_encoding)
            name = ""
            face_distance = face_recognition.face_distance(known_face_encoding,face_encoding)
            best_match_index = np.argmin(face_distance)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]
            face_names.append(name)
            if name in known_face_names and name in students:
                students.remove(name)
                print(f"已签到:{name},剩余未签到:{students}")
                # 每次获取当前时间
                current_time = datetime.now().strftime("%H-%M-%S")
                lnwriter.writerow([name, current_time])

    cv2.imshow("attendence system", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()
f.close()

可以先尝试更换摄像头索引,然后运行修正后的代码,应该能解决摄像头无法读取的问题。如果还是不行,再检查权限和OpenCV版本。

备注:内容来源于stack exchange,提问作者Darshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 16:03:14