OpenCV: 01 picture & video loading display

learning target:

  • Understand the operating mechanism of OpenCV
  • Some image common problems can be handled with OpenCV
  • Learn how to deal with problems such as object recognition and text recognition

Loading display of images and videos

Import OpenCV packagecv2

# 导入opencv的包
import cv2

window operation

cv2.imshow('window',0) # imshow(winname, mat): 'mat' indicates what to display, 0 indicates nothing to display

# 创建窗口
#cv2.namedWindow('window',cv2.WINDOW_AUTOSIZE)
cv2.namedWindow('window',cv2.WINDOW_NORMAL)

# 更改窗口大小—>在窗口属性为‘WINDOW_AUTOSIZE’自动设置时无效果
cv2.resizeWindow('window',800,600) # resizeWindow(winname, width, height)

# 展示名字为window的窗口
cv2.imshow('window',0) # imshow(winname, mat):'mat'表示展示的内容,0表示什么都不展示

# 等待按键
#cv2.waitKey(0) # waitKey会返回按下按键的ASCII值(8位)
              # 值为‘0’表示接受任意按键,如果给其他的整数,表示等待按键的时间(单位:毫秒ms)
            # 比如waitKey(5000)如果5000ms后没有按键,则窗口无响应
        # 可以用waitKey来销毁窗口,不用每次都重启python
key = cv2.waitKey(0)
if key == ord('q'): # 如果按下键盘上的'q'
    print("准备销毁窗口")
    cv2.destroyAllWindows() # 销毁窗口

Calculate ASCIIthe value of the key

# 怎么计算按键'x'的ASCII码
# ord()是python中计算ASCII值的函数
ord('q')

read pictures

cv2.imread('./cat.jpeg') # ./是直接调用day1目录下的文件

Use other plugins to read (take matplotlibas an example)

First save the picture in our folder and name itcat.jpeg
insert image description here

import matplotlib.pyplot as plt
# 默认按照彩色图片来读取
cat = cv2.imread('./cat.jpeg') # ./是直接调用day1目录下的文件

# 调出cat的值
cat


# 利用matplotlib来显示图像
plt.imshow(cat)

# 我们会发现matplotlib显示的图片和真实的图片颜色不一样,发生了变化
    # 因为opencv读进来的通道不是默认的RGB(红绿蓝)通道,而是BGR(蓝绿红)
    # 因此opencv读进来的图片不要用别的方式去展示(如matplotlib),而是用opencv自带的方式去展示

Note: imshow()You don’t need to create a window when you call it separately, opencv will automatically generate it
insert image description here


Use OpenCVyour own way to display pictures

cv2.imshow('cat',cat)
key = cv2.waitKey(0)
if key == ord('q'): # 如果按下键盘上的'q'
    print("准备销毁窗口")
    cv2.destroyAllWindows() # 销毁窗口
    
# 执行时会弹出窗口,显示图片     按‘q’则退出窗口

Encapsulation of functions

If we need to display pictures frequently, then we can encapsulate the method of displaying pictures into a function to facilitate us to display pictures

Put this function in a file, if you need to use it, just import the file directly

Save the function as .pya file (named utils.py), in our folder

# 如果我们需要频繁地显示图片,那么我们可以把显示图片的方法封装成一个函数方便我们显示图片
    # 把这个函数放在一个文件里,需要使用的话就直接导入文件即可
def cv_show(name,img):
    import cv2
    cv2.imshow(name,img)
    
    # 关闭窗口
    key = cv2.waitKey(0)
    if key  == ord('q') or key == ord('Q'):
        cv2.destroyAllWindows()

When we want to call the function, we can import the file

# 从外部py文件中导入工具类,即可直接使用
from utils import cv_show

Note: The file must be executed first after importing!

# 导入后必须先执行文件
%run utils.py

# 如果出现报错IndentationError:unindent does not match any outer indentation level
    # 那就是Tab和空格混用的缩进问题:本应该用Tab缩进,可能打成了空格缩进

use function

cv_show('cat',cat)

save Picture

imwrite(path,img): use imwrite to save the picture

import cv2

# 创建一个窗口
cv2.namedWindow('img',cv2.WINDOW_NORMAL)
cv2.resizeWindow('img',640,480)

# 读一个图片
img = cv2.imread('./cat.jpeg') # 打开当前目录下的图像文件

