天天看点

python和OpenCV获取和改变图片的尺寸并处理视频

1.Python3+OpenCV中的shape命令获取图片的高度、宽度、深度

import cv2
fn="1.jpg"
img = cv2.imread(fn)
[height,width,pixels] = img.shape
print(height,width,pixels)
           

参考:https://blog.csdn.net/qq_15505637/article/details/78539240

2.Python3+OpenCV中的 cv2.resize(源文件,目标,变换方法)将图片变换为想要的尺寸

#如:要将一个图片变为32*32大小的
 import cv2
 image=cv2.imread('test.jpg')
 res=cv2.resize(image,(32,32),interpolation=cv2.INTER_CUBIC)
 cv2.imshow('iker',res)
 cv2.imshow('image',image)
 cv2.waitKey(0)
 cv2.destoryAllWindows()
           

参考:https://blog.csdn.net/oppo62258801/article/details/70144735

3.Python3+OpenCV在视频文件中画框并将视频按比例缩放

# -*- coding: utf-8 -*-
import cv2
cap = cv2.VideoCapture(r'./1.mp4')#读取视频文件
color = (0, 255, 0)#框的颜色规定为绿色
while cap.isOpened():
    ok, frame = cap.read()  # 读取一帧数据
    if not ok:#如果读取失败,直接break
        break
    x, y, w, h = [100, 200, 100, 200]#方框大小,可通过深度学习模型来确定方框位置
    cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)#在每一帧上画方框
    [height,width,pixels]= frame.shape #获取图片大小
    # print(height,width,pixels)
    new_img = cv2.resize(frame, (int(width/3), int(height/3)), interpolation=cv2.INTER_CUBIC)#缩小图像
    cv2.imshow("new_video", new_img)# 显示图像
    c = cv2.waitKey(25)	#每秒播放的帧数,数值越小帧频越快,只能为整数,不可为浮点数
    if c & 0xFF == ord('q'):#键盘输入英文字母q键退出视频
        break
cap.release()# 释放摄像头或视频文件
cv2.destroyAllWindows()#销毁所有窗口
           

参考:https://blog.csdn.net/sinat_28584777/article/details/86708208