File size: 6,293 Bytes
327b68f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#coding=utf-8
import os
import cv2  # OpenCV 라이브러리
import numpy as np
from PIL import Image


# -- IO utils
# ν…μŠ€νŠΈ 라인 뢈러였기
def read_txt_lines(filepath):
    # 파일이 μžˆλŠ”μ§€ 확인, μ—†μœΌλ©΄ AssertionError λ©”μ‹œμ§€λ₯Ό 띄움
    assert os.path.isfile( filepath ), "Error when trying to read txt file, path does not exist: {}".format(filepath)  # μ›ν•˜λŠ” 쑰건의 λ³€μˆ˜κ°’μ„ λ³΄μ¦ν•˜κΈ° μœ„ν•΄ μ‚¬μš©
    
    # 파일 뢈러였기
    with open( filepath ) as myfile:
        content = myfile.read().splitlines()  # λ¬Έμžμ—΄μ„ '\n' κΈ°μ€€μœΌλ‘œ μͺΌκ°  ν›„ list 생성
    return content


# npz μ €μž₯
def save2npz(filename, data=None):
    # 데이터가 λΉ„μ–΄μžˆλŠ”μ§€ 확인, μ—†μœΌλ©΄ AssertionError λ©”μ‹œμ§€λ₯Ό 띄움               
    assert data is not None, "data is {}".format(data)          
    
    # 파일 없을 경우                 
    if not os.path.exists(os.path.dirname(filename)):                            
        os.makedirs(os.path.dirname(filename))  # 디렉토리 생성
    np.savez_compressed(filename, data=data)  # μ••μΆ•λ˜μ§€ μ•Šμ€ .npz 파일 ν˜•μ‹ 으둜 μ—¬λŸ¬ λ°°μ—΄ μ €μž₯
def save2npz(filename, data=None):
    """save2npz.
    :param filename: str, the fileanme where the data will be saved.
    :param data: ndarray, arrays to save to the file.
    """
    assert data is not None, "data is {}".format(data)
    if not os.path.exists(os.path.dirname(filename)):
        os.makedirs(os.path.dirname(filename))
    np.savez_compressed(filename, data=data)

# λΉ„λ””μ˜€ 뢈러였기
def read_video(filename):
    cap = cv2.VideoCapture(filename)  # μ˜μƒ 객체(파일) κ°€μ Έμ˜€κΈ°

    while(cap.isOpened()):  # μ˜μƒ 파일(카메라)이 μ •μƒμ μœΌλ‘œ μ—΄λ ΈλŠ”μ§€(μ΄ˆκΈ°ν™”λ˜μ—ˆλŠ”μ§€) μ—¬λΆ€  
        # ret: μ •μƒμ μœΌλ‘œ μ½μ–΄μ™”λŠ”κ°€?
        # frame: ν•œ μž₯의 이미지(frame) κ°€μ Έμ˜€κΈ°
        ret, frame = cap.read() # BGR                                            
        if ret:  # ν”„λ ˆμž„ 정보λ₯Ό μ •μƒμ μœΌλ‘œ 읽지 λͺ»ν•˜λ©΄                                                                  
            yield frame  # ν”„λ ˆμž„μ„ ν•¨μˆ˜ λ°”κΉ₯으둜 μ „λ‹¬ν•˜λ©΄μ„œ μ½”λ“œ 싀행을 ν•¨μˆ˜ λ°”κΉ₯에 양보                                                        
        else:  # ν”„λ ˆμž„ 정보λ₯Ό μ •μƒμ μœΌλ‘œ 읽지 λͺ»ν•˜λ©΄                                                                    
            break  # while λΉ μ Έλ‚˜κ°€κΈ°                                                                 
    cap.release()  # μ˜μƒ 파일(카메라) μ‚¬μš© μ’…λ£Œ
    


# Video 정보 κ°€μ Έμ˜€κΈ°
def get_video_info(infilename, is_print=False):
    cap = cv2.VideoCapture(infilename)
    if not cap.isOpened():
        print("could not open : ", infilename)
        cap.release()
        exit(0)
    
    length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    cap.release()
    
    if is_print:
        print('length : ', length)
        print('width : ', width)
        print('height : ', height)
        print('fps : ', fps)
        
    video_info = {
        'length': length,
        'width': width,
        'height': height,
        'fps': fps,
    }
    
    return video_info

