cv_module.py 22.7 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
H
haoyuying 已提交
18 19 20
import base64
import argparse
from typing import List, Union
H
haoyuying 已提交
21
from collections import OrderedDict
22

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

30 31 32
import paddlehub.vision.transforms as T
import paddlehub.vision.functional as Func
from paddlehub.vision import utils
H
haoyuying 已提交
33 34
from paddlehub.module.module import serving, RunModule, runnable
from paddlehub.utils.utils import base64_to_cv2, cv2_to_base64
W
wuzewu 已提交
35 36 37 38


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

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

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

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

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

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

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

H
haoyuying 已提交
81
    def predict(self, images: List[np.ndarray], batch_size: int = 1, top_k: int = 1) -> List[dict]:
82 83 84 85 86
        '''
        Predict images

        Args:
            images(list[numpy.ndarray]) : Images to be predicted, consist of np.ndarray in bgr format.
H
haoyuying 已提交
87
            batch_size(int) : Batch size for prediciton.
88 89 90 91 92
            top_k(int) : Output top k result of each image.

        Returns:
            results(list[dict]) : The prediction result of each input image
        '''
H
haoyuying 已提交
93
        self.eval()
W
wuzewu 已提交
94
        res = []
H
haoyuying 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
        total_num = len(images)
        loop_num = int(np.ceil(total_num / batch_size))
 
        for iter_id in range(loop_num):
            batch_data = []
            handle_id = iter_id * batch_size
            for image_id in range(batch_size):
                try:
                    image = self.transforms(images[handle_id + image_id])
                    batch_data.append(image)
                except:
                    pass
            batch_image = np.array(batch_data)
            preds, feature = self(paddle.to_tensor(batch_image))
            preds = F.softmax(preds, axis=1).numpy()
            pred_idxs = np.argsort(preds)[:, ::-1][:, :top_k]
            
            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)   
H
haoyuying 已提交
119

W
wuzewu 已提交
120
        return res
H
haoyuying 已提交
121

H
haoyuying 已提交
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
    @serving
    def serving_method(self, images: list, top_k: int, **kwargs):
        """
        Run as a service.
        """
        top_k = int(top_k)
        images_decode = [base64_to_cv2(image) for image in images]
        resdicts = self.predict(images=images_decode, top_k=top_k,**kwargs)
        final={}
        for resdict in resdicts:
            for key, value in resdict.items():
                resdict[key] = float(value)
        final['data'] = resdicts
        return final

    @runnable
    def run_cmd(self, argvs: list):
        """
        Run as a command.
        """
        self.parser = argparse.ArgumentParser(
            description="Run the {} module.".format(self.name),
            prog='hub run {}'.format(self.name),
            usage='%(prog)s',
            add_help=True)
        self.arg_input_group = self.parser.add_argument_group(
            title="Input options", description="Input data. Required")
        self.arg_config_group = self.parser.add_argument_group(
            title="Config options",
            description=
            "Run configuration for controlling module behavior, not required.")
        self.add_module_config_arg()
        self.add_module_input_arg()
        args = self.parser.parse_args(argvs)
        results = self.predict(
            images=[args.input_path],
            top_k=args.top_k)
H
haoyuying 已提交
159

H
haoyuying 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        return results

    def add_module_config_arg(self):
        """
        Add the command config options.
        """

        self.arg_config_group.add_argument(
            '--top_k',
            type=int,
            default=1,
            help="top_k classification result.")

    def add_module_input_arg(self):
        """
        Add the command input options.
        """
        self.arg_input_group.add_argument(
            '--input_path', type=str, help="path to image.")

       
H
haoyuying 已提交
181 182 183 184
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 已提交
185

H
haoyuying 已提交
186 187 188
        Args:
            batch(list[paddle.Tensor]): The one batch data, which contains images and labels.
            batch_idx(int): The index of batch.
H
haoyuying 已提交
189

H
haoyuying 已提交
190
        Returns:
H
haoyuying 已提交
191
            results(dict): The model outputs, such as loss and metrics.