while True:# 进入循环,使得cv2不停地展示img图片
    cv2.imshow('img',img)
    key = cv2.waitKey(0) # 接受任意字符——>写0
    
    if key == ord('q'): # 按下按键'q'——> quit
        break
    elif key == ord('s'): # 按下按键's'——> save
        cv2.imwrite('./123.png',img) # 会把cv2.imshow('img',img)的图片保存到当前文件下下,命名为123.png
    else:
        print(key)

# 关闭窗口
cv2.destroyAllWindows()

insert image description here


Read camera and video data

turn on the camera

  • A video is composed of pictures, and each frame of the video is a picture, usually 30 frames, which means that 30 pictures are displayed in 1 second
  • cv2.VideoCapture()You can capture the camera and use numbers to represent different devices, such as 0, 1
  • If it is a video file, you can directly specify the path
import cv2
# VideoCapture()可以捕获摄像头:如果是视频文件,则直接在参数中写入路径即可;如果是电脑上的摄像头,则可以根据摄像头编号进行索引,通过这个简单的数字去指定调用的摄像头


# 打开视频文件 #
#vc = cv2.VideoCapture()  

# 打开摄像头 #
cv2.namedWindow('video',cv2.WINDOW_NORMAL)
cv2.resizeWindow('video',640,480)

# 如果打开失败或者没读到数据,会闪退,但并不会报错
#cap = cv2.VideoCapture(1)

cap = cv2.VideoCapture(0) # 该函数会返回一个对象,我们用cap来接受(0是笔记本自带的摄像头)

# 循环读取摄像头的每一帧
while True:
    # 读一帧数据(一帧=视频里的一幅图) 
    flag,frame = cap.read() # 返回“标记”和“这一帧数据(图片)”:True表示读取成功,False表示读取失败
    
    # 可以根据flag做判断
    if not flag:
        print("没读到数据!退出......")
        break
        
    # 显示数据
    else:
        cv2.imshow('video',frame)
        
    key = cv2.waitKey(1) # 此处不可以写0!因为0会允许任何输入并且一直在等待输入,如果这样写就只能看到一帧数据,并且一直在等待
                         # 此处写1,每隔1ms检测一次输入
    if key == ord('q'):
        break
        
# 别忘了释放资源!
cap.release()
cv2.destroyAllWindows()

open video

The operation of opening the video is the same as opening the camera: just modify it cap = cv2.VideoCapture(0)tocap = cv2.VideoCapture(‘./1.mp4’) # 括号内为路径

The released video will have an accelerated effect: because our code key = cv2.waitKey(1)executes the next picture every 1ms

So in order to play this video completely, we asked a question: If a video is 30 frames, how many milliseconds should there be between each picture?

# 1帧 = 1s内显示1张图片,每张图片用时t = 1/1(s) = 1000/1(ms)
# 30帧 = 1s内显示30张图片,每张图片用时t = 1/30(s) = 1000/30(ms)

