cv_module.py 11.0 KB
Newer Older
W
wuzewu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# coding:utf-8
# Copyright (c) 2020  PaddlePaddle Authors. All Rights Reserved.
#
# 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.

H
haoyuying 已提交
16 17
import time
import os
18
from typing import List
H
haoyuying 已提交
19
from collections import OrderedDict
20

W
wuzewu 已提交
21 22
import numpy as np
import paddle
H
haoyuying 已提交
23
import paddle.nn as nn
24
import paddle.nn.functional as F
H
haoyuying 已提交
25
from PIL import Image
W
wuzewu 已提交
26 27 28

from paddlehub.module.module import serving, RunModule
from paddlehub.utils.utils import base64_to_cv2
H
haoyuying 已提交
29
from paddlehub.process.transforms import ConvertColorSpace, ColorPostprocess, Resize, BoxTool
W
wuzewu 已提交
30 31 32 33


class ImageServing(object):
    @serving
34
    def serving_method(self, images: List[str], **kwargs) -> List[dict]:
W
wuzewu 已提交
35 36 37 38 39 40 41
        """Run as a service."""
        images_decode = [base64_to_cv2(image) for image in images]
        results = self.predict(images=images_decode, **kwargs)
        return results


class ImageClassifierModule(RunModule, ImageServing):
42 43 44 45 46
    def training_step(self, batch: int, batch_idx: int) -> dict:
        '''
        One step for training, which should be called as forward computation.

        Args:
W
wuzewu 已提交
47 48
            batch(list[paddle.Tensor]) : The one batch data, which contains images and labels.
            batch_idx(int) : The index of batch.
49 50 51 52

        Returns:
            results(dict) : The model outputs, such as loss and metrics.
        '''
W
wuzewu 已提交
53 54
        return self.validation_step(batch, batch_idx)

55 56 57 58 59
    def validation_step(self, batch: int, batch_idx: int) -> dict:
        '''
        One step for validation, which should be called as forward computation.

        Args:
W
wuzewu 已提交
60 61
            batch(list[paddle.Tensor]) : The one batch data, which contains images and labels.
            batch_idx(int) : The index of batch.
62 63 64 65

        Returns:
            results(dict) : The model outputs, such as metrics.
        '''
W
wuzewu 已提交
66
        images = batch[0]
67
        labels = paddle.unsqueeze(batch[1], axis=-1)
W
wuzewu 已提交
68 69

        preds = self(images)
70 71 72
        loss, _ = F.softmax_with_cross_entropy(preds, labels, return_softmax=True, axis=1)
        loss = paddle.mean(loss)
        acc = paddle.metric.accuracy(preds, labels)
W
wuzewu 已提交
73 74
        return {'loss': loss, 'metrics': {'acc': acc}}

75 76 77 78 79 80 81 82 83 84 85
    def predict(self, images: List[np.ndarray], top_k: int = 1) -> List[dict]:
        '''
        Predict images

        Args:
            images(list[numpy.ndarray]) : Images to be predicted, consist of np.ndarray in bgr format.
            top_k(int) : Output top k result of each image.

        Returns:
            results(list[dict]) : The prediction result of each input image
        '''
W
wuzewu 已提交
86 87 88
        images = self.transforms(images)
        if len(images.shape) == 3:
            images = images[np.newaxis, :]
W
wuzewu 已提交
89
        preds = self(paddle.to_tensor(images))
90
        preds = F.softmax(preds, axis=1).numpy()
W
wuzewu 已提交
91 92 93 94 95 96 97 98 99
        pred_idxs = np.argsort(preds)[::-1][:, :top_k]
        res = []
        for i, pred in enumerate(pred_idxs):
            res_dict = {}
            for k in pred:
                class_name = self.labels[int(k)]
                res_dict[class_name] = preds[i][k]
            res.append(res_dict)
        return res
H
haoyuying 已提交
100 101 102 103 104 105


