用Python-OpenCV 打开USB摄像头时, 出现如下提示, 意思是 媒体类型不匹配
测试源代码
cap = cv2.VideoCapture(0)
while cap.isOpened():
start = time.time()
is_opened, frame = cap.read()
end = time.time()
if i<10:
i+=1
print("### 读取图像流时间: %f 秒"%(end-start) )
start = time.time()
cv2.imwrite('I:/' + str(i) + '.jpg', frame)
end = time.time()
print("@@@ 保存图像时间: %f 秒" % (end - start))
cv2.imshow('frame', frame)
k = cv2.waitKey(1)
if k == 27:
break
elif k == ord('s'):
start = time.time()
cv2.imwrite('I:/' + str(i) + '.jpg', frame)
end = time.time()
print("@@@ 保存图像时间: %f 秒" % (end - start))
i += 1
cap.release()
错误提示为:
CvCapture_MSMF::initStream Failed to set mediaType (stream 0, (640x480 @ 30) MFVideoFormat_RGB24(codec not found)
需要在初始化摄像头是增加一个参数 cv2.CAP_DSHOW, 之后即可以正常打开:
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
使用普通用户,无权限打开摄像头, 而使用sudo, 则提示找不到cv2模块, 此时为环境变量问题, 有多种方法可以修改环境变量路径解决该问题, 比如修改/etc/sudoers, 编辑.bashrc,最后添加alias sudo='sudo env PATH=$PATH’等, 我主要使用如下方法
使用sudo -E指令,保留当前用户环境变量, 次方法用起来比较简单
debian@npi:~/tigerots/python$ sudo -E python open_cv2_photo.py
### 读取图像流时间: 1.561338 秒
### 读取图像流时间: 0.674829 秒
### 读取图像流时间: 0.622834 秒
debian@npi:~/tigerots/python$ python
Python 3.7.3 (default, Jul 25 2020, 13:03:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import sys
>>> sys.path
['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/debian/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages']
>>>
>>>
debian@npi:~/tigerots/python$ sudo python
Python 3.7.3 (default, Jul 25 2020, 13:03:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import sys
>>> sys.path
['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages']
>>>
import sys
sys.path.append("/usr/local/lib/python3.7/dist-packages")