cv_module.py 14.5 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

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

28 29 30
import paddlehub.vision.transforms as T
import paddlehub.vision.functional as Func
from paddlehub.vision import utils
W
wuzewu 已提交
31 32 33 34 35 36
from paddlehub.module.module import serving, RunModule
from paddlehub.utils.utils import base64_to_cv2


class ImageServing(object):
    @serving
37
    def serving_method(self, images: List[str], **kwargs) -> List[dict]:
W
wuzewu 已提交
38 39 40 41 42 43 44
        """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):
45 46 47 48 49
    def training_step(self, batch: int, batch_idx: int) -> dict:
        '''
        One step for training, which should be called as forward computation.

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

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

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

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

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

H
haoyuying 已提交
72 73
        preds, feature = self(images)
        
74 75 76
        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 已提交
77 78
        return {'loss': loss, 'metrics': {'acc': acc}}

79 80 81 82 83 84 85 86 87 88 89
    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 已提交
90 91 92
        images = self.transforms(images)
        if len(images.shape) == 3:
            images = images[np.newaxis, :]
H
haoyuying 已提交
93
        preds, feature = self(paddle.to_tensor(images))
94
        preds = F.softmax(preds, axis=1).numpy()
W
wuzewu 已提交
95 96
        pred_idxs = np.argsort(preds)[::-1][:, :top_k]
        res = []
H
haoyuying 已提交
97

W
wuzewu 已提交
98 99 100 101 102 103 104
        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 已提交
105 106 107 108 109 110


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 已提交
111

H
haoyuying 已提交
112 113 114
        Args:
            batch(list[paddle.Tensor]): The one batch data, which contains images and labels.
            batch_idx(int): The index of batch.
H
haoyuying 已提交
115

H
haoyuying 已提交
116
        Returns:
H
haoyuying 已提交
117
            results(dict): The model outputs, such as loss and metrics.
H
haoyuying 已提交
118 119 120 121 122 123
        '''
        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 已提交
124

H
haoyuying 已提交
125 126 127
        Args:
            batch(list[paddle.Tensor]): The one batch data, which contains images and labels.
            batch_idx(int): The index of batch.
H
haoyuying 已提交
128

H
haoyuying 已提交
129 130 131
        Returns:
            results(dict) : The model outputs, such as metrics.
        '''
H
haoyuying 已提交
132 133
        img = self.preprocess(batch[0])
        out_class, out_reg = self(img['A'], img['hint_B'], img['mask_B'])
H
haoyuying 已提交
134

H
haoyuying 已提交
135
        # loss
H
haoyuying 已提交
136
        criterionCE = nn.loss.CrossEntropyLoss()
H
haoyuying 已提交
137 138
        loss_ce = criterionCE(out_class, img['real_B_enc'][:, 0, :, :])
        loss_G_L1_reg = paddle.sum(paddle.abs(img['B'] - out_reg), axis=1, keepdim=True)
H
haoyuying 已提交
139 140
        loss_G_L1_reg = paddle.mean(loss_G_L1_reg)
        loss = loss_ce + loss_G_L1_reg
H
haoyuying 已提交
141

H
haoyuying 已提交
142
        return {'loss': loss}
H
haoyuying 已提交
143 144 145 146

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

H
haoyuying 已提交
148
        Args:
H
haoyuying 已提交
149
            images(str|np.ndarray) : Images path or BGR image to be colorized.
H
haoyuying 已提交
150 151
            visualization(bool): Whether to save colorized images.
            save_path(str) : Path to save colorized images.
H
haoyuying 已提交
152

H
haoyuying 已提交
153 154 155
        Returns:
            results(list[dict]) : The prediction result of each input image
        '''
156
        self.eval()
H
haoyuying 已提交
157
        lab2rgb = T.LAB2RGB()
W
wuzewu 已提交
158

H
haoyuying 已提交
159 160
        if isinstance(images, str):
            images = cv2.imread(images).astype('float32')
H
haoyuying 已提交
161

H
haoyuying 已提交
162
        im = self.transforms(images)
H
haoyuying 已提交
163 164 165
        im = im[np.newaxis, :, :, :]
        im = self.preprocess(im)
        out_class, out_reg = self(im['A'], im['hint_B'], im['mask_B'])
H
haoyuying 已提交
166

H
haoyuying 已提交
167 168
        result = []
        visual_ret = OrderedDict()
H
haoyuying 已提交
169
        for i in range(im['A'].shape[0]):
H
haoyuying 已提交
170
            gray = lab2rgb(np.concatenate((im['A'].numpy(), np.zeros(im['B'].shape)), axis=1))[i]
H
haoyuying 已提交
171 172
            gray = np.clip(np.transpose(gray, (1, 2, 0)), 0, 1) * 255
            visual_ret['gray'] = gray.astype(np.uint8)
H
haoyuying 已提交
173
            hint = lab2rgb(np.concatenate((im['A'].numpy(), im['hint_B'].numpy()), axis=1))[i]
H
haoyuying 已提交
174 175
            hint = np.clip(np.transpose(hint, (1, 2, 0)), 0, 1) * 255
            visual_ret['hint'] = hint.astype(np.uint8)
H
haoyuying 已提交
176
            real = lab2rgb(np.concatenate((im['A'].numpy(), im['B'].numpy()), axis=1))[i]
H
haoyuying 已提交
177 178
            real = np.clip(np.transpose(real, (1, 2, 0)), 0, 1) * 255
            visual_ret['real'] = real.astype(np.uint8)
H
haoyuying 已提交
179
            fake = lab2rgb(np.concatenate((im['A'].numpy(), out_reg.numpy()), axis=1))[i]
H
haoyuying 已提交
180 181
            fake = np.clip(np.transpose(fake, (1, 2, 0)), 0, 1) * 255
            visual_ret['fake_reg'] = fake.astype(np.uint8)
H
haoyuying 已提交
182

H
haoyuying 已提交
183
            if visualization:
H
haoyuying 已提交
184
                h, w, c = images.shape
H
haoyuying 已提交
185 186 187 188 189
                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'])
H
haoyuying 已提交
190
                visual_gray = visual_gray.resize((w, h), Image.BILINEAR)
H
haoyuying 已提交
191
                visual_gray.save(fake_path)
H
haoyuying 已提交
192

H
haoyuying 已提交
193 194
            result.append(visual_ret)
        return result
H
haoyuying 已提交
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


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.
        '''
        img = batch[0].astype('float32')
224 225 226 227 228 229 230 231 232
        gtbox = batch[1].astype('float32')
        gtlabel = batch[2].astype('int32')
        gtscore = batch[3].astype("float32")
        losses = []
        outputs = self(img)
        self.downsample = 32

        for i, out in enumerate(outputs):
            anchor_mask = self.anchor_masks[i]
233 234 235 236 237 238 239 240 241 242 243
            loss = F.yolov3_loss(
                x=out,
                gt_box=gtbox,
                gt_label=gtlabel,
                gt_score=gtscore,
                anchors=self.anchors,
                anchor_mask=anchor_mask,
                class_num=self.class_num,
                ignore_thresh=self.ignore_thresh,
                downsample_ratio=32,
                use_label_smooth=False)
W
wuzewu 已提交
244
            losses.append(paddle.mean(loss))
245 246 247
            self.downsample //= 2

        return {'loss': sum(losses)}
H
haoyuying 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

    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.
        '''
264
        self.eval()
265 266 267 268
        boxes = []
        scores = []
        self.downsample = 32
        im = self.transform(imgpath)
269
        h, w, c = utils.img_shape(imgpath)
270
        im_shape = paddle.to_tensor(np.array([[h, w]]).astype('int32'))
271
        label_names = utils.get_label_infos(filelist)
272 273 274 275 276 277 278 279 280 281 282
        img_data = paddle.to_tensor(np.array([im]).astype('float32'))

        outputs = self(img_data)

        for i, out in enumerate(outputs):
            anchor_mask = self.anchor_masks[i]
            mask_anchors = []
            for m in anchor_mask:
                mask_anchors.append((self.anchors[2 * m]))
                mask_anchors.append(self.anchors[2 * m + 1])

283 284 285 286 287 288 289 290
            box, score = F.yolo_box(
                x=out,
                img_size=im_shape,
                anchors=mask_anchors,
                class_num=self.class_num,
                conf_thresh=self.valid_thresh,
                downsample_ratio=self.downsample,
                name="yolo_box" + str(i))
291 292 293 294 295 296 297 298

            boxes.append(box)
            scores.append(paddle.transpose(score, perm=[0, 2, 1]))
            self.downsample //= 2

        yolo_boxes = paddle.concat(boxes, axis=1)
        yolo_scores = paddle.concat(scores, axis=2)

299 300 301 302 303 304 305 306
        pred = F.multiclass_nms(
            bboxes=yolo_boxes,
            scores=yolo_scores,
            score_threshold=self.valid_thresh,
            nms_top_k=self.nms_topk,
            keep_top_k=self.nms_posk,
            nms_threshold=self.nms_thresh,
            background_label=-1)
307 308 309 310 311 312 313

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

        if visualization:
H
haoyuying 已提交
314 315
            if not os.path.exists(save_path):
                os.mkdir(save_path)
316
            utils.draw_boxes_on_image(imgpath, boxes, scores, labels, label_names, 0.5, save_path)
H
haoyuying 已提交
317 318

        return boxes, scores, labels
H
haoyuying 已提交
319 320


H
haoyuying 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
class StyleTransferModule(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 and labels.
            batch_idx(int): The index of batch.

        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.

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

        Returns:
            results(dict) : The model outputs, such as metrics.
        '''
        mse_loss = nn.MSELoss()
        N, C, H, W = batch[0].shape
        batch[1] = batch[1][0].unsqueeze(0)
        self.setTarget(batch[1])

        y = self(batch[0])
        xc = paddle.to_tensor(batch[0].numpy().copy())
353 354
        y = utils.subtract_imagenet_mean_batch(y)
        xc = utils.subtract_imagenet_mean_batch(xc)
H
haoyuying 已提交
355 356 357 358 359
        features_y = self.getFeature(y)
        features_xc = self.getFeature(xc)
        f_xc_c = paddle.to_tensor(features_xc[1].numpy(), stop_gradient=True)
        content_loss = mse_loss(features_y[1], f_xc_c)

360
        batch[1] = utils.subtract_imagenet_mean_batch(batch[1])
H
haoyuying 已提交
361
        features_style = self.getFeature(batch[1])
362
        gram_style = [utils.gram_matrix(y) for y in features_style]
H
haoyuying 已提交
363 364
        style_loss = 0.
        for m in range(len(features_y)):
365
            gram_y = utils.gram_matrix(features_y[m])
H
haoyuying 已提交
366 367 368 369 370 371 372
            gram_s = paddle.to_tensor(np.tile(gram_style[m].numpy(), (N, 1, 1, 1)))
            style_loss += mse_loss(gram_y, gram_s[:N, :, :])

        loss = content_loss + style_loss

        return {'loss': loss, 'metrics': {'content gap': content_loss, 'style gap': style_loss}}

H
haoyuying 已提交
373
    def predict(self, origin: str, style: str, visualization: bool = True, save_path: str = 'result'):
H
haoyuying 已提交
374 375 376 377
        '''
        Colorize images

        Args:
H
haoyuying 已提交
378 379
            origin(str|np.array): Content image path or BGR image.
            style(str|np.array): Style image path or BGR image.
H
haoyuying 已提交
380 381 382 383 384 385
            visualization(bool): Whether to save colorized images.
            save_path(str) : Path to save colorized images.

        Returns:
            output(np.ndarray) : The style transformed images with bgr mode.
        '''
386
        self.eval()
H
haoyuying 已提交
387 388 389

        content = paddle.to_tensor(self.transform(origin).astype('float32'))
        style = paddle.to_tensor(self.transform(style).astype('float32'))
H
haoyuying 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
        content = content.unsqueeze(0)
        style = style.unsqueeze(0)

        self.setTarget(style)
        output = self(content)
        output = paddle.clip(output[0].transpose((1, 2, 0)), 0, 255).numpy()

        if visualization:
            output = output.astype(np.uint8)
            style_name = "style_" + str(time.time()) + ".png"
            if not os.path.exists(save_path):
                os.mkdir(save_path)
            path = os.path.join(save_path, style_name)
            cv2.imwrite(path, output)
        return output