realsr_predictor.py 3.8 KB
Newer Older
L
LielinJiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#  Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
#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.
L
LielinJiang 已提交
14

L
LielinJiang 已提交
15
import os
L
LielinJiang 已提交
16 17 18 19 20
import cv2
import glob
import numpy as np
from PIL import Image
from tqdm import tqdm
L
LielinJiang 已提交
21

L
LielinJiang 已提交
22
import paddle
L
LielinJiang 已提交
23 24
from ppgan.models.generators import RRDBNet
from ppgan.utils.video import frames2video, video2frames
L
LielinJiang 已提交
25
from ppgan.utils.download import get_path_from_url
L
LielinJiang 已提交
26
from .base_predictor import BasePredictor
L
LielinJiang 已提交
27

L
LielinJiang 已提交
28
REALSR_WEIGHT_URL = 'https://paddlegan.bj.bcebos.com/applications/DF2K_JPEG.pdparams'
L
LielinJiang 已提交
29 30


L
LielinJiang 已提交
31 32
class RealSRPredictor(BasePredictor):
    def __init__(self, output='output', weight_path=None):
L
LielinJiang 已提交
33 34 35 36
        self.input = input
        self.output = os.path.join(output, 'RealSR')
        self.model = RRDBNet(3, 3, 64, 23)
        if weight_path is None:
L
LielinJiang 已提交
37
            weight_path = get_path_from_url(REALSR_WEIGHT_URL)
L
LielinJiang 已提交
38

L
LielinJiang 已提交
39
        state_dict = paddle.load(weight_path)
L
LielinJiang 已提交
40 41 42 43 44 45 46 47 48 49 50
        self.model.load_dict(state_dict)
        self.model.eval()

    def norm(self, img):
        img = np.array(img).transpose([2, 0, 1]).astype('float32') / 255.0
        return img.astype('float32')

    def denorm(self, img):
        img = img.transpose((1, 2, 0))
        return (img * 255).clip(0, 255).astype('uint8')

L
LielinJiang 已提交
51 52 53 54 55 56 57 58
    def run_image(self, img):
        if isinstance(img, str):
            ori_img = Image.open(img).convert('RGB')
        elif isinstance(img, np.ndarray):
            ori_img = Image.fromarray(img).convert('RGB')
        elif isinstance(img, Image.Image):
            ori_img = img

L
LielinJiang 已提交
59 60 61 62 63 64 65 66
        img = self.norm(ori_img)
        x = paddle.to_tensor(img[np.newaxis, ...])
        out = self.model(x)

        pred_img = self.denorm(out.numpy()[0])
        pred_img = Image.fromarray(pred_img)
        return pred_img

L
LielinJiang 已提交
67 68
    def run_video(self, video):
        base_name = os.path.basename(video).split('.')[0]
L
LielinJiang 已提交
69 70 71 72 73 74 75 76 77
        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)

L
LielinJiang 已提交
78
        cap = cv2.VideoCapture(video)
L
LielinJiang 已提交
79 80
        fps = cap.get(cv2.CAP_PROP_FPS)

L
LielinJiang 已提交
81
        out_path = video2frames(video, output_path)
L
LielinJiang 已提交
82 83 84 85

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

        for frame in tqdm(frames):
L
LielinJiang 已提交
86
            pred_img = self.run_image(frame)
L
LielinJiang 已提交
87 88 89 90 91 92 93 94

            frame_name = os.path.basename(frame)
            pred_img.save(os.path.join(pred_frame_path, frame_name))

        frame_pattern_combined = os.path.join(pred_frame_path, '%08d.png')

        vid_out_path = os.path.join(output_path,
                                    '{}_realsr_out.mp4'.format(base_name))
L
LielinJiang 已提交
95
        frames2video(frame_pattern_combined, vid_out_path, str(int(fps)))
L
LielinJiang 已提交
96 97

        return frame_pattern_combined, vid_out_path
L
LielinJiang 已提交
98 99

    def run(self, input):
L
LielinJiang 已提交
100 101 102 103
        if not os.path.exists(self.output):
            os.makedirs(self.output)

        if not self.is_image(input):
L
LielinJiang 已提交
104 105 106 107
            return self.run_video(input)
        else:
            pred_img = self.run_image(input)

L
LielinJiang 已提交
108
            out_path = None
L
LielinJiang 已提交
109
            if self.output:
L
LielinJiang 已提交
110 111 112
                base_name = os.path.splitext(os.path.basename(input))[0]
                out_path = os.path.join(self.output, base_name + '.png')
                pred_img.save(out_path)
L
LielinJiang 已提交
113

L
LielinJiang 已提交
114
            return pred_img, out_path