H
haoyuying 已提交
192 193 194 195 196 197
        '''
        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 已提交
198

H
haoyuying 已提交
199 200 201
        Args:
            batch(list[paddle.Tensor]): The one batch data, which contains images and labels.
            batch_idx(int): The index of batch.
H
haoyuying 已提交
202

H
haoyuying 已提交
203 204 205
        Returns:
            results(dict) : The model outputs, such as metrics.
        '''
H
haoyuying 已提交
206 207
        img = self.preprocess(batch[0])
        out_class, out_reg = self(img['A'], img['hint_B'], img['mask_B'])
H
haoyuying 已提交
208

H
haoyuying 已提交
209
        # loss
H
haoyuying 已提交
210 211
        loss_ce = F.cross_entropy(out_class, img['real_B_enc'][:, :1, :, :], axis=1)
        loss_ce = paddle.mean(loss_ce)
H
haoyuying 已提交
212
        loss_G_L1_reg = paddle.sum(paddle.abs(img['B'] - out_reg), axis=1, keepdim=True)
H
haoyuying 已提交
213 214
        loss_G_L1_reg = paddle.mean(loss_G_L1_reg)
        loss = loss_ce + loss_G_L1_reg
H
haoyuying 已提交
215
        return {'loss': loss}
H
haoyuying 已提交
216

H
haoyuying 已提交
217
    def predict(self, images: list, visualization: bool = True, batch_size: int = 1, save_path: str = 'colorization'):
H
haoyuying 已提交
218 219
        '''
        Colorize images
H
haoyuying 已提交
220

H
haoyuying 已提交
221
        Args:
H
haoyuying 已提交
222
            images(list[str|np.ndarray]) : Images path or BGR image to be colorized.
H
haoyuying 已提交
223
            visualization(bool): Whether to save colorized images.
H
haoyuying 已提交
224
            batch_size(int): Batch size for prediciton.
H
haoyuying 已提交
225
            save_path(str) : Path to save colorized images.
H
haoyuying 已提交
226

H
haoyuying 已提交
227
        Returns:
H
haoyuying 已提交
228
            res(list[dict]) : The prediction result of each input image
H
haoyuying 已提交
229
        '''
230
        self.eval()
H
haoyuying 已提交
231
        lab2rgb = T.LAB2RGB()
H
haoyuying 已提交
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
        res = []
        total_num = len(images)
        loop_num = int(np.ceil(total_num / batch_size))
        for iter_id in range(loop_num):
            batch_data = []
            handle_id = iter_id * batch_size
            for image_id in range(batch_size):
                try:
                    image = self.transforms(images[handle_id + image_id])
                    batch_data.append(image)
                except:
                    pass
            batch_data = np.array(batch_data)
            im = self.preprocess(batch_data)
            out_class, out_reg = self(im['A'], im['hint_B'], im['mask_B'])

            visual_ret = OrderedDict()
            for i in range(im['A'].shape[0]):
                gray = lab2rgb(np.concatenate((im['A'].numpy(), np.zeros(im['B'].shape)), axis=1))[i]
                gray = np.clip(np.transpose(gray, (1, 2, 0)), 0, 1) * 255
                visual_ret['gray'] = gray.astype(np.uint8)
                hint = lab2rgb(np.concatenate((im['A'].numpy(), im['hint_B'].numpy()), axis=1))[i]
                hint = np.clip(np.transpose(hint, (1, 2, 0)), 0, 1) * 255
                visual_ret['hint'] = hint.astype(np.uint8)
                real = lab2rgb(np.concatenate((im['A'].numpy(), im['B'].numpy()), axis=1))[i]
                real = np.clip(np.transpose(real, (1, 2, 0)), 0, 1) * 255
                visual_ret['real'] = real.astype(np.uint8)
                fake = lab2rgb(np.concatenate((im['A'].numpy(), out_reg.numpy()), axis=1))[i]
                fake = np.clip(np.transpose(fake, (1, 2, 0)), 0, 1) * 255
                visual_ret['fake_reg'] = fake.astype(np.uint8)

                if visualization:
                    if isinstance(images[handle_id + i], str):
                        org_img = cv2.imread(images[handle_id + i]).astype('float32')
                    else:
                        org_img = images[handle_id + i]
                    h, w, c = org_img.shape
                    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 = visual_gray.resize((w, h), Image.BILINEAR)
                    visual_gray.save(fake_path)

                res.append(visual_ret)
        return res