# Video -> Numpy
# μ°Έκ³  κΉƒν—ˆλΈŒ μ½”λ“œ: https://github.com/khazit/Lip2Word/blob/master/lipReader.py#L22
def videoToArray(video_pathname, is_gray=True) :
    
    cap = cv2.VideoCapture(video_pathname)  # μ˜μƒ 객체(파일) κ°€μ Έμ˜€κΈ°
    
    # μ˜μƒ 파일(카메라)이 μ •μƒμ μœΌλ‘œ 열리지 μ•Šμ€ 경우
    if not cap.isOpened():
        print("could not open : ", video_pathname)
        cap.release()  # μ˜μƒ 파일(카메라) μ‚¬μš© μ’…λ£Œ
        exit(0)  # λΉ μ Έλ‚˜κ°€κΈ°
    
    n_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))  # μ˜μƒ ν”„λ ˆμž„ 개수
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))  # μ˜μƒ λ„ˆλΉ„
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))  # μ˜μƒ 높이
    fps = cap.get(cv2.CAP_PROP_FPS)  # μ˜μƒ FPS(Frames Per Second)
    
    if is_gray:
        video = np.zeros((n_frames, height, width))  # gray
    else:
        n_channels=3
        video = np.zeros((n_frames, height, width, n_channels))  # color
        
    video = video.astype(np.uint8)
    
    i = 0
    while True :
        success, frame = cap.read()
        if not success :
            break
        else :
            # gray scale 적용
            if is_gray:
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                
            video[i] = frame
            i += 1
            
    cap.release()  # μ˜μƒ 파일(카메라) μ‚¬μš© μ’…λ£Œ
    
    return video  # μ˜μƒ 정보 μ•žμ— μ˜μƒ ν”„λ ˆμž„ 개수λ₯Ό μΆ”κ°€ν•œ numpy λ°˜ν™˜


# Frame Sampling (ν”„λ ˆμž„ 개수 λ§žμΆ”κΈ°)
# μ°Έκ³  κΉƒν—ˆλΈŒ μ½”λ“œ: https://github.com/khazit/Lip2Word/blob/master/lipReader.py#L62
def frameAdjust(video, target_frames=29):
    n_frames = video.shape[0]  # μ˜μƒ ν”„λ ˆμž„ 개수
    
    if target_frames == n_frames :
        return video  # μ˜μƒ κ·ΈλŒ€λ‘œ λ°˜ν™˜
    else :
        # μ˜μƒ ν”„λ ˆμž„ 개수 > μ›ν•˜λŠ” ν”„λ ˆμž„ 개수
        if n_frames > target_frames :
            idx = np.linspace(0, n_frames-1, target_frames)  # 숫자 μ‹œν€€μŠ€ 생성 # ꡬ간 μ‹œμž‘μ , ꡬ간 끝점, ꡬ간 λ‚΄ 숫자 개수
            idx = np.around(idx, 0).astype(np.int32)  # λ°˜μ˜¬λ¦Όν•˜κ³  dtype 을 μ •μˆ˜λ‘œ λ³€κ²½
            return video[idx]  # μ›ν•˜λŠ” ν”„λ ˆμž„ 개수둜 sampling ν•œ μ˜μƒ
        # μ˜μƒ ν”„λ ˆμž„ 개수 < μ›ν•˜λŠ” ν”„λ ˆμž„ 개수
        else :
            output_video = np.zeros((target_frames, *video.shape[1:])).astype(np.uint8)  # μ›ν•˜λŠ” ν”„λ ˆμž„ κ°œμˆ˜μ— λ§žμΆ°μ„œ 0으둜 μ΄ˆκΈ°ν™”ν•œ numpy 생성
            output_video[:n_frames] = video  # μ˜μƒ ν”„λ ˆμž„ κ°œμˆ˜κΉŒμ§€ κ·ΈλŒ€λ‘œ μ˜μƒ 정보 μ €μž₯
            
            # μ›ν•˜λŠ” ν”„λ ˆμž„ 개수만큼 λ§ˆμ§€λ§‰ ν”„λ ˆμž„ 볡제
            for i in range(target_frames-n_frames+1) :
                output_video[i+n_frames-1] = output_video[n_frames-1]
                
            return output_video  # μ›ν•˜λŠ” ν”„λ ˆμž„ 개수둜 sampling ν•œ μ˜μƒ