key = cv2.waitKey(1000 // 30)	# 括号内必须是整数!"//"两个斜线表示除后向下取整

video recording

opencv opens a video or a camera, we store each captured frame in a video

  • VideoWrite: The first parameter is the output file, the second parameter is the multimedia file format, the third parameter is the frame rate, and the fourth parameter is the resolution
  • write: encode and write to cache
  • release: Write cached content to disk and release resources
import cv2
cap = cv2.VideoCapture(0) # 把摄像头捕获的内容存入cap中

# 创建对象 (fourcc表示视频的一种格式)
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # *mp4v表示“解包操作”——> 等同于解成'm','p','4','v'

# 创建对象
vw = cv2.VideoWriter('output.mp4',fourcc,30,(640,480)) # ('保存的文件名',指定存储的格式,帧率,摄像头的分辨率(一定要正确否则报错!))

# 判断摄像头是否打开
while cap.isOpened() :
    ret,frame = cap.read()
    if not ret: # 如果没有打开
        print('can not recive frame ,Exiting...')
        break
        
    else : # 如果成功打开——> 写每一帧数据
        vw.write(frame) # 把 这一帧数据 写到Videowriter中
        cv2.imshow('frame',frame) # 展示 这一帧数据 到窗口
        
    if cv2.waitKey(1) == ord('q') or cv2.waitKey(1) == ord('Q'):
        break

# 别忘了release
cap.release()
        
# 释放Videowriter
vw.release() # write是先写到缓存中,再由release写入到磁盘中 

cv2.destroyAllWindows()

video processing

OpenCVNot only can process images, but also can process video. A video is constructed from a large number of images, which are acquired from the video at regular time intervals . In this way, image processing methods can be used to process these images, thereby achieving the purpose of video processing.

To process video, you need to read, display, save and other related operations on the video first . For this purpose, classes and related methods of classes OpenCVare providedVideoCaptureVideoWrite


Camera

Camera video refers to the video read from the camera in real time. In order to read and display the camera video, related methods of the class OpenCVare provided , these methods include:VideoCapture

  • Camera initialization method
  • How to check whether the camera initialization is successful
  • How to read frames from camera
  • How to turn off the camera, etc.

Video is composed of a large number of images, which are called "frames"


Camera initialization

The VideoCapture class provides a construction method VideoCapture()for completing the initialization of the camera

Key API: capture = cv2.VideoCapture(index)
Among them:

  • index: device index of the camera
    • At that timeindex = 0 , it indicated that the first camera was to be turned on; for a 64-bit Window 10 notebook, it was indicated that the built-in camera of the notebook was to be turned on :capture = cv2.VideoCapture(0)
    • At that timeindex = 1 , it indicated that the second camera was to be opened; for a 64-bit Window 10 notebook, it was indicated that an external camera connected to the notebook was to be opened :capture = cv2.VideoCapture(1)

return value:

  • capture: the camera to open

Detect initialization results

In order to detect whether the camera is initialized successfully, VideoCapturethe class provides isOpened()methods

Key API: retval = cv2.VideoCapture.isOpened()
return value:

  • retval: If the camera is initialized successfully, retval = True; otherwise,retval = False
  • Note: Based on the initialization format, isOpened()the grammatical format of the method can be abbreviated asretval = capture.isOpened()

Read the image from the camera

When the camera is initialized, frames can be read from the camera , and methods are provided for VideoCapturethis classread()

Key API: retval,frame = cv2.VideoCapture.read()
Among them:

  • retval: Boolean type, whether to read the frame. If a frame was read, then retval = True; otherwiseretval = False
  • frame: The read frame. Because frames refer to the images that make up the video, "read frames" can be understood as "read images"
  • Note: Note: On the basis of the initialization format, read()the grammatical format of the method can be abbreviated asretval,frame = capture.read()

turn off camera

OpenCV particularly emphasizes on the official website that the camera must be turned off when the camera is not needed. For this purpose, the VideoCapture class provides the release() method.

Key API: cv2.VideoCapture.release()


Read and display camera video

Write a program to open the built-in camera of the notebook to read and display the video in real time. When the space bar is pressed , the built-in camera of the notebook is turned off and the window displaying the camera is destroyed

Sample code:

import cv2

capture = cv2.VideoCapture(0) # 打开笔记本内置摄像头

# 判断摄像头是否被打开
while(capture.isOpened()):
    # 如果打开
    retval,image = capture.read() # 从摄像头中实时读取数据
    cv2.imshow('video',image)# 从窗口中显示读取的数据
    
    
    #每1ms检测用户是否按下键盘
    key = cv2.waitKey(1)
    if key == 32: # 如果按下空格键
        break
    
# 释放内存
capture.release()
cv2.destroyAllWindows()

Convert camera video from color video to grayscale video

In the previous routine, we have successfully read and displayed the camera video, so how to process this video?

In fact, the method used to process video is the same as the method used to process images —>gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

Below we will use the related methods of image processing to convert the read and displayed color video into grayscale video

Sample code:

import cv2

capture = cv2.VideoCapture(0) # 打开笔记本内置摄像头

# 判断摄像头是否被打开
while(capture.isOpened()):
    # 如果打开
    retval,frame = capture.read() # 从摄像头中实时读取数据
    
    # 将读取到的帧转换为灰度图
    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    
    cv2.imshow('video',gray)# 从窗口中显示读取的数据
    
    
    #每1ms检测用户是否按下键盘
    key = cv2.waitKey(1)
    if key == 32: # 如果按下空格键
        break
    
# 释放内存
capture.release()
cv2.destroyAllWindows()

Display and save the image at a certain moment in the camera video

Write a program to turn on the built-in camera of the notebook, read and display the video in real time. When the space bar is pressed, the built-in camera of the notebook is turned off, and the image in the camera video at this moment is saved and displayed

Sample code:

import cv2

capture = cv2.VideoCapture(0) # 打开笔记本内置摄像头

# 判断摄像头是否被打开
while(capture.isOpened()):
    # 如果打开
    retval,frame = capture.read() # 从摄像头中实时读取数据
    cv2.imshow('Video',frame)
    #每1ms检测用户是否按下键盘
    key = cv2.waitKey(1)
    if key == 32: # 如果按下空格键  
        # 释放内存
        capture.release()
        cv2.destroyWindow('Video')
        cv2.imwrite('D:\OpenCV11\基于OpenCV的机器视觉\day1\copy.png',frame)
        cv2.imshow('img',frame)# 从窗口中显示读取的数据
        cv2.waitKey()
        
        break
    
# 释放内存
cv2.destroyAllWindows()

Read and display two camera videos

Write a program to open an external camera connected to the notebook while opening the notebook's built-in camera to read and display the video in real time.

When the space bar is pressed, the built-in camera of the notebook and the external camera connected to the notebook are turned off, and the window displaying the video is destroyed

Sample code:

import cv2

capture_Inner = cv2.VideoCapture(0) # 打开笔记本内置摄像头
capture_Outer = cv2.VideoCapture(1) # 打开一个连接笔记本的外置摄像头


# 判断摄像头是否被打开
while(capture_Inner.isOpened() and capture_Outer.isOpened()):
    # 如果两个摄像头都被打开
    retval_In,frame_In = capture_Inner.read() # 从内置摄像头中实时读取数据
    retval_Out,frame_Out = capture_Outer.read() # 从摄像头中实时读取数据
    
    # 展示
    cv2.imshow('Video_In',frame_In)
    cv2.imshow('Video_Out',frame_Out)
    
    
    #每1ms检测用户是否按下键盘
    key = cv2.waitKey(1)
    if key == 32: # 如果按下空格键 
        break
    
# 释放内存
capture_Inner.release()
capture_Outer.release()
cv2.destroyAllWindows()

play video file

VideoCaptureIn addition to reading and displaying camera video, the class and its methods can also read and display video files

When the window displays the video file according to the duration of the video file, the effect of playing the video file is realized


read and display video file

VideoCaptureThe construction method of the class VideoCapture()can not only be used to complete the initialization work of the camera, but also can be used to complete the initialization work of the video file. When VideoCapture()used to initialize a video file, its syntax is as follows:

Key API: video = cv2.VideoCapture(filename)
Among them:

  • filename: the file name of the open video

return value:

  • video: the video to open

Note: OpenCV can support video files in various formats, but in different operating systems, video files in a certain format may not be supported.
However, regardless of the operating system, OpenCV supports video files with the extension .avi

Sample code:

# 播放视频文件

import cv2

video = cv2.VideoCapture('./公司宣传.avi')


# 判断视频是否被打开
while(video.isOpened()):
    # 如果视频被成功打开
    retval ,frame = video.read()
    
    # 修改窗口大小
    cv2.namedWindow('video',cv2.WINDOW_NORMAL)
    cv2.resizeWindow('video',420,300)
    
    # 展示 ——> 当没有读到视频时自动退出!不写判断语句会发生报错
    if retval == True:
        cv2.imshow('video',frame)
    
    else:
        break
    
    
    #每1ms检测用户是否按下键盘
    key = cv2.waitKey(1)
    if key == 32: # 如果按下空格键 
        break
    
# 释放内存
video.release()
cv2.destroyAllWindows()

result:
insert image description here

Description: Adjust cv2.waitKey()the parameter value in the method to control the playback speed of the video file . For example, cv2.waitKey(1)at that time , the playback speed of the video file was very fast; cv2.waitKey(50)at that time, it was possible to slow down the playback speed of the video file


Convert video files from color video to grayscale video

Using related methods of image processing, the camera video color can be converted from color to grayscale video. Then, the same method can also be used to convert video files from color video to grayscale video

Key APIs:gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

Sample code:

# 将视频文件由彩色视频转换成灰度视频

import cv2

video = cv2.VideoCapture('./公司宣传.avi')


# 判断视频是否被打开
while(video.isOpened()):
    # 如果视频被成功打开
    retval ,frame = video.read()
    
    # 修改窗口大小
    cv2.namedWindow('video',cv2.WINDOW_NORMAL)
    cv2.resizeWindow('video',420,300)
    
   
    
    # 展示 ——> 当没有读到视频时自动退出!不写判断语句会发生报错
    if retval == True:
         # 转换为灰度视频
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        cv2.imshow('video',gray)
    else:
        break
    
    
    #每1ms检测用户是否按下键盘
    key = cv2.waitKey(1)
    if key == 27: # 如果按下ESC键 
        break
    
# 释放内存
video.release()
cv2.destroyAllWindows()

result:
insert image description here


Pausing and resuming video playback

Through the key command, in the process of playing the video, the video can be paused and played continuously

  • Continue to play: cv2.waitKey(50) # 括号内只要有非零数值即可, which means to detect whether the keyboard is pressed every 50ms: if it is pressed, the corresponding event will be executed; if it is not pressed, the video will continue to play
  • Pause playback: cv2.waitKey(0)Indicates that the machine waits indefinitely for the user to press a keyboard button, and stops playing the video at this time to achieve a pause effect

Sample code:

# 视频的暂停播放和继续播放

import cv2

video = cv2.VideoCapture('./公司宣传.avi')


# 判断视频是否被打开
while(video.isOpened()):
    # 如果视频被成功打开
    retval ,frame = video.read()
    
    # 修改窗口大小
    cv2.namedWindow('video',cv2.WINDOW_NORMAL)
    cv2.resizeWindow('video',420,300)
    
   
    
    # 展示 ——> 当没有读到视频时自动退出!不写判断语句会发生报错
    if retval == True:
         # 转换为灰度视频
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        cv2.imshow('video',gray)
    else:
        break
    
    
    #每1ms检测用户是否按下键盘
    key = cv2.waitKey(1)
    if key == 27: # 如果按下ESC键 
        break
        
    elif key == 32: # 如果按下空格键
        cv2.waitKey(0) # 无限等待用户按下键盘按键,实现暂停效果
        
        
    
# 释放内存
video.release()
cv2.destroyAllWindows()

Properties of video files

  • A video is composed of a large number of continuous images, each of which is called a frame
  • The number of frames refers to the total number of images contained in the video file, the more the number of frames, the smoother the video playback
  • In the process of playing video, the number of images displayed per second is called frame rate (FPS, unit: frame/s)
  • Frame width refers to the total number of pixels the image contains in the horizontal direction
  • Frame height refers to the total number of pixels the image contains in the vertical direction

save video file

In the actual development process, it is often desired to save a video, for which OpenCVa VideoWriteclass


constructor VideoWriteclass object

Key API: 创建的对象 = cv2.VideoWriter(filename,fourcc,fps,frameSize)
Among them:

  • filename: the path when saving the video (including the file name)
  • fourcc: video encoding format represented by 4 characters
    • In OpenCV, cv2.VideoWriter_fourcc()used to determine the video encoding format
    • commonly usedfourcc = cv2.VideoWriter_fourcc('X','V','I','D')
  • fps:Frame rate
  • frameSize: the size of each frame
  • Under the Windows operating system, the value of fourcc is fourcc = cv2.VideoWriter_fourcc('X','V','I','D'), the frame rate fps = 20, and the frame size isframeSize = (640 ,480)

like:

fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
# 也可以写成fourcc = cv2.VideoWriter_fourcc(* 'XVID')

output = cv2.VideoWriter('output.avi',fourcc,20,(640,480))

Save a webcam video

In order to save a video, in addition to using VideoWriterthe constructor of the class, you also need to use the methods VideoWriteprovided by the classwrite

write()VideoWriterThe function of the method is to write the read frame in the created class object

Key APIs:cv2.VideoWriter.write(frame)

  • frame: read frame

Note: write()When using a method, it needs VideoWriteto be called by the class object. For example , writing the read frame into the created VideoWriterclass object can be written asoutputoutput.write(frame)

VideoWriterAnd release the class object when not in use :cv2.VideoWriter.release()

Example: To write a program,
first open the built-in camera of the notebook, read and display the video in real time;
then press ESCthe key to close the built-in camera of the notebook, destroy the window displaying the video of the camera,
and save the video from turning on the camera to closing the camera as .avi video in the current folder

code show as below:

# 保存一段摄像头视频

import cv2

# 打开笔记本内置摄像头
capture = cv2.VideoCapture(0) 

# 确定视频被保存后的编码格式
fourcc = cv2.VideoWriter_fourcc(* 'XVID')
output = cv2.VideoWriter('D:\OpenCV11\基于OpenCV的机器视觉\day1\output.avi',fourcc,20,(640,480))

# 检测笔记本摄像头是否被打开
while (capture.isOpened()):
    retval,frame = capture.read()
    # 如果读取到图像
    if retval == True:
        # 在VideoWriter类对象中写入读取到的帧
        output.write(frame)
        
        # 在窗口中显示摄像头视频
        cv2.imshow('frame',frame)
        
    key = cv2.waitKey(1)
    if key == 27: # 如果按下了ESC键
        break
        
# 释放
capture.release()
output.release()
cv2.destroyAllWindows()

Notice! The above code can be run repeatedly. Since output.avi already exists in the current project path, the newly generated output.avi will overwrite the existing output.avi file


Save a camera video with a duration of 10s

write a program

  1. First turn on the built-in camera of the notebook, read and display the video in real time;
  2. Then record a camera video with a duration of 10 seconds: After 10 seconds, the built-in camera of the notebook is automatically turned off, and the window displaying the camera is destroyed at the same time
  3. Save this 10-second camera video as a file under the current project path10s.avi

Sample code:

# 保存一段摄像头视频

import cv2

# 打开笔记本内置摄像头
capture = cv2.VideoCapture(0) 

# 确定视频被保存后的编码格式
fourcc = cv2.VideoWriter_fourcc(* 'XVID')

# Windows10的帧速率
fps = 20

# 创建VideoWriter类对象
output = cv2.VideoWriter('D:\OpenCV11\基于OpenCV的机器视觉\day1\output.avi',fourcc,20,(640,480))

# 时长为10s的摄像头视频中含有的帧数
frame_Num = 10 * fps 

# 笔记本摄像头是否被打开 且 摄像头视频含有的帧数大于0
while (capture.isOpened() and frame_Num > 0):
    retval,frame = capture.read()
    # 如果读取到图像
    if retval == True:
        # 在VideoWriter类对象中写入读取到的帧
        output.write(frame)
        
        # 在窗口中显示摄像头视频
        cv2.imshow('frame',frame)
    
    # 时长为10s的摄像头视频含有的帧数减小一帧
    frame_Num -= 1
    
    key = cv2.waitKey(1)
    if key == 27: # 如果按下了ESC键
        break
        
# 释放
capture.release()
output.release()
cv2.destroyAllWindows()

save video file

The VideoWriter class can not only save camera video, but also save video files, and the steps to save video files and save cameras are the same

Sample code:

# 保存一段摄像头视频

import cv2

# 打开视频文件
video = cv2.VideoCapture('./公司宣传.avi')
# video = cv2.VideoCapture('./output.mp4')


# 获取视频文件的帧速率fps
fps = video.get(cv2.CAP_PROP_FPS)

# 获取视频文件的帧大小size
size = (int(video.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)))

