
#!/usr/bin/env python
# coding: utf-8
# In[22]:
# 导入库
import cv2
from PIL import Image
# In[23]:
# 视频路径
video_path = "C:/Users/koala/Videos/movie.mp4"
video_capture = cv2.VideoCapture(video_path)
ret,frame = video_capture.read()
# 字幕矩阵大小  原视频高度 宽带  及 字幕的高度
subtitle_shape = [frame.shape[0],frame.shape[1],120]
# 时间点
times = [0.5,5,9,10,11,14,17,19,24,26,29,35,37,40,45,49,52,58,60,62,67,71,77,85,90,94,97,99,104,109,115,121,124,127,136,139,141,144]
# 帧数
FPS = video_capture.get(5)
# 截取的图片数组
clip_images = []
# 保持图片的位置
base_path = "D:/subtitle.jpg"
# In[24]:
# 截取视频指定时间感兴趣的区域
def get_key_area(video,times,subtitle_shape):
    # 当前关键帧
    key_frame = 0
    # 当前帧
    current_frame = 0
    while True:
        ret,frame = video.read()
        if ret:
            current_frame += 1
            if key_frame < len(times) and current_frame == times[key_frame]*FPS:
                # 匹配完成 关键帧+1
                key_frame += 1
                clip = frame[subtitle_shape[0]-subtitle_shape[2]:subtitle_shape[0],0:subtitle_shape[1]]
                clip_images.append(clip)
#               cv2.imwrite("D:/" + str(key_frame) + ".jpg",clip)  
        else:
            break
    print("匹配完成 共计图片 数目为:%d "%len(clip_images))
    video.release()
# In[25]:
def main():
    get_key_area(video_capture,times,subtitle_shape)
    # 生成幕布  长高
    subtitle_image = Image.new("RGB",(subtitle_shape[1],subtitle_shape[2]*len(clip_images)))
    for index,item in enumerate(clip_images):
        # 将图片矩阵转化为PIL 的图片对象
        img = Image.fromarray(item)
        # 左上  右下
        subtitle_image.paste(img,box=(0,index*subtitle_shape[2],subtitle_shape[1],subtitle_shape[2]*(index+1)))
    subtitle_image.save(base_path)
    subtitle_image.show()
# In[26]:
if __name__ == '__main__':
    main()
    # print(__name__)
# In[ ]:                
                