class ImageColorizeModule(RunModule, ImageServing):
    def training_step(self, batch: int, batch_idx: int) -> dict:
        '''
        One step for training, which should be called as forward computation.
H
haoyuying 已提交
106

H
haoyuying 已提交
107 108 109
        Args:
            batch(list[paddle.Tensor]): The one batch data, which contains images and labels.
            batch_idx(int): The index of batch.
H
haoyuying 已提交
110

H
haoyuying 已提交
111 112 113 114 115 116 117 118
        Returns:
            results(dict) : The model outputs, such as loss and metrics.
        '''
        return self.validation_step(batch, batch_idx)

    def validation_step(self, batch: int, batch_idx: int) -> dict:
        '''
        One step for validation, which should be called as forward computation.
H
haoyuying 已提交
119

H
haoyuying 已提交
120 121 122
        Args:
            batch(list[paddle.Tensor]): The one batch data, which contains images and labels.
            batch_idx(int): The index of batch.
H
haoyuying 已提交
123

H
haoyuying 已提交
124 125 126 127
        Returns:
            results(dict) : The model outputs, such as metrics.
        '''
        out_class, out_reg = self(batch[0], batch[1], batch[2])
H
haoyuying 已提交
128

H
haoyuying 已提交
129 130 131 132 133
        criterionCE = nn.loss.CrossEntropyLoss()
        loss_ce = criterionCE(out_class, batch[4][:, 0, :, :])
        loss_G_L1_reg = paddle.sum(paddle.abs(batch[3] - out_reg), axis=1, keepdim=True)
        loss_G_L1_reg = paddle.mean(loss_G_L1_reg)
        loss = loss_ce + loss_G_L1_reg
H
haoyuying 已提交
134

H
haoyuying 已提交
135 136 137 138 139 140 141 142 143
        visual_ret = OrderedDict()
        psnrs = []
        lab2rgb = ConvertColorSpace(mode='LAB2RGB')
        process = ColorPostprocess()
        for i in range(batch[0].numpy().shape[0]):
            real = lab2rgb(np.concatenate((batch[0].numpy(), batch[3].numpy()), axis=1))[i]
            visual_ret['real'] = process(real)
            fake = lab2rgb(np.concatenate((batch[0].numpy(), out_reg.numpy()), axis=1))[i]
            visual_ret['fake_reg'] = process(fake)
H
haoyuying 已提交
144
            mse = np.mean((visual_ret['real'] * 1.0 - visual_ret['fake_reg'] * 1.0)**2)
H
haoyuying 已提交
145 146 147 148 149 150 151 152
            psnr_value = 20 * np.log10(255. / np.sqrt(mse))
            psnrs.append(psnr_value)
        psnr = paddle.to_variable(np.array(psnrs))
        return {'loss': loss, 'metrics': {'psnr': psnr}}

    def predict(self, images: str, visualization: bool = True, save_path: str = 'result'):
        '''
        Colorize images
H
haoyuying 已提交
153

H
haoyuying 已提交
154 155 156 157
        Args:
            images(str) : Images path to be colorized.
            visualization(bool): Whether to save colorized images.
            save_path(str) : Path to save colorized images.
H
haoyuying 已提交
158

H
haoyuying 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
        Returns:
            results(list[dict]) : The prediction result of each input image
        '''
        lab2rgb = ConvertColorSpace(mode='LAB2RGB')
        process = ColorPostprocess()
        resize = Resize((256, 256))
        visual_ret = OrderedDict()
        im = self.transforms(images, is_train=False)
        out_class, out_reg = self(paddle.to_tensor(im['A']), paddle.to_variable(im['hint_B']),
                                  paddle.to_variable(im['mask_B']))
        result = []

        for i in range(im['A'].shape[0]):
            gray = lab2rgb(np.concatenate((im['A'], np.zeros(im['B'].shape)), axis=1))[i]
            visual_ret['gray'] = resize(process(gray))
            hint = lab2rgb(np.concatenate((im['A'], im['hint_B']), axis=1))[i]
            visual_ret['hint'] = resize(process(hint))
            real = lab2rgb(np.concatenate((im['A'], im['B']), axis=1))[i]
            visual_ret['real'] = resize(process(real))
            fake = lab2rgb(np.concatenate((im['A'], out_reg.numpy()), axis=1))[i]
            visual_ret['fake_reg'] = resize(process(fake))
H
haoyuying 已提交
180

