天天看點

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