【跟官网学opencv-python】笔记1.1:图像与视频的读写显存

目录

前言

一、图像操作

参数详解

1、cv2.imread(filename: Any, flags: Any = None)读取图像

2、cv2.imshow(winname: Any, mat: Any)显示图像

3、cv2.imwrite(filename: Any, img: Any, params: Any = None) 保存图像

代码演示

二、视频操作

参数详解

1、从相机获取视频

        1.1、连接计算机摄像头

        1.2、连接外部(海康)工业相机

2、从文件读取播放视频

3、保存视频

代码演示

参考


前言

跟着官网学习才是基础入门的最佳选择,下文是opencv-python官网的学习记录及扩展!

一、图像操作

参数详解

1、cv2.imread(filename: Any, flags: Any = None)读取图像

filename:图像路径

flags:图像颜色模式,默认空缺时为彩色模式
        cv2.IMREAD_GRAYSCALE:以灰度模式读入图像,可用数字  0  代替
        cv2.IMREAD_COLOR:读入彩色图像,可用数字  1  代替
        cv2.IMREAD_UNCHANGED: 保持原图格式读取,可用数字  -1 代替

cv2.imread('lena.png', 0) # cv2.imread('lena.png', cv2.IMREAD_GRAYSCALE) 
cv2.imread('lena.png', 1) # cv2.imread('lena.png', cv2.IMREAD_COLOR)

2、cv2.imshow(winname: Any, mat: Any)显示图像

winname: 窗口名称
mat: 读取到的图像数据

cv2.namedWindow('Display window', cv2.WINDOW_NORMAL) #设定可调窗口
# cv2.WINDOW_NORMAL可用数字 0 代替,默认为cv2.WINDOW_AUTOSIZE = 1
cv2.imshow('image',img) #显示图像
cv2.waitKey(0) #等待键盘输入,为毫秒级
cv2.destroyAllWindows() #可以轻易删除任何我们建立的窗口,括号内输入想删除的窗口名

3、cv2.imwrite(filename: Any, img: Any, params: Any = None) 保存图像

filename: 保存图像的全路径
img: 图像数据
params: 见官方文档

cv2.imwrite('lena_save.png', img)

读写操作中的flags和param详细设置见官方文档:

OpenCV: Flags used for image file reading and writing

代码演示

import cv2
import sys

cv2.namedWindow('Display window', cv2.WINDOW_NORMAL)  # cv2.WINDOW_NORMAL:0  cv2.WINDOW_AUTOSIZE:1

img = cv2.imread("./lena.png", cv2.IMREAD_GRAYSCALE)  # IMREAD_COLOR:1  IMREAD_GRAYSCALE:0
if img is None:
    sys.exit("Could not read the image.")
print("Image Shape: " + str(img.shape))
cv2.imshow("Display window", img)
k = cv2.waitKey(0)
if k == ord("s"):  # wait for 's' key to save and exit
    cv2.imwrite("./lena_save.png", img)
elif k == 27:  # wait for ESC key to exit
    cv2.destroyWindow("Display window")  # destroy specified window by winname
    cv2.destroyAllWindows()  # destroy all windows

二、视频操作

参数详解

1、从相机获取视频

cv2.VideoCapture(flag)

flag: 0为默认计算机默认摄像头,1可以更换来源

1.1、连接计算机摄像头

import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # Our operations on the frame come here
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv.imshow('frame', gray)
    if cv.waitKey(1) == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

当代码报错时,可以使用cap.isOpened()来检查是否成功初始化了,返回值是True,就没有问题,否则就要使用cap.open()。
可以使用cap.get(propId)来获取视频的一些参数信息。propId可以是0到18之间的任何数,每一个数代表一个属性。
其中一些值可以使用cap.set(propId,value)来修改,例如cap.get(3)和cap.get(4)来查看每一帧的宽和高,默认是640x480。我们可以使用ret=cap.set(3,320)和ret = cap.set(4,240)来把宽和高改成320x240。

1.2、连接外部(海康)工业相机

采用海康工业相机测试

首先,安装海康相机的SDK,海康机器人-机器视觉-下载中心 (hikrobotics.com)