H
haoyuying 已提交
181 182 183 184 185 186 187
            if visualization:
                fake_name = "fake_" + str(time.time()) + ".png"
                if not os.path.exists(save_path):
                    os.mkdir(save_path)
                fake_path = os.path.join(save_path, fake_name)
                visual_gray = Image.fromarray(visual_ret['fake_reg'])
                visual_gray.save(fake_path)
H
haoyuying 已提交
188 189

            mse = np.mean((visual_ret['real'] * 1.0 - visual_ret['fake_reg'] * 1.0)**2)
H
haoyuying 已提交
190 191 192
            psnr_value = 20 * np.log10(255. / np.sqrt(mse))
            result.append(visual_ret)
        return result
H
haoyuying 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288


class Yolov3Module(RunModule, ImageServing):
    def training_step(self, batch: int, batch_idx: int) -> dict:
        '''
        One step for training, which should be called as forward computation.

        Args:
            batch(list[paddle.Tensor]): The one batch data, which contains images, ground truth boxes, labels and scores.
            batch_idx(int): The index of batch.

        Returns:
            results(dict): The model outputs, such as loss.
        '''

        return self.validation_step(batch, batch_idx)

    def validation_step(self, batch: int, batch_idx: int) -> dict:
        '''
        One step for validation, which should be called as forward computation.

        Args:
            batch(list[paddle.Tensor]): The one batch data, which contains images, ground truth boxes, labels and scores.
            batch_idx(int): The index of batch.

        Returns:
            results(dict) : The model outputs, such as metrics.
        '''
        ious = []
        boxtool = BoxTool()
        img = batch[0].astype('float32')
        B, C, W, H = img.shape
        im_shape = np.array([(W, H)] * B).astype('int32')
        im_shape = paddle.to_tensor(im_shape)

        gt_box = batch[1].astype('float32')
        gt_label = batch[2].astype('int32')
        gt_score = batch[3].astype("float32")
        loss, pred = self(img, gt_box, gt_label, gt_score, im_shape)

        for i in range(len(pred)):
            bboxes = pred[i].numpy()
            labels = bboxes[:, 0].astype('int32')
            scores = bboxes[:, 1].astype('float32')
            boxes = bboxes[:, 2:].astype('float32')
            iou = []

            for j, (box, score, label) in enumerate(zip(boxes, scores, labels)):
                x1, y1, x2, y2 = box
                w = x2 - x1 + 1
                h = y2 - y1 + 1
                bbox = [x1, y1, w, h]
                bbox = np.expand_dims(boxtool.coco_anno_box_to_center_relative(bbox, H, W), 0)
                gt = gt_box[i].numpy()
                iou.append(max(boxtool.box_iou_xywh(bbox, gt)))

            ious.append(max(iou))
        ious = paddle.to_tensor(np.array(ious))

        return {'loss': loss, 'metrics': {'iou': ious}}

    def predict(self, imgpath: str, filelist: str, visualization: bool = True, save_path: str = 'result'):
        '''
        Detect images

        Args:
            imgpath(str): Image path .
            filelist(str): Path to get label name.
            visualization(bool): Whether to save result image.
            save_path(str) : Path to save detected images.

        Returns:
            boxes(np.ndarray): Predict box information.
            scores(np.ndarray): Predict score.
            labels(np.ndarray): Predict labels.
        '''
        boxtool = BoxTool()
        img = {}
        img['image'] = imgpath
        img['id'] = 0
        im, im_id, im_shape = self.transform(img, 416)
        label_names = self.get_label_infos(filelist)
        img_data = np.array([im]).astype('float32')
        img_data = paddle.to_tensor(img_data)
        im_shape = np.array([im_shape]).astype('int32')
        im_shape = paddle.to_tensor(im_shape)

        output, pred = self(img_data, None, None, None, im_shape)

        for i in range(len(pred)):
            bboxes = pred[i].numpy()
            labels = bboxes[:, 0].astype('int32')
            scores = bboxes[:, 1].astype('float32')
            boxes = bboxes[:, 2:].astype('float32')

            if visualization:
H
haoyuying 已提交
289 290
                if not os.path.exists(save_path):
                    os.mkdir(save_path)
H
haoyuying 已提交
291 292 293
                boxtool.draw_boxes_on_image(imgpath, boxes, scores, labels, label_names, 0.5)

        return boxes, scores, labels