Python 使用 Opencv 库调用摄像头

Python 使用 Opencv 库调用摄像头

1、引用Opencv库
import cv2

Tips:未安装opencv库直接命令行安装:pip install opencv-python

2、打开摄像头
camera = cv2.VideoCapture(1,cv2.CAP_DSHOW)

Tips:1代表打开外置摄像头,0代表电脑内置摄像头(本人使用的是外接摄像头),外置多个摄像头可依此枚举 0,1,2…

3、设定摄像头参数

例子设置摄像头分辨率 1920 *1080:

width = 1920
heigth = 1080
camera.set(cv2.CAP_PROP_FRAME_WIDTH,width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT,heigth)

获取摄像头参数例子如下(传入具体参数即可):

heigth = camera.get(cv2.CAP_PROP_FRAME_WIDTH,width)

摄像头参数具体有如下:

CAP_PROP_POS_MSEC       =0, //!< Current position of the video file in milliseconds.
CAP_PROP_POS_FRAMES     =1, //!< 0-based index of the frame to be decoded/captured next.
CAP_PROP_POS_AVI_RATIO  =2, //!< Relative position of the video file: 0=start of the film, 1=end of the film.
CAP_PROP_FRAME_WIDTH    =3, //!< Width of the frames in the video stream.
CAP_PROP_FRAME_HEIGHT   =4, //!< Height of the frames in the video stream.
CAP_PROP_FPS            =5, //!< Frame rate.
CAP_PROP_FOURCC         =6, //!< 4-character code of codec. see VideoWriter::fourcc .
CAP_PROP_FRAME_COUNT    =7, //!< Number of frames in the video file.
CAP_PROP_FORMAT         =8, //!< Format of the %Mat objects (see Mat::type()) returned by VideoCapture::retrieve().
					   //!< Set value -1 to fetch undecoded RAW video streams (as Mat 8UC1).
CAP_PROP_MODE           =9, //!< Backend-specific value indicating the current capture mode.
CAP_PROP_BRIGHTNESS    =10, //!< Brightness of the image (only for those cameras that support).
CAP_PROP_CONTRAST      =11, //!< Contrast of the image (only for cameras).
CAP_PROP_SATURATION    =12, //!< Saturation of the image (only for cameras).
CAP_PROP_HUE           =13, //!< Hue of the image (only for cameras).
CAP_PROP_GAIN          =14, //!< Gain of the image (only for those cameras that support).
CAP_PROP_EXPOSURE      =15, //!< Exposure (only for those cameras that support).
CAP_PROP_CONVERT_RGB   =16, //!< Boolean flags indicating whether images should be converted to RGB. <br/>
					   //!< *GStreamer note*: The flag is ignored in case if custom pipeline is used. It's user responsibility to interpret pipeline output.
