import cv2
#引入库
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
cv2.imshow("Video", frame)
#读取内容
if cv2.waitKey(10) == ord("q"):
break
#随时准备按q退出
cap.release()
cv2.destroyAllWindows()
#停止调用,关闭窗口
将
cap = cv2.VideoCapture(0)
改成
cap = cv2.VideoCapture(1)
,如果有多个摄像头,考虑将 1 改成 2 或3等。
import cv2 # 调用usb摄像头 cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 480) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 640) cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc("M", "J", "P", "G")) # 显示 while True: ret, frame = cap.read() cv2.imshow("Video Display", frame) cv2.imshow("Video Display2", frame) cv2.imshow("Video Display3", frame) cv2.imshow("Video Display4", frame) cv2.imshow("Video Display5", frame) cv2.imshow("Video Display6", frame) if cv2.waitKey(1) & 0xFF == ord("q"): break # 关闭 cap.release() cv2.destroyAllWindows()
如果测试时,报错,可能是摄像头分辨率参数不对,以上的480宽度,640高度是从摄像头的参数上看到的。 如果摄像头上没有标出参数,可以通过以下代码获取:
import cv2
videoCaputer = cv2.VideoCapture(0)
size = (int(videoCaputer.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(videoCaputer.get(cv2.CAP_PROP_FRAME_WIDTH)))
print(size) #错误结果(480,640)
# 只要set下,貌似size就发生了变化
videoCaputer.set(cv2.CAP_PROP_FRAME_WIDTH,5000)
videoCaputer.set(cv2.CAP_PROP_FRAME_HEIGHT,5000)
size = (int(videoCaputer.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(videoCaputer.get(cv2.CAP_PROP_FRAME_WIDTH)))
_,frame = videoCaputer.read()
print(size) # 正确结果(1024,1280)
print(frame.shape)# 正确结果(1024,1280, 3)
参考链接: https://www.jianshu.com/p/3b42df1850b2
但有时测试时,这段代码也能用。也能读取台式机外接USB摄像头的图像。
import cv2
#引入库
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
cv2.imshow("Video", frame)
#读取内容
if cv2.waitKey(10) == ord("q"):
break
#随时准备按q退出
cap.release()
cv2.destroyAllWindows()
#停止调用,关闭窗口
Python+Opencv 调用USB摄像头(一)https://blog.csdn.net/Programmer_ch/article/details/89057129
Python+Opencv 调用USB摄像头(二) https://blog.csdn.net/Programmer_ch/article/details/89429677