# 确定视频被保存后的编码格式
fourcc = cv2.VideoWriter_fourcc('X','V','I','D')

# 创建VideoWriter类对象
output = cv2.VideoWriter('D:\OpenCV11\基于OpenCV的机器视觉\day1\copy.avi',fourcc,fps,size)

# 笔记本摄像头是否被打开 且 摄像头视频含有的帧数大于0
while (capture.isOpened()):
    retval,frame = capture.read()
    # 如果读取到图像
    if retval == True:
        output.write(frame)
    else:
        break

        
# 释放
video.release()
cv2.destroyAllWindows()

control mouse

OpenCVAllows us to respond to mouse actions on the window

  • setMouseCallback(winname,callback,userdata): winnameIt is the name of the window, callbackit is the callback function, and userdatait is the parameter for the callback function
  • callback(event,x,y,flags,userdata): The callback function must contain these 5 parameters: eventit is an event (mouse movement, pressing the left button, right button...); xyit means that the mouse is located at the (x, y) coordinate position of the window; flagsit is mainly used for combination keys; it is the userdataabovesetMouseCallbackuserdata

Mouse event Event:Event

EVENT_MOUSEMOVE 0            #滑动
EVENT_LBUTTONDOWN 1          #左键点击
EVENT_RBUTTONDOWN 2          #右键点击
EVENT_MBUTTONDOWN 3          #中键点击
EVENT_LBUTTONUP 4            #左键放开
EVENT_RBUTTONUP 5            #右键放开
EVENT_MBUTTONUP 6            #中键放开
EVENT_LBUTTONDBLCLK 7        #左键双击
EVENT_RBUTTONDBLCLK 8        #右键双击
EVENT_MBUTTONDBLCLK 9        #中键双击

