图像、视频读取显示及操作

import cv2 as cv
import numpy as np

# 显示图像
def image_io_demo():
    image = cv.imread("001.jpg")                # BGR
    h, w, c = image.shape
    print(h, w, c)                              #长、宽、颜色通道(1080 1920 3)
    cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
    cv.imshow("input", image)                   # 显示原图
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)# 转换为灰度
    print(gray.shape)                           # 1080 1920
    cv.imshow("gray", gray)
    cv.imwrite("002.jpg", gray)                 # 创建新图
    cv.waitKey(0)
    cv.destroyAllWindows()
# 视频播放
def video_io_demo():
    cap = cv.VideoCapture("1.mp4")              #获取视频或者摄像头(参数0、1)
    while True:
        ret, frame = cap.read()                 #按帧读取视频
        if ret is not True:
            break
        cv.imshow("frame", frame)
        c = cv.waitKey(10)
        if c == 27:
            break
    cap.release()                               #释放资源
# 图像数据相关操作
def basic_ops_demo():
    image = cv.imread("001.jpg")  # BGR
    cv.imshow("input", image)
    h, w, c = image.shape                               #(1080 1920 3)
    print(h, w, c)                                      
    mv = cv.split(image)
    blob = cv.resize(image, (300, 300))                 #改变图像大小为(300,300,3)
    print(blob.shape) # HWC
    image_blob = blob.transpose(2, 0, 1)                #变换 HWC->CHW (1, 3, 300, 300)
    print(image_blob.shape)
    image_blob = np.expand_dims(image_blob, 0)          #增加维数(1, 3, 300, 300)
    print(image_blob.shape)
    cv.imshow("blob", blob)
    cv.waitKey(0)
    cv.destroyAllWindows()

    a = np.array([1, 2,3, 4, 5, 6, 9, 88, 0, 12, 14, 5, 6])
    index = np.argmax(a)                               #x轴最大索引
    print(a[index])
    for row in range(h):
        for col in range(w):
            b, g, r = image[row, col]
            print(b, g, r)                              #获取bgr颜色值
if __name__ == "__main__":

    basic_ops_demo()
posted @ 2022-02-23 10:41  wuyuan2011woaini  阅读(45)  评论(0编辑  收藏  举报