安装DirectShow,在MVS软件目录D:\Program Files\MVS\MVS\Development\ThirdPartyPlatformAdapter\DirectShow\x64\MvDSS2\InstallDSSvc_x64.bat 以管理员运行安装DirectShow。

运行代码如下:

import cv2

cap = cv2.VideoCapture(1)  # 调用摄像头‘0’一般是打开电脑自带摄像头,‘1’是打开外部摄像头(只有一个摄像头的情况)

if False == cap.isOpened():
    print(0)
else:
    print(1)

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 5120)  # 设置图像宽度
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 5120)  # 设置图像高度
cap.set(cv2.CAP_PROP_FPS, 4)  # 设置帧率
# 显示图像
cv2.namedWindow('frame',0)
while True:
    ret, frame = cap.read()
    frame_1 = cv2.resize(frame, (640, 480))
    cv2.imshow("frame", frame_1)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imwrite("gray.png", gray)

    input = cv2.waitKey(1)
    if input == ord('q'):
        break

cap.release()  # 释放摄像头
cv2.destroyAllWindows()  # 销毁窗口

2、从文件读取播放视频

把设备索引号改成文件名即可。在播放每一帧时,使用cv2.waitKey()适当持续时间,一般可以设置25ms。

    import cv2 as cv

    cap = cv.VideoCapture('vtest.avi')
    while cap.isOpened():
        ret, frame = cap.read()
        # if frame is read correctly ret is True
        if not ret:
            print("Can't receive frame (stream end?). Exiting ...")
            break
        gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        cv.imshow('frame', gray)
        cv.waitKey(25)  # set 25ms to slow video
        if cv.waitKey(1) == ord('q'):
            break
    cap.release()
    cv.destroyAllWindows()

确保安装了正确版本的 ffmpeg 或 gstreamer。有时使用视频捕获会令人头疼,主要是由于错误地安装了ffmpeg / gstreamer。

3、保存视频

创建一个VideoWrite的对象,指定输出文件名,指定FourCC编码,播放频率和帧的大小,最后是isColor标签,True为彩色。
FourCC是一个4字节码,用来确定视频的编码格式。
1.In Fedora : DIVX , XVID , MJPG , X264 , WMV1 , WMV2
XVID是最好的,MJPG是高尺寸视频,X264得到小尺寸视频
2.In Windows : DIVX
3.In OSX :MJPG (.mp4), DIVX (.avi), X264 (.mkv).

设置FourCC格式时,原文里采用了cv2.VideoWriter_fourcc()这个函数,若运行程序的时候显示这个函数不存在,可以改用了cv2.cv.CV_FOURCC这个函数。

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi', fourcc, 20.0, (640,  480))
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    frame = cv.flip(frame, 0)
    # write the flipped frame
    out.write(frame)
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break
# Release everything if job is finished
cap.release()
out.release()
cv.destroyAllWindows()

代码演示

import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")

    # open video file
    import cv2 as cv

    cap = cv.VideoCapture('../Resources/vtest.avi')

    # Define the codec and create VideoWriter object
    fourcc = cv.VideoWriter_fourcc(*'XVID')
    out = None

    while cap.isOpened():
        ret, frame = cap.read()
        if out is None:
            h,w,c=frame.shape
            print(h,w,c)
            out = cv.VideoWriter('../Resources/output.avi', fourcc, 20.0, (w, h))

        # if frame is read correctly ret is True
        if not ret:
            print("Can't receive frame (stream end?). Exiting ...")
            break

        frame = cv.flip(frame, 0)
        # write the flipped frame
        out.write(frame)

        gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        cv.imshow('frame', gray)
        # cv.waitKey(25)  # set 25ms to slow video
        if cv.waitKey(1) == ord('q'):
            break
    cap.release()
    out.release()
    cv.destroyAllWindows()

    exit()
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # Our operations on the frame come here
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv.imshow('frame', gray)
    if cv.waitKey(1) == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

参考

OpenCV: OpenCV-Python Tutorials

学习、进步、坚持。。。内容不间断更新中。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值