CAP_PROP_WHITE_BALANCE_BLUE_U =17, //!< Currently unsupported.
CAP_PROP_RECTIFICATION =18, //!< Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently).
CAP_PROP_MONOCHROME    =19,
CAP_PROP_SHARPNESS     =20,
CAP_PROP_AUTO_EXPOSURE =21, //!< DC1394: exposure control done by camera, user can adjust reference level using this feature.
CAP_PROP_GAMMA         =22,
CAP_PROP_TEMPERATURE   =23,
CAP_PROP_TRIGGER       =24,
CAP_PROP_TRIGGER_DELAY =25,
CAP_PROP_WHITE_BALANCE_RED_V =26,
CAP_PROP_ZOOM          =27,
CAP_PROP_FOCUS         =28,
CAP_PROP_GUID          =29,
CAP_PROP_ISO_SPEED     =30,
CAP_PROP_BACKLIGHT     =32,
CAP_PROP_PAN           =33,
CAP_PROP_TILT          =34,
CAP_PROP_ROLL          =35,
CAP_PROP_IRIS          =36,
CAP_PROP_SETTINGS      =37, //!< Pop up video/camera filter dialog (note: only supported by DSHOW backend currently. The property value is ignored)
CAP_PROP_BUFFERSIZE    =38,
CAP_PROP_AUTOFOCUS     =39,
CAP_PROP_SAR_NUM       =40, //!< Sample aspect ratio: num/den (num)
CAP_PROP_SAR_DEN       =41, //!< Sample aspect ratio: num/den (den)
CAP_PROP_BACKEND       =42, //!< Current backend (enum VideoCaptureAPIs). Read-only property
CAP_PROP_CHANNEL       =43, //!< Video input or Channel Number (only for those cameras that support)
CAP_PROP_AUTO_WB       =44, //!< enable/ disable auto white-balance
CAP_PROP_WB_TEMPERATURE=45, //!< white-balance color temperature
CAP_PROP_CODEC_PIXEL_FORMAT =46,    //!< (read-only) codec's pixel format. 4-character code - see VideoWriter::fourcc . Subset of [AV_PIX_FMT_*](https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/raw.c) or -1 if unknown
CAP_PROP_BITRATE       =47, //!< (read-only) Video bitrate in kbits/s
CAP_PROP_ORIENTATION_META=48, //!< (read-only) Frame rotation defined by stream meta (applicable for FFmpeg back-end only)
CAP_PROP_ORIENTATION_AUTO=49, //!< if true - rotates output frames of CvCapture considering video file's metadata  (applicable for FFmpeg back-end only) (https://github.com/opencv/opencv/issues/15499)
CAP_PROP_HW_ACCELERATION=50, //!< (**open-only**) Hardware acceleration type (see #VideoAccelerationType). Setting supported only via `params` parameter in cv::VideoCapture constructor / .open() method. Default value is backend-specific.
CAP_PROP_HW_DEVICE      =51, //!< (**open-only**) Hardware device index (select GPU if multiple available). Device enumeration is acceleration type specific.
CAP_PROP_HW_ACCELERATION_USE_OPENCL=52, //!< (**open-only**) If non-zero, create new OpenCL context and bind it to current thread. The OpenCL context created with Video Acceleration context attached it (if not attached yet) for optimized GPU data copy between HW accelerated decoder and cv::UMat.
CAP_PROP_OPEN_TIMEOUT_MSEC=53, //!< (**open-only**) timeout in milliseconds for opening a video capture (applicable for FFmpeg back-end only)
CAP_PROP_READ_TIMEOUT_MSEC=54, //!< (**open-only**) timeout in milliseconds for reading from a video capture (applicable for FFmpeg back-end only)
CAP_PROP_STREAM_OPEN_TIME_USEC =55, //<! (read-only) time in microseconds since Jan 1 1970 when stream was opened. Applicable for FFmpeg backend only. Useful for RTSP and other live streams
CAP_PROP_VIDEO_TOTAL_CHANNELS = 56, //!< (read-only) Number of video channels
CAP_PROP_VIDEO_STREAM = 57, //!< (**open-only**) Specify video stream, 0-based index. Use -1 to disable video stream from file or IP cameras. Default value is 0.
CAP_PROP_AUDIO_STREAM = 58, //!< (**open-only**) Specify stream in multi-language media files, -1 - disable audio processing or microphone. Default value is -1.
CAP_PROP_AUDIO_POS = 59, //!< (read-only) Audio position is measured in samples. Accurate audio sample timestamp of previous grabbed fragment. See CAP_PROP_AUDIO_SAMPLES_PER_SECOND and CAP_PROP_AUDIO_SHIFT_NSEC.
CAP_PROP_AUDIO_SHIFT_NSEC = 60, //!< (read only) Contains the time difference between the start of the audio stream and the video stream in nanoseconds. Positive value means that audio is started after the first video frame. Negative value means that audio is started before the first video frame.
CAP_PROP_AUDIO_DATA_DEPTH = 61, //!< (open, read) Alternative definition to bits-per-sample, but with clear handling of 32F / 32S
CAP_PROP_AUDIO_SAMPLES_PER_SECOND = 62, //!< (open, read) determined from file/codec input. If not specified, then selected audio sample rate is 44100
CAP_PROP_AUDIO_BASE_INDEX = 63, //!< (read-only) Index of the first audio channel for .retrieve() calls. That audio channel number continues enumeration after video channels.
CAP_PROP_AUDIO_TOTAL_CHANNELS = 64, //!< (read-only) Number of audio channels in the selected audio stream (mono, stereo, etc)
CAP_PROP_AUDIO_TOTAL_STREAMS = 65, //!< (read-only) Number of audio streams.
CAP_PROP_AUDIO_SYNCHRONIZE = 66, //!< (open, read) Enables audio synchronization.
CAP_PROP_LRF_HAS_KEY_FRAME = 67, //!< FFmpeg back-end only - Indicates whether the Last Raw Frame (LRF), output from VideoCapture::read() when VideoCapture is initialized with VideoCapture::open(CAP_FFMPEG, {CAP_PROP_FORMAT, -1}) or VideoCapture::set(CAP_PROP_FORMAT,-1) is called before the first call to VideoCapture::read(), contains encoded data for a key frame.
CAP_PROP_CODEC_EXTRADATA_INDEX = 68, //!< Positive index indicates that returning extra data is supported by the video back end.  This can be retrieved as cap.retrieve(data, <returned index>).  E.g. When reading from a h264 encoded RTSP stream, the FFmpeg backend could return the SPS and/or PPS if available (if sent in reply to a DESCRIBE request), from calls to cap.retrieve(data, <returned index>).
CAP_PROP_FRAME_TYPE = 69, //!< (read-only) FFmpeg back-end only - Frame type ascii code (73 = 'I', 80 = 'P', 66 = 'B' or 63 = '?' if unknown) of the most recently read frame.

