python - python opencv相机无法打开
问题描述
我用python运行了以下代码。但是没有视频显示画面。所以摄像头灯亮了,但是看不到视频画面。
操作系统:Windows 10 x64 python:3.9.1
来源 https://github.com/GangYuanFan/Closed-Eye-Detection-with-opencv/blob/master/cv_close_eye_detect.py
import cv2
eye_cascPath = 'haarcascade_eye_tree_eyeglasses.xml'
face_cascPath = 'haarcascade_frontalface_alt.xml'
faceCascade = cv2.CascadeClassifier(face_cascPath)
eyeCascade = cv2.CascadeClassifier(eye_cascPath)
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
while 1:
ret, img = cap.read()
if ret:
frame = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = faceCascade.detectMultiScale(
frame,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
# flags = cv2.CV_HAAR_SCALE_IMAGE
)
#print("Found {0} faces!".format(len(faces)))
if len(faces) > 0:
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
frame_tmp = img[faces[0][1]:faces[0][1] + faces[0][3], faces[0][0]:faces[0][0] + faces[0][2]:1, :]
frame = frame[faces[0][1]:faces[0][1] + faces[0][3], faces[0][0]:faces[0][0] + faces[0][2]:1]
eyes = eyeCascade.detectMultiScale(
frame,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
# flags = cv2.CV_HAAR_SCALE_IMAGE
)
if len(eyes) == 0:
print('no eyes!!!')
else:
print('eyes!!!')
frame_tmp = cv2.resize(frame_tmp, (400, 400), interpolation=cv2.INTER_LINEAR)
cv2.imshow('Face Recognition', frame_tmp)
waitkey = cv2.waitKey(1)
if waitkey == ord('q') or waitkey == ord('Q'):
cv2.destroyAllWindows()
break
解决方案
看起来你只是cv2.imshow()
在if len(faces) > 0:
条件内,试着把它放在if ret:
条件下,你至少应该看到 cv2 相机窗口弹出。
推荐阅读
- react-native - 随机选择 DynamoDB 条目
- r - 重命名列表中的数据框列
- amazon-web-services - AWS - Alexa 指令定义
- ios - 在 UIStackView 对齐过程中实际做什么 isBaselineRelativeArrangement 属性?
- c# - 我收到 System.BadImageFormatException: Invalid Image System.Runtime.InteropServices.RuntimeInformation.dll 使用单声道运行 asp.net 应用程序时
- machine-learning - 模型训练:具有不同超参数的已保存模型的命名方案
- python - python方法名称动态执行-我可以期待什么样的漏洞?
- android - 如何根据名称获取鸡尾酒列表
- powershell - 我想从相对路径加载模块,以便在 PowerShell Repl 和 ISE 内从 cmd 提示符运行脚本时它可以工作
- r - R(Mac)在打开脚本时冻结