最近需要做動圖,需要從視頻中提取幀圖片並進行裁剪縮放處理。
#-*- coding: utf-8 -*-
#!/usr/bin/python3
from PIL import Image
import os
import cv2
'''
將視頻幀轉換爲圖片
'''
videoPath = '../video.mp4'
frames = cv2.VideoCapture(videoPath)
c = 0
i = 0
timeF = 3
rval=frames.isOpened()
while rval: # 循環讀取視頻幀
c = c + 1
rval, frame = frames.read()
if (c % timeF == 0) and rval: # 每隔timeF幀進行存儲操作
cv2.imwrite(str(i) + '.jpg', frame) # 存儲爲圖像
i = i + 1
frames.release()
'''
# 將圖片指定區域裁剪出來並縮放到指定尺寸保存
'''
list = os.listdir('./')
for i in range(0, len(list)):
path = os.path.join(list[i])
if os.path.isfile(path) and path.endswith('jpg'):
img = Image.open(path)
img = img.crop((160, 145, 1436, 936)) # 裁剪圖片指定區域
out = img.resize((600, 372), Image.ANTIALIAS) # 縮放圖片 抗鋸齒
path = path.replace('.jpg', '.png')
path = 's' + path
out.save(path)