W
wuzewu 已提交
279

H
haoyuying 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    @serving
    def serving_method(self, images: list, **kwargs):
        """
        Run as a service.
        """
        images_decode = [base64_to_cv2(image) for image in images]
        visual = self.predict(images=images_decode, **kwargs)
        final={}
        for i, visual_ret in enumerate(visual):
            h, w, c = images_decode[i].shape
            for key, value in visual_ret.items():
                value = cv2.resize(cv2.cvtColor(value,cv2.COLOR_RGB2BGR), (w, h), cv2.INTER_NEAREST)
                visual_ret[key] = cv2_to_base64(value)
        final['data'] = visual
        return final

    @runnable
    def run_cmd(self, argvs: list):
        """
        Run as a command.
        """
        self.parser = argparse.ArgumentParser(
            description="Run the {} module.".format(self.name),
            prog='hub run {}'.format(self.name),
            usage='%(prog)s',
            add_help=True)
        self.arg_input_group = self.parser.add_argument_group(
            title="Input options", description="Input data. Required")
        self.arg_config_group = self.parser.add_argument_group(
            title="Config options",
            description=
            "Run configuration for controlling module behavior, not required.")
        self.add_module_config_arg()
        self.add_module_input_arg()
        args = self.parser.parse_args(argvs)
        results = self.predict(
            images=[args.input_path],
            visualization=args.visualization,
            save_path=args.output_dir)

        return results

    def add_module_config_arg(self):
        """
        Add the command config options.
        """

        self.arg_config_group.add_argument(
            '--output_dir',
            type=str,
            default='colorization',
            help="save visualization result.")
        self.arg_config_group.add_argument(
            '--visualization',
            type=bool,
            default=True,
            help="whether to save output as images.")

    def add_module_input_arg(self):
        """
        Add the command input options.
        """
        self.arg_input_group.add_argument(
            '--input_path', type=str, help="path to image.")
H
haoyuying 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372


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')
373 374 375 376 377 378 379 380 381
        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]
382 383 384 385 386 387 388 389 390 391 392
            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 已提交
393
            losses.append(paddle.mean(loss))
394 395 396
            self.downsample //= 2

        return {'loss': sum(losses)}
H
haoyuying 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412

    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.
        '''
413
        self.eval()
414 415 416 417
        boxes = []
        scores = []
        self.downsample = 32
        im = self.transform(imgpath)
418
        h, w, c = utils.img_shape(imgpath)
419
        im_shape = paddle.to_tensor(np.array([[h, w]]).astype('int32'))
420
        label_names = utils.get_label_infos(filelist)
421 422 423 424 425 426 427 428 429 430 431
        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])

432 433 434 435 436 437 438 439
            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))
440 441 442 443 444 445 446 447

            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)

448 449 450 451 452 453 454 455
        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)
456 457 458 459 460 461 462

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

        if visualization:
H
haoyuying 已提交
463 464
            if not os.path.exists(save_path):
                os.mkdir(save_path)
465
            utils.draw_boxes_on_image(imgpath, boxes, scores, labels, label_names, 0.5, save_path)
H
haoyuying 已提交
466 467

        return boxes, scores, labels
H
haoyuying 已提交
468 469


H
haoyuying 已提交
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
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())
502 503
        y = utils.subtract_imagenet_mean_batch(y)
        xc = utils.subtract_imagenet_mean_batch(xc)
H
haoyuying 已提交
504 505 506 507 508
        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)

509
        batch[1] = utils.subtract_imagenet_mean_batch(batch[1])
H
haoyuying 已提交
510
        features_style = self.getFeature(batch[1])
511
        gram_style = [utils.gram_matrix(y) for y in features_style]
H
haoyuying 已提交
512 513
        style_loss = 0.
        for m in range(len(features_y)):
514
            gram_y = utils.gram_matrix(features_y[m])
H
haoyuying 已提交
515 516 517 518 519 520 521
            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 已提交
522
    def predict(self, origin: list, style: Union[str, np.ndarray], batch_size: int = 1, visualization: bool = True, save_path: str = 'style_tranfer'):
H
haoyuying 已提交
523 524 525 526
        '''
        Colorize images

        Args:
