opencv(Python)学习笔记(1)

主要参考该网站进行学习记录:

机器视觉全栈|机器视觉教程|docsify|pytorch官方教程中文版|opencv-python官方教程中文版

1.读取和保存图片

import cv2 as cv
import sys
img = cv.imread(cv.samples.findFile("spe.jpg"))
if img is None:
    sys.exit("Could not read the image.")
cv.namedWindow("Display window", cv.WINDOW_FREERATIO)  # 显示高分辨率的图像时可以自由控制窗口比例
cv.imshow("Display window", img)
k = cv.waitKey(0)
if k == ord("s"):
    cv.imwrite("test.png", img)

在读入图像后,数据将被存储在一个cv::Mat对象中

2.使用摄像头

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)  # 打开电脑的摄像头
print(cap.get(cv.CAP_PROP_FRAME_WIDTH), cap.get(cv.CAP_PROP_FRAME_HEIGHT))  # 读取摄像头成像的分辨率
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)  # 将摄像头读取到的RGB图转换为灰度图
    # 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()

播放本地视频:

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(r'G:\CloudMusic\MV\1.mp4')
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.namedWindow('frame', cv.WINDOW_FREERATIO)
    # cv.imshow('frame', gray)
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break
cap.release()
cv.destroyAllWindows()

保存视频:

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) #上下镜像
    frame = cv.flip(frame, 1)  # 左右镜像
    # 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()

3.绘制图形:

直线:

import numpy as np
import cv2 as cv
# Create a black image
img = np.zeros((512, 512, 3), np.uint8)
# Draw a diagonal blue line with thickness of 5 px