Tips:具体哪些参数可调节取决于你的摄像头支持哪些参数调节,可通过打印参数值判断参数是否可以通过opencv库直接调节参数,返回值为-1项,一般代表不支持此参数设置,摄像头的某些参数一般情况下不要去调节。

示例

for i in range(15):
    print("No.={} parameter={}".format(i,camera.get(i)))

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YJy7F8GE-1659751896189)(file://C:\Users\user\AppData\Roaming\marktext\images\2022-08-06-09-49-51-image.png?msec=1659750591707)]

4、打开摄像头设置好参数后就可以拍照或者录制屏幕了

楼主写了一个demo,只是为了演示拍照功能,不喜忽喷。

控制台输入1将自动捕捉一帧按下时的画面,并生成一张图片(生成照片在程序相同目录下)

控制台输入3窗口实施显示当前摄像头画面,按ESC退出窗口显示

# -*- coding: utf-8 -*-
"""
Created on Fri Jul 29 19:41:05 2022

@author: user
"""
import cv2
import numpy as np
import threading
import time
from multiprocessing import Process, Queue
import os, time, random

class Camera(threading.Thread):
    __slots__ = ['camera','Flag','count','width','heigth','frame']
    def __init__(self):
        threading.Thread.__init__(self)
        self.camera = cv2.VideoCapture(0,cv2.CAP_DSHOW)
        self.Flag = 0
        self.count = 1
        self.width = 1920
        self.heigth = 1080
        self.name = ''
        self.path = ''
        self.camera.set(cv2.CAP_PROP_FRAME_WIDTH,self.width)
        self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT,self.heigth)
        #for i in range(46):
            #print("No.={} parameter={}".format(i,self.camera.get(i)))
    def run(self):
        while True:
            ret, self.frame =  self.camera.read() # 摄像头读取,ret为是否成功打开摄像头,true,false。 frame为视频的每一帧图像
            self.frame = cv2.flip(self.frame, 1) # 摄像头是和人对立的,将图像左右调换回来正常显示。
            if self.Flag == 1:
                print("拍照")
                if self.name == ''and self.path == '':
                    cv2.imwrite(str(self.count) + '.jpg', self.frame) #将画面写入到文件中生成一张图片
                elif self.name != '':
                    cv2.imwrite(self.name+ '.jpg', self.frame)
                self.count+=1
                self.Flag = 0
            if self.Flag == 2:
                print("退出")
                self.camera.release()#释放内存空间
                cv2.destroyAllWindows()#删除窗口
                break
            
    def take_photo(self):
        self.Flag = 1
    def exit_program(self):
        self.Flag = 2
    def set_name(self,str):
        self.name = str
    def set_path(self,str):
        self.path = str

def show_window(cap):
        while True:
            cv2.namedWindow("window", 1)# 1代表外置摄像头
            cv2.resizeWindow("window", cap.width,cap.heigth )  #指定显示窗口大小
            cv2.imshow('window', cap.frame)
            c = cv2.waitKey(50) #按ESC退出画面
            if c == 27:
                cv2.destroyAllWindows()
                break

if __name__ == '__main__':
    cap = Camera()
    cap.start()
    while True:
        i = int(input("input:"))
        if i == 1:
            cap.take_photo()
        if i == 2:
            cap.exit_program()
        if i == 3:
            recv_data_thread = threading.Thread(target=show_window,args=(cap,))
            recv_data_thread.start()
        time.sleep(1)
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

威威攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值