OpenCV Quick Start II: Camera reading and saving (including binocular reading and saving)

Camera read and save (including binocular read and save)

In the previous section, we learned how to read and save pictures . Today we will learn how to read the camera.

1: Related APIs

Windows presses and holds down Ctrl and clicks on the relevant API to jump to the packaging page.
If the api has any suggestions that you don't understand, go directly to the OpenCV official website , and then you can see how netizens explain it.

VideoCapure()				#创建对象0是本地摄像头,1是外接
cap.read()					#返回读取状态——Ture  False返回视频帧
cap.release()				#释放资源 
cv2.VideoWriter_fourcc()	#视频保存格式
cv2.VideoWriter()			#视频保存

Two: Camera reading

1. Quote

import cv2

2. Create a camera object

cap=cv2.VideoCapture(0)

3. Read and display frame by frame

while True:
    ret,fame=cap.read()
    cv2.imshow('video',fame)

Three: source code

1. Camera reading

import cv2

cv2.namedWindow('video',cv2.WINDOW_AUTOSIZE)
cv2.resizeWindow('video',640,480)#设置窗口大小
#获取视频设备
cap=cv2.VideoCapture(0)#将0换成文件名,可进行文件播放,注意路径
while True:
    ret,fame=cap.read()
    cv2.imshow('video',fame)
    #等待键盘事件
    key=cv2.waitKey(1)#为0则只显示一帧
    #若播放过快,造成卡顿
	#key=cv2.waitKey(40)#25帧-1000/25
    if(key&0xff==ord('q')):
        break
#释放viedcapture
cap.release()
#销毁所有窗口
cv2.destroyAllWindows()

2. Video save

import cv2
#创建videowrite
fourcc=cv2.VideoWriter_fourcc(*'MJPG')#mp4
#保存的文件名,格式,大小
vw=cv2.VideoWriter('./out.mp4',fourcc,25,(640,480))#这里的(640,480)是摄像头真实的分辨率,否则可能造成保存的画面显示不出

cv2.namedWindow('video',cv2.WINDOW_AUTOSIZE)

cap=cv2.VideoCapture(0)
#判断是否打开
while cap.isOpened():
    #读摄像头
    ret,fame=cap.read()
    if ret==True:
        cv2.imshow('video',fame)
        #若改窗口大小写这
        # cv2.resizeWindow('video',640,480)
        #写数据
        vw.write(fame)
        key=cv2.waitKey(1)#为0则只显示一帧
        if(key&0xff==ord('q')):
            break
    else:
        break
#释放viedcapture
cap.release()
#释放
vw.release()
cv2.destroyAllWindows()

3.1 Binocular read and save

The binoculars I used here are two identical USB cameras, and I fixed them on an acrylic board.

I disabled the webcam on my computer in device manager

disable camera

3.2 Code display

import cv2
import time

cap = cv2.VideoCapture(0+cv2.CAP_DSHOW)
cap1 = cv2.VideoCapture(1+cv2.CAP_DSHOW)
#有时候不设置图片输出大小可能读取失败
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 720)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap1.set(cv2.CAP_PROP_FRAME_WIDTH, 720)
cap1.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

flag = cap.isOpened()
index = 1

while (flag):
    ret, frame = cap.read()
    ret, frame1 = cap1.read()
    if not ret:
        break
    cv2.imshow('left', frame)
    cv2.imshow("right", frame1)

    # for i in range(100):这里本来想实现自动拍照
    #     #resize = cv2.resize(frame, (512,512), interpolation=cv2.INTER_NEAREST)
    #     #cv2.imwrite(str(index)+'.jpg', resize)
    #     cv2.imwrite("C:\\Users\\DMr\\Pictures\\shaungmu\\left" + str(index) + ".jpg", frame)
    #     cv2.imwrite("C:\\Users\\DMr\\Pictures\\shaungmu\\right" + str(index) + ".jpg", frame1)
    #     time.sleep(0.5)
    #
    #     i += 1


    k = cv2.waitKey(1) & 0xFF
    if k & 0xff == ord('s'):  # 按下s键,进入下面的保存图片操作
        cv2.imwrite("C:\\Users\\DMr\\Pictures\\shaungmu\\left" + str(index) + ".jpg", frame)
        cv2.imwrite("C:\\Users\\DMr\\Pictures\\shaungmu\\right" + str(index) + ".jpg", frame1)
        print(cap.get(3))#列(宽度)
        print(cap.get(4))#行(高度)
        print("save" + str(index) + ".jpg successfuly!")
        print("-------------------------")
        index += 1
    elif k == ord('q'):
        break
cap.release()
cap1.release()
cv2.destroyAllWindows()

output
two eyes

4. Video frame extraction

import cv2
import os
def video2im(video_name, train_path='D:\\Pictures\\video2img',factor=2):
    if not os.path.exists(train_path):
        os.makedirs(train_path)
    frame = 0
    cap = cv2.VideoCapture(video_name)
    length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    print('Total Frame Count:',length)

    while True:
        check, img = cap.read()
        if check:
            img = cv2.resize(img,(1920//factor,1080//factor))
            cv2.imwrite(os.path.join(train_path,str(frame).zfill(4)+'.jpg'),img)
            frame += 1
            # print('Processed: ',frame)
        else:
            break
    cap.release()
video2im('C:\\Users\\26901\\Videos\\2.mp4')

Daily "Big Pie":
If fate is the worst screenwriter in the world, you have to strive to be the best actor in your own life

Guess you like

Origin blog.csdn.net/weixin_52051554/article/details/125806395