H
haoyuying 已提交
527
            origin(list[str|np.array]): Content image path or BGR image.
H
haoyuying 已提交
528
            style(str|np.array): Style image path or BGR image.
H
haoyuying 已提交
529
            batch_size(int): Batch size for prediciton.
H
haoyuying 已提交
530 531 532 533
            visualization(bool): Whether to save colorized images.
            save_path(str) : Path to save colorized images.

        Returns:
H
haoyuying 已提交
534
            output(list[np.ndarray]) : The style transformed images with bgr mode.
H
haoyuying 已提交
535
        '''
536
        self.eval()
H
haoyuying 已提交
537
        style = paddle.to_tensor(self.transform(style).astype('float32'))
H
haoyuying 已提交
538 539
        style = style.unsqueeze(0)

H
haoyuying 已提交
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
        res = []
        total_num = len(origin)
        loop_num = int(np.ceil(total_num / batch_size))
        for iter_id in range(loop_num):
            batch_data = []
            handle_id = iter_id * batch_size
            for image_id in range(batch_size):
                try:
                    image = self.transform(origin[handle_id + image_id])
                    batch_data.append(image.astype('float32'))
                except:
                    pass

            batch_image = np.array(batch_data)    
            content = paddle.to_tensor(batch_image)

            self.setTarget(style)
            output = self(content)
            for num in range(batch_size):
                out = paddle.clip(output[num].transpose((1, 2, 0)), 0, 255).numpy().astype(np.uint8)
                res.append(out)
                if visualization:
                    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, out)
        return res
H
haoyuying 已提交
568

H
haoyuying 已提交
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
    @serving
    def serving_method(self, images: list, **kwargs):
        """
        Run as a service.
        """
        images_decode = [base64_to_cv2(image) for image in images[0]]
        style_decode = base64_to_cv2(images[1])
        results = self.predict(origin=images_decode, style=style_decode, **kwargs)
        final={}
        final['data'] = [cv2_to_base64(result) for result in results]
        return final

    @runnable
    def run_cmd(self, argvs: list):
        """
        Run as a command.
        """
        self.parser = argparse.ArgumentParser(
            description="Run the {} module.".format(self.name),
            prog='hub run {}'.format(self.name),
            usage='%(prog)s',
            add_help=True)
        self.arg_input_group = self.parser.add_argument_group(
            title="Input options", description="Input data. Required")
        self.arg_config_group = self.parser.add_argument_group(
            title="Config options",
            description=
            "Run configuration for controlling module behavior, not required.")
        self.add_module_config_arg()
        self.add_module_input_arg()
        args = self.parser.parse_args(argvs)
        results = self.predict(
            origin=[args.input_path],
            style=args.style_path,
            save_path=args.output_dir,
            visualization=args.visualization)

        return results
        
    def add_module_config_arg(self):
        """
        Add the command config options.
        """

        self.arg_config_group.add_argument(
            '--output_dir',
            type=str,
            default='style_tranfer',
            help="The directory to save output images.")

        self.arg_config_group.add_argument(
            '--visualization',
            type=bool,
            default=True,
            help="whether to save output as images.")

    def add_module_input_arg(self):
        """
        Add the command input options.
        """
        self.arg_input_group.add_argument(
            '--input_path', type=str, help="path to image.")
        self.arg_input_group.add_argument(
            '--style_path', type=str, help="path to style image.")