完整代码
# 1.导入cv库
import cv2
# 2.打开摄像头
capture = cv2.VideoCapture(0) # 0表示笔记本内置摄像头
# 3.读取帧的宽度,高度,每秒闪过多少图片
frame_width = capture.get(cv2.CAP_PROP_FRAME_WIDTH)
frame_height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
fps = capture.get(cv2.CAP_PROP_FPS)
print(f'帧的宽度:{frame_width}')
print(f'帧的高度:{frame_height}')
print(f'FPS:{fps}')
# 4.判断摄像头是否打开
if capture.isOpened is False:
print("error")
# 5.打开摄像头直至关闭
while (capture.isOpened()):
# 6.读取帧(图像)
re, img = capture.read()
"""
re:是否读取到帧
img:读取到的帧,可以理解为图像
"""
# 7.显示读取到的图像
cv2.imshow('img', img)
# 8.将帧转换为灰度
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 9.显示灰度图像
cv2.imshow('gary_img',gray_img)
# 10.按‘空格’关闭摄像头
if cv2.waitKey(10) & 0xFF == 32:
break
# 11.关闭所有窗口
capture.release()
cv2.destroyAllWindows()
问题:代码可以正常运行,但存在红色警告
帧的宽度:640.0
帧的高度:480.0
FPS:30.0
[ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-9d_dfo3_\opencv\modules\videoio\src\cap_msmf.cpp (435) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
进程已结束,退出代码0
改正方法:修改 #2
# 2.打开摄像头
将
capture = cv2.VideoCapture(0)
修改为:
capture = cv2.VideoCapture(0,cv2.CAP_DSHOW) #更改API设置
修改之后的代码运行:正常且完美
帧的宽度:640.0
帧的高度:480.0
FPS:0.0
进程已结束,退出代码0