Mouse drag event & keyboard and mouse combined event flags :flags

EVENT_FLAG_LBUTTON 1       #左鍵拖曳  
EVENT_FLAG_RBUTTON 2       #右鍵拖曳  
EVENT_FLAG_MBUTTON 4       #中鍵拖曳  
EVENT_FLAG_CTRLKEY 8       #(8~15)按Ctrl不放事件  
EVENT_FLAG_SHIFTKEY 16     #(16~31)按Shift不放事件  
EVENT_FLAG_ALTKEY 32       #(32~39)按Alt不放事件  
# opencv控制鼠标
import cv2
import numpy as np

# 定义鼠标的回调函数(函数名可以随便取,但是参数必须是五个!)
def mouse_callback(event,x,y,flags,userdata): # event:鼠标事件;xy:鼠标坐标;flags:鼠标的组合操作;userdata:传给用户的数据
    print(event,x,y,flags,userdata)
    
    # 增加功能:按下鼠标右键退出
    if event == 2:
        cv2.destroyAllWindows() # 窗口会闪一下 然后继续出现,其实我们是运行成功了,只不过下方是个死循环,会一直存在
    
# 创建窗口
cv2.namedWindow('mouse',cv2.WINDOW_NORMAL)
cv2.resizeWindow('mouse',640,360) # 宽度(列)和高度(行)

