predict.py 6.1 KB
Newer Older
L
LielinJiang 已提交
1
#  Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
L
lijianshe02 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.

import os
import sys
L
LielinJiang 已提交
17 18 19 20

cur_path = os.path.abspath(os.path.dirname(__file__))
sys.path.append(cur_path)

L
lijianshe02 已提交
21 22 23
import time
import argparse
import ast
L
LielinJiang 已提交
24
import glob
L
lijianshe02 已提交
25
import numpy as np
L
LielinJiang 已提交
26

L
lijianshe02 已提交
27 28 29
import paddle.fluid as fluid
import cv2

L
LielinJiang 已提交
30 31
from data import EDVRDataset
from paddle.incubate.hapi.download import get_path_from_url
L
lijianshe02 已提交
32

L
LielinJiang 已提交
33
EDVR_weight_url = 'https://paddlegan.bj.bcebos.com/applications/edvr_infer_model.tar'
L
lijianshe02 已提交
34 35 36 37

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
L
LielinJiang 已提交
38
        '--input',
L
lijianshe02 已提交
39 40
        type=str,
        default=None,
L
LielinJiang 已提交
41
        help='input video path')
L
lijianshe02 已提交
42
    parser.add_argument(
L
LielinJiang 已提交
43
        '--output',
L
lijianshe02 已提交
44
        type=str,
L
LielinJiang 已提交
45 46
        default='output',
        help='output path')
L
lijianshe02 已提交
47
    parser.add_argument(
L
LielinJiang 已提交
48
        '--weight_path',
L
lijianshe02 已提交
49 50
        type=str,
        default=None,
L
LielinJiang 已提交
51
        help='weight path')
L
lijianshe02 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    args = parser.parse_args()
    return args

def get_img(pred):
    print('pred shape', pred.shape)
    pred = pred.squeeze()
    pred = np.clip(pred, a_min=0., a_max=1.0)
    pred = pred * 255
    pred = pred.round()
    pred = pred.astype('uint8')
    pred = np.transpose(pred, (1, 2, 0)) # chw -> hwc
    pred = pred[:, :, ::-1] # rgb -> bgr
    return pred

def save_img(img, framename):
L
LielinJiang 已提交
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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    dirname = os.path.dirname(framename)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    cv2.imwrite(framename, img)


def dump_frames_ffmpeg(vid_path, outpath, r=None, ss=None, t=None):
    ffmpeg = ['ffmpeg ', ' -loglevel ', ' error ']
    vid_name = vid_path.split('/')[-1].split('.')[0]
    out_full_path = os.path.join(outpath, 'frames_input')

    if not os.path.exists(out_full_path):
        os.makedirs(out_full_path)

    # video file name
    outformat = out_full_path + '/%08d.png'

    if ss is not None and t is not None and r is not None:
        cmd = ffmpeg + [
            ' -ss ',
            ss,
            ' -t ',
            t,
            ' -i ',
            vid_path,
            ' -r ',
            r,
            ' -qscale:v ',
            ' 0.1 ',
            ' -start_number ',
            ' 0 ',
            outformat
        ]
    else:
        cmd = ffmpeg + [' -i ', vid_path, ' -start_number ', ' 0 ', outformat]

    cmd = ''.join(cmd)
    print(cmd)
    if os.system(cmd) == 0:
        print('Video: {} done'.format(vid_name))
    else:
        print('Video: {} error'.format(vid_name))
    print('')
    sys.stdout.flush()
    return out_full_path


def frames_to_video_ffmpeg(framepath, videopath, r):
    ffmpeg = ['ffmpeg ', ' -loglevel ', ' error ']
    cmd = ffmpeg + [
        ' -r ', r, ' -f ', ' image2 ', ' -i ', framepath, ' -vcodec ',
        ' libx264 ', ' -pix_fmt ', ' yuv420p ', ' -crf ', ' 16 ', videopath
    ]
    cmd = ''.join(cmd)
    print(cmd)

    if os.system(cmd) == 0:
        print('Video: {} done'.format(videopath))
    else:
        print('Video: {} error'.format(videopath))
    print('')
    sys.stdout.flush()


class EDVRPredictor:
    def __init__(self, input, output, weight_path=None):
        self.input = input
        self.output = os.path.join(output, 'EDVR')

        place = fluid.CUDAPlace(0) if fluid.is_compiled_with_cuda() else fluid.CPUPlace()
        self.exe = fluid.Executor(place)

        if weight_path is None:
            weight_path = get_path_from_url(EDVR_weight_url, cur_path)
        
        print(weight_path)

        model_filename = 'EDVR_model.pdmodel'
        params_filename = 'EDVR_params.pdparams'
        
        out = fluid.io.load_inference_model(dirname=weight_path, 
                                            model_filename=model_filename, 
                                            params_filename=params_filename, 
                                            executor=self.exe)
        self.infer_prog, self.feed_list, self.fetch_list = out

    def run(self):
        vid = self.input
        base_name = os.path.basename(vid).split('.')[0]
        output_path = os.path.join(self.output, base_name)
        pred_frame_path = os.path.join(output_path, 'frames_pred')

        if not os.path.exists(output_path):
            os.makedirs(output_path)

        if not os.path.exists(pred_frame_path):
            os.makedirs(pred_frame_path)

        cap = cv2.VideoCapture(vid)
        fps = cap.get(cv2.CAP_PROP_FPS)

        out_path = dump_frames_ffmpeg(vid, output_path)

        frames = sorted(glob.glob(os.path.join(out_path, '*.png')))

        dataset = EDVRDataset(frames)

        periods = []
L
lijianshe02 已提交
176
        cur_time = time.time()
L
LielinJiang 已提交
177 178 179 180 181 182 183
        for infer_iter, data in enumerate(dataset):
            data_feed_in = [data[0]]
            
            infer_outs = self.exe.run(self.infer_prog,
                                fetch_list=self.fetch_list,
                                feed={self.feed_list[0]:np.array(data_feed_in)})
            infer_result_list = [item for item in infer_outs]
L
lijianshe02 已提交
184

L
LielinJiang 已提交
185 186 187 188
            frame_path = data[1]
            
            img_i = get_img(infer_result_list[0])
            save_img(img_i, os.path.join(pred_frame_path, os.path.basename(frame_path)))                   
L
lijianshe02 已提交
189

L
LielinJiang 已提交
190 191 192 193
            prev_time = cur_time
            cur_time = time.time()
            period = cur_time - prev_time
            periods.append(period)
L
lijianshe02 已提交
194

L
LielinJiang 已提交
195 196 197 198
            print('Processed {} samples'.format(infer_iter + 1))
        frame_pattern_combined = os.path.join(pred_frame_path, '%08d.png')
        vid_out_path = os.path.join(self.output, '{}_edvr_out.mp4'.format(base_name))
        frames_to_video_ffmpeg(frame_pattern_combined, vid_out_path, str(int(fps)))
L
lijianshe02 已提交
199

L
LielinJiang 已提交
200
        return frame_pattern_combined, vid_out_path
L
lijianshe02 已提交
201 202 203


if __name__ == "__main__":
L
LielinJiang 已提交
204 205
    predictor = EDVRPredictor(args.input, args.output, args.weight_path)
    predictor.run()
L
lijianshe02 已提交
206