cat = cv2.imread('./cat.jpeg')


# 设置鼠标的回调函数
cv2.setMouseCallback('mouse',mouse_callback,'123') # '123'为用户数据,会传到上方的参数userdata中
    # 在我们生成的mouse的窗口上,做任何鼠标的操作,它都会去执行我们定义的mouse_callback()函数

# 生成一个全黑的图片(先行后列——> 要和上面反过来)
img = np.zeros((360,640,3),np.uint8) # np.zeros()生成全是0的图片  np.uint8表示0-255 u表示无符号

# 循环展示图片
while True:
#     cv2.imshow('mouse',img) # 展示刚才生成的全黑图片
    cv2.imshow('mouse',cat) # 展示猫
    key = cv2.waitKey(1)
    
    if key == ord('q') or key == ord('Q'):
        break
        
cv2.destroyAllWindows()
    



TrackBar control

TrackBar is a draggable control that can be used to control RGB

Now we create a TrackBar to adjust RGB , use the adjusted value to generate a picture, and change the color of the picture at any time by dragging it to the TrackBar

  • cv2.createTrackbar(trackbarName, windowName, value, count, onChange)Create a trackbar control: the default value of the trackbar (the position of the cursor at the beginning), the valuemaximum and minimum values ​​of the bar (two values), and a callback function. Every time this value is modified, it will jump into this functioncoutonChange
  • cv2.getTrackbarPos(trackbarName, windowName): Get the value of the current TrackBar
# trackbar的使用
import cv2
import numpy as np

# 创建窗口
cv2.namedWindow('trackbar',cv2.WINDOW_NORMAL)
cv2.resizeWindow('trackbar',640,480)

# 定义回调函数 ——> 我们用这个函数来打印当前的值
def callback(value):
    print(value)
    
# 创建3个trackbar
cv2.createTrackbar('R','trackbar',0,255,callback)
cv2.createTrackbar('G','trackbar',0,255,callback)
cv2.createTrackbar('B','trackbar',0,255,callback)

# 创建一个背景图片
img = np.zeros((480,640,3),np.uint8)

# 不停地循环展示图片,读取数据
while True:
    # 获取当前trackbar的值
    r = cv2.getTrackbarPos('R','trackbar')
    g = cv2.getTrackbarPos('G','trackbar')    
    b = cv2.getTrackbarPos('B','trackbar')    
    
    # 用获取到的三个值修改背景图片颜色
    img[:] = [b , g , r] # opencv里的图片颜色通道就是BGR 
    
    # 展示图片
    cv2.imshow('trackbar',img)
    
    # 退出
    key = cv2.waitKey(1)
    if key == ord('q') or key == ord('Q'):
        break
        
# 释放空间
cv2.destroyAllWindows()

result:
insert image description here

Guess you like

Origin blog.csdn.net/m0_59466249/article/details/125452030