test_transforms.py 28.3 KB
Newer Older
L
LielinJiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# 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.

import unittest
import os
import tempfile
import cv2
import shutil
import numpy as np
21
from PIL import Image
L
LielinJiang 已提交
22

23 24
import paddle
from paddle.vision import get_image_backend, set_image_backend, image_load
25 26 27
from paddle.vision.datasets import DatasetFolder
from paddle.vision.transforms import transforms
import paddle.vision.transforms.functional as F
L
LielinJiang 已提交
28 29


30
class TestTransformsCV2(unittest.TestCase):
L
LielinJiang 已提交
31
    def setUp(self):
32 33
        self.backend = self.get_backend()
        set_image_backend(self.backend)
L
LielinJiang 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47
        self.data_dir = tempfile.mkdtemp()
        for i in range(2):
            sub_dir = os.path.join(self.data_dir, 'class_' + str(i))
            if not os.path.exists(sub_dir):
                os.makedirs(sub_dir)
            for j in range(2):
                if j == 0:
                    fake_img = (np.random.random(
                        (280, 350, 3)) * 255).astype('uint8')
                else:
                    fake_img = (np.random.random(
                        (400, 300, 3)) * 255).astype('uint8')
                cv2.imwrite(os.path.join(sub_dir, str(j) + '.jpg'), fake_img)

48 49 50 51 52 53 54 55 56 57 58
    def get_backend(self):
        return 'cv2'

    def create_image(self, shape):
        if self.backend == 'cv2':
            return (np.random.rand(*shape) * 255).astype('uint8')
        elif self.backend == 'pil':
            return Image.fromarray((np.random.rand(*shape) * 255).astype(
                'uint8'))

    def get_shape(self, img):
59 60 61 62
        if isinstance(img, paddle.Tensor):
            return img.shape

        elif self.backend == 'pil':
63 64 65 66
            return np.array(img).shape

        return img.shape

L
LielinJiang 已提交
67 68 69 70 71 72 73 74 75 76 77
    def tearDown(self):
        shutil.rmtree(self.data_dir)

    def do_transform(self, trans):
        dataset_folder = DatasetFolder(self.data_dir, transform=trans)

        for _ in dataset_folder:
            pass

    def test_trans_all(self):
        normalize = transforms.Normalize(
78 79
            mean=[123.675, 116.28, 103.53],
            std=[58.395, 57.120, 57.375], )
L
LielinJiang 已提交
80
        trans = transforms.Compose([
81
            transforms.RandomResizedCrop(224),
L
LielinJiang 已提交
82
            transforms.ColorJitter(
83 84 85 86
                brightness=0.4, contrast=0.4, saturation=0.4, hue=0.4),
            transforms.RandomHorizontalFlip(),
            transforms.Transpose(),
            normalize,
L
LielinJiang 已提交
87 88 89 90
        ])

        self.do_transform(trans)

L
LielinJiang 已提交
91 92
    def test_normalize(self):
        normalize = transforms.Normalize(mean=0.5, std=0.5)
93
        trans = transforms.Compose([transforms.Transpose(), normalize])
L
LielinJiang 已提交
94 95
        self.do_transform(trans)

L
LielinJiang 已提交
96 97
    def test_trans_resize(self):
        trans = transforms.Compose([
98
            transforms.Resize(300),
L
LielinJiang 已提交
99
            transforms.RandomResizedCrop((280, 280)),
100
            transforms.Resize(280),
L
LielinJiang 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
            transforms.Resize((256, 200)),
            transforms.Resize((180, 160)),
            transforms.CenterCrop(128),
            transforms.CenterCrop((128, 128)),
        ])
        self.do_transform(trans)

    def test_flip(self):
        trans = transforms.Compose([
            transforms.RandomHorizontalFlip(1.0),
            transforms.RandomHorizontalFlip(0.0),
            transforms.RandomVerticalFlip(0.0),
            transforms.RandomVerticalFlip(1.0),
        ])
        self.do_transform(trans)

    def test_color_jitter(self):
118
        trans = transforms.Compose([
L
LielinJiang 已提交
119 120 121 122 123 124 125
            transforms.BrightnessTransform(0.0),
            transforms.HueTransform(0.0),
            transforms.SaturationTransform(0.0),
            transforms.ContrastTransform(0.0),
        ])
        self.do_transform(trans)

L
LielinJiang 已提交
126 127
    def test_rotate(self):
        trans = transforms.Compose([
128 129 130
            transforms.RandomRotation(90),
            transforms.RandomRotation([-10, 10]),
            transforms.RandomRotation(
L
LielinJiang 已提交
131
                45, expand=True),
132
            transforms.RandomRotation(
L
LielinJiang 已提交
133 134 135 136 137 138 139 140
                10, expand=True, center=(60, 80)),
        ])
        self.do_transform(trans)

    def test_pad(self):
        trans = transforms.Compose([transforms.Pad(2)])
        self.do_transform(trans)

141
        fake_img = self.create_image((200, 150, 3))
L
LielinJiang 已提交
142 143
        trans_pad = transforms.Pad(10)
        fake_img_padded = trans_pad(fake_img)
144
        np.testing.assert_equal(self.get_shape(fake_img_padded), (220, 170, 3))
L
LielinJiang 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        trans_pad1 = transforms.Pad([1, 2])
        trans_pad2 = transforms.Pad([1, 2, 3, 4])
        img = trans_pad1(fake_img)
        img = trans_pad2(img)

    def test_random_crop(self):
        trans = transforms.Compose([
            transforms.RandomCrop(200),
            transforms.RandomCrop((140, 160)),
        ])
        self.do_transform(trans)

        trans_random_crop1 = transforms.RandomCrop(224)
        trans_random_crop2 = transforms.RandomCrop((140, 160))

160
        fake_img = self.create_image((500, 400, 3))
L
LielinJiang 已提交
161 162 163
        fake_img_crop1 = trans_random_crop1(fake_img)
        fake_img_crop2 = trans_random_crop2(fake_img_crop1)

164
        np.testing.assert_equal(self.get_shape(fake_img_crop1), (224, 224, 3))
L
LielinJiang 已提交
165

166
        np.testing.assert_equal(self.get_shape(fake_img_crop2), (140, 160, 3))
L
LielinJiang 已提交
167 168 169 170

        trans_random_crop_same = transforms.RandomCrop((140, 160))
        img = trans_random_crop_same(fake_img_crop2)

171 172
        trans_random_crop_bigger = transforms.RandomCrop(
            (180, 200), pad_if_needed=True)
L
LielinJiang 已提交
173 174 175 176 177
        img = trans_random_crop_bigger(img)

        trans_random_crop_pad = transforms.RandomCrop((224, 256), 2, True)
        img = trans_random_crop_pad(img)

178 179 180 181 182 183
    def test_erase(self):
        trans = transforms.Compose([
            transforms.RandomErasing(), transforms.RandomErasing(value="random")
        ])
        self.do_transform(trans)

L
LielinJiang 已提交
184 185 186 187 188
    def test_grayscale(self):
        trans = transforms.Compose([transforms.Grayscale()])
        self.do_transform(trans)

        trans_gray = transforms.Grayscale()
189
        fake_img = self.create_image((500, 400, 3))
L
LielinJiang 已提交
190 191
        fake_img_gray = trans_gray(fake_img)

192 193
        np.testing.assert_equal(self.get_shape(fake_img_gray)[0], 500)
        np.testing.assert_equal(self.get_shape(fake_img_gray)[1], 400)
L
LielinJiang 已提交
194 195

        trans_gray3 = transforms.Grayscale(3)
196
        fake_img = self.create_image((500, 400, 3))
L
LielinJiang 已提交
197 198
        fake_img_gray = trans_gray3(fake_img)

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    def test_tranpose(self):
        trans = transforms.Compose([transforms.Transpose()])
        self.do_transform(trans)

        fake_img = self.create_image((50, 100, 3))
        converted_img = trans(fake_img)

        np.testing.assert_equal(self.get_shape(converted_img), (3, 50, 100))

    def test_to_tensor(self):
        trans = transforms.Compose([transforms.ToTensor()])
        fake_img = self.create_image((50, 100, 3))

        tensor = trans(fake_img)

        assert isinstance(tensor, paddle.Tensor)
        np.testing.assert_equal(tensor.shape, (3, 50, 100))

217 218 219 220 221 222
    def test_keys(self):
        fake_img1 = self.create_image((200, 150, 3))
        fake_img2 = self.create_image((200, 150, 3))
        trans_pad = transforms.Pad(10, keys=("image", ))
        fake_img_padded = trans_pad((fake_img1, fake_img2))

L
LielinJiang 已提交
223 224 225
    def test_exception(self):
        trans = transforms.Compose([transforms.Resize(-1)])

226
        trans_batch = transforms.Compose([transforms.Resize(-1)])
L
LielinJiang 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245

        with self.assertRaises(Exception):
            self.do_transform(trans)

        with self.assertRaises(Exception):
            self.do_transform(trans_batch)

        with self.assertRaises(ValueError):
            transforms.ContrastTransform(-1.0)

        with self.assertRaises(ValueError):
            transforms.SaturationTransform(-1.0),

        with self.assertRaises(ValueError):
            transforms.HueTransform(-1.0)

        with self.assertRaises(ValueError):
            transforms.BrightnessTransform(-1.0)

L
LielinJiang 已提交
246 247 248 249
        with self.assertRaises(ValueError):
            transforms.Pad([1.0, 2.0, 3.0])

        with self.assertRaises(TypeError):
250
            fake_img = self.create_image((100, 120, 3))
L
LielinJiang 已提交
251 252 253
            F.pad(fake_img, '1')

        with self.assertRaises(TypeError):
254
            fake_img = self.create_image((100, 120, 3))
L
LielinJiang 已提交
255 256 257
            F.pad(fake_img, 1, {})

        with self.assertRaises(TypeError):
258
            fake_img = self.create_image((100, 120, 3))
L
LielinJiang 已提交
259 260 261
            F.pad(fake_img, 1, padding_mode=-1)

        with self.assertRaises(ValueError):
262
            fake_img = self.create_image((100, 120, 3))
L
LielinJiang 已提交
263 264
            F.pad(fake_img, [1.0, 2.0, 3.0])

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, '1')

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, 1, {})

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, 1, padding_mode=-1)

        with self.assertRaises(ValueError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, [1.0, 2.0, 3.0])

L
LielinJiang 已提交
281
        with self.assertRaises(ValueError):
282
            transforms.RandomRotation(-2)
L
LielinJiang 已提交
283 284

        with self.assertRaises(ValueError):
285
            transforms.RandomRotation([1, 2, 3])
L
LielinJiang 已提交
286 287 288

        with self.assertRaises(ValueError):
            trans_gray = transforms.Grayscale(5)
289
            fake_img = self.create_image((100, 120, 3))
L
LielinJiang 已提交
290 291
            trans_gray(fake_img)

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
        with self.assertRaises(TypeError):
            transform = transforms.RandomResizedCrop(64)
            transform(1)

        with self.assertRaises(ValueError):
            transform = transforms.BrightnessTransform([-0.1, -0.2])

        with self.assertRaises(TypeError):
            transform = transforms.BrightnessTransform('0.1')

        with self.assertRaises(ValueError):
            transform = transforms.BrightnessTransform('0.1', keys=1)

        with self.assertRaises(NotImplementedError):
            transform = transforms.BrightnessTransform('0.1', keys='a')

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(scale=0.5)

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(ratio=0.8)

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(scale=(10, 0.4))

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(ratio=(3.3, 0.3))

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(prob=1.5)

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(value="0")

L
LielinJiang 已提交
326 327
    def test_info(self):
        str(transforms.Compose([transforms.Resize((224, 224))]))
328 329 330 331 332 333 334 335
        str(transforms.Compose([transforms.Resize((224, 224))]))


class TestTransformsPIL(TestTransformsCV2):
    def get_backend(self):
        return 'pil'


336 337 338 339 340 341 342 343 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 373 374 375 376 377 378 379 380 381
class TestTransformsTensor(TestTransformsCV2):
    def get_backend(self):
        return 'tensor'

    def create_image(self, shape):
        return paddle.to_tensor(np.random.rand(*shape)).transpose(
            (2, 0, 1))  # hwc->chw

    def do_transform(self, trans):
        trans.transforms.insert(0, transforms.ToTensor(data_format='CHW'))
        trans.transforms.append(transforms.Transpose(order=(1, 2, 0)))
        dataset_folder = DatasetFolder(self.data_dir, transform=trans)
        for _ in dataset_folder:
            pass

    def test_trans_all(self):
        normalize = transforms.Normalize(
            mean=[123.675, 116.28, 103.53],
            std=[58.395, 57.120, 57.375], )
        trans = transforms.Compose([
            transforms.RandomResizedCrop(224),
            transforms.RandomHorizontalFlip(),
            normalize,
        ])
        self.do_transform(trans)

    def test_grayscale(self):
        trans = transforms.Compose([transforms.Grayscale()])
        self.do_transform(trans)

        trans_gray = transforms.Grayscale()
        fake_img = self.create_image((500, 400, 3))
        fake_img_gray = trans_gray(fake_img)

        np.testing.assert_equal(self.get_shape(fake_img_gray)[1], 500)
        np.testing.assert_equal(self.get_shape(fake_img_gray)[2], 400)

        trans_gray3 = transforms.Grayscale(3)
        fake_img = self.create_image((500, 400, 3))
        fake_img_gray = trans_gray3(fake_img)

    def test_normalize(self):
        normalize = transforms.Normalize(mean=0.5, std=0.5)
        trans = transforms.Compose([normalize])
        self.do_transform(trans)

J
JYChen 已提交
382 383 384 385
    def test_color_jitter(self):
        trans = transforms.Compose([transforms.ColorJitter(1.1, 2.2, 0.8, 0.1)])
        self.do_transform(trans)

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    def test_pad(self):
        trans = transforms.Compose([transforms.Pad(2)])
        self.do_transform(trans)

        fake_img = self.create_image((200, 150, 3))
        trans_pad = transforms.Compose([transforms.Pad(10)])
        fake_img_padded = trans_pad(fake_img)
        np.testing.assert_equal(self.get_shape(fake_img_padded), (3, 220, 170))
        trans_pad1 = transforms.Pad([1, 2])
        trans_pad2 = transforms.Pad([1, 2, 3, 4])
        trans_pad4 = transforms.Pad(1, padding_mode='edge')
        img = trans_pad1(fake_img)
        img = trans_pad2(img)
        img = trans_pad4(img)

    def test_random_crop(self):
        trans = transforms.Compose([
            transforms.RandomCrop(200),
            transforms.RandomCrop((140, 160)),
        ])
        self.do_transform(trans)

        trans_random_crop1 = transforms.RandomCrop(224)
        trans_random_crop2 = transforms.RandomCrop((140, 160))

        fake_img = self.create_image((500, 400, 3))
        fake_img_crop1 = trans_random_crop1(fake_img)
        fake_img_crop2 = trans_random_crop2(fake_img_crop1)

        np.testing.assert_equal(self.get_shape(fake_img_crop1), (3, 224, 224))

        np.testing.assert_equal(self.get_shape(fake_img_crop2), (3, 140, 160))

        trans_random_crop_same = transforms.RandomCrop((140, 160))
        img = trans_random_crop_same(fake_img_crop2)

        trans_random_crop_bigger = transforms.RandomCrop(
            (180, 200), pad_if_needed=True)
        img = trans_random_crop_bigger(img)

        trans_random_crop_pad = transforms.RandomCrop((224, 256), 2, True)
        img = trans_random_crop_pad(img)

429 430 431 432 433 434 435
    def test_erase(self):
        trans = transforms.Compose([
            transforms.RandomErasing(value=(0.5, )),
            transforms.RandomErasing(value="random")
        ])
        self.do_transform(trans)

436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 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
    def test_exception(self):
        trans = transforms.Compose([transforms.Resize(-1)])

        trans_batch = transforms.Compose([transforms.Resize(-1)])

        with self.assertRaises(Exception):
            self.do_transform(trans)

        with self.assertRaises(Exception):
            self.do_transform(trans_batch)

        with self.assertRaises(ValueError):
            transforms.Pad([1.0, 2.0, 3.0])

        with self.assertRaises(TypeError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, '1')

        with self.assertRaises(TypeError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, 1, {})

        with self.assertRaises(TypeError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, 1, padding_mode=-1)

        with self.assertRaises(ValueError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, [1.0, 2.0, 3.0])

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, '1')

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, 1, {})

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, 1, padding_mode=-1)

        with self.assertRaises(ValueError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, [1.0, 2.0, 3.0])

        with self.assertRaises(ValueError):
            transforms.RandomRotation(-2)

        with self.assertRaises(ValueError):
            transforms.RandomRotation([1, 2, 3])

        with self.assertRaises(ValueError):
            trans_gray = transforms.Grayscale(5)
            fake_img = self.create_image((100, 120, 3))
            trans_gray(fake_img)

        with self.assertRaises(TypeError):
            transform = transforms.RandomResizedCrop(64)
            transform(1)

    test_color_jitter = None


500 501 502 503 504 505 506 507 508 509
class TestFunctional(unittest.TestCase):
    def test_errors(self):
        with self.assertRaises(TypeError):
            F.to_tensor(1)

        with self.assertRaises(ValueError):
            fake_img = Image.fromarray((np.random.rand(28, 28, 3) * 255).astype(
                'uint8'))
            F.to_tensor(fake_img, data_format=1)

510 511 512 513 514 515 516 517
        with self.assertRaises(ValueError):
            fake_img = paddle.rand((3, 100, 100))
            F.pad(fake_img, 1, padding_mode='symmetric')

        with self.assertRaises(TypeError):
            fake_img = paddle.rand((3, 100, 100))
            F.resize(fake_img, {1: 1})

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
        with self.assertRaises(TypeError):
            fake_img = Image.fromarray((np.random.rand(28, 28, 3) * 255).astype(
                'uint8'))
            F.resize(fake_img, '1')

        with self.assertRaises(TypeError):
            F.resize(1, 1)

        with self.assertRaises(TypeError):
            F.pad(1, 1)

        with self.assertRaises(TypeError):
            F.crop(1, 1, 1, 1, 1)

        with self.assertRaises(TypeError):
            F.hflip(1)

        with self.assertRaises(TypeError):
            F.vflip(1)

        with self.assertRaises(TypeError):
            F.adjust_brightness(1, 0.1)

        with self.assertRaises(TypeError):
            F.adjust_contrast(1, 0.1)

        with self.assertRaises(TypeError):
            F.adjust_hue(1, 0.1)

        with self.assertRaises(TypeError):
            F.adjust_saturation(1, 0.1)

        with self.assertRaises(TypeError):
            F.rotate(1, 0.1)

        with self.assertRaises(TypeError):
            F.to_grayscale(1)

        with self.assertRaises(ValueError):
            set_image_backend(1)

        with self.assertRaises(ValueError):
            image_load('tmp.jpg', backend=1)

    def test_normalize(self):
563
        np_img = (np.random.rand(28, 24, 3) * 255).astype('uint8')
564 565
        pil_img = Image.fromarray(np_img)
        tensor_img = F.to_tensor(pil_img)
566
        tensor_img_hwc = F.to_tensor(pil_img, data_format='HWC') * 255
567 568 569 570 571

        mean = [0.5, 0.5, 0.5]
        std = [0.5, 0.5, 0.5]

        normalized_img = F.normalize(tensor_img, mean, std)
572
        normalized_img_tensor = F.normalize(
573 574
            tensor_img_hwc, mean, std, data_format='HWC')

575 576
        normalized_img_pil = F.normalize(pil_img, mean, std, data_format='HWC')
        normalized_img_np = F.normalize(
577
            np_img, mean, std, data_format='HWC', to_rgb=False)
578

579 580
        np.testing.assert_almost_equal(
            np.array(normalized_img_pil), normalized_img_np)
581 582
        np.testing.assert_almost_equal(
            normalized_img_tensor.numpy(), normalized_img_np, decimal=4)
583

584
    def test_center_crop(self):
585
        np_img = (np.random.rand(28, 24, 3) * 255).astype('uint8')
586
        pil_img = Image.fromarray(np_img)
587
        tensor_img = F.to_tensor(pil_img, data_format='CHW') * 255
588 589 590

        np_cropped_img = F.center_crop(np_img, 4)
        pil_cropped_img = F.center_crop(pil_img, 4)
591
        tensor_cropped_img = F.center_crop(tensor_img, 4)
592 593 594

        np.testing.assert_almost_equal(np_cropped_img,
                                       np.array(pil_cropped_img))
595 596 597 598
        np.testing.assert_almost_equal(
            np_cropped_img,
            tensor_cropped_img.numpy().transpose((1, 2, 0)),
            decimal=4)
599

J
JYChen 已提交
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 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
    def test_color_jitter_sub_function(self):
        np.random.seed(555)
        np_img = (np.random.rand(28, 28, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img)
        tensor_img = F.to_tensor(np_img)
        np_img = pil_img

        np_img_gray = (np.random.rand(28, 28, 1) * 255).astype('uint8')
        tensor_img_gray = F.to_tensor(np_img_gray)

        places = ['cpu']
        if paddle.device.is_compiled_with_cuda():
            places.append('gpu')

        def test_adjust_brightness(np_img, tensor_img):
            result_cv2 = np.array(F.adjust_brightness(np_img, 1.2))
            result_tensor = F.adjust_brightness(tensor_img, 1.2).numpy()
            result_tensor = np.transpose(result_tensor * 255,
                                         (1, 2, 0)).astype('uint8')
            np.testing.assert_equal(result_cv2, result_tensor)

        # For adjust_contrast / adjust_saturation / adjust_hue the implement is kind
        # of different between PIL and Tensor. So the results can not equal exactly.

        def test_adjust_contrast(np_img, tensor_img):
            result_pil = np.array(F.adjust_contrast(np_img, 0.36))
            result_tensor = F.adjust_contrast(tensor_img, 0.36).numpy()
            result_tensor = np.transpose(result_tensor * 255, (1, 2, 0))
            diff = np.max(np.abs(result_tensor - result_pil))
            self.assertTrue(diff < 1.1)

        def test_adjust_saturation(np_img, tensor_img):
            result_pil = np.array(F.adjust_saturation(np_img, 1.0))
            result_tensor = F.adjust_saturation(tensor_img, 1.0).numpy()
            result_tensor = np.transpose(result_tensor * 255., (1, 2, 0))
            diff = np.max(np.abs(result_tensor - result_pil))
            self.assertTrue(diff < 1.1)

        def test_adjust_hue(np_img, tensor_img):
            result_pil = np.array(F.adjust_hue(np_img, 0.45))
            result_tensor = F.adjust_hue(tensor_img, 0.45).numpy()
            result_tensor = np.transpose(result_tensor * 255, (1, 2, 0))
            diff = np.max(np.abs(result_tensor - result_pil))
            self.assertTrue(diff <= 16.0)

        for place in places:
            paddle.set_device(place)

            test_adjust_brightness(np_img, tensor_img)
            test_adjust_contrast(np_img, tensor_img)
            test_adjust_saturation(np_img, tensor_img)
            test_adjust_hue(np_img, tensor_img)

653
    def test_pad(self):
654
        np_img = (np.random.rand(28, 24, 3) * 255).astype('uint8')
655
        pil_img = Image.fromarray(np_img)
656
        tensor_img = F.to_tensor(pil_img, 'CHW') * 255
657 658 659

        np_padded_img = F.pad(np_img, [1, 2], padding_mode='reflect')
        pil_padded_img = F.pad(pil_img, [1, 2], padding_mode='reflect')
660
        tensor_padded_img = F.pad(tensor_img, [1, 2], padding_mode='reflect')
661 662

        np.testing.assert_almost_equal(np_padded_img, np.array(pil_padded_img))
663 664 665 666
        np.testing.assert_almost_equal(
            np_padded_img,
            tensor_padded_img.numpy().transpose((1, 2, 0)),
            decimal=3)
667 668 669 670

        tensor_padded_img = F.pad(tensor_img, 1, padding_mode='reflect')
        tensor_padded_img = F.pad(tensor_img, [1, 2, 1, 2],
                                  padding_mode='reflect')
671 672 673 674 675 676

        pil_p_img = pil_img.convert('P')
        pil_padded_img = F.pad(pil_p_img, [1, 2])
        pil_padded_img = F.pad(pil_p_img, [1, 2], padding_mode='reflect')

    def test_resize(self):
677
        np_img = (np.zeros([28, 24, 3]) * 255).astype('uint8')
678
        pil_img = Image.fromarray(np_img)
679
        tensor_img = F.to_tensor(pil_img, 'CHW') * 255
680 681 682

        np_reseized_img = F.resize(np_img, 40)
        pil_reseized_img = F.resize(pil_img, 40)
683 684
        tensor_reseized_img = F.resize(tensor_img, 40)
        tensor_reseized_img2 = F.resize(tensor_img, (46, 40))
685 686 687

        np.testing.assert_almost_equal(np_reseized_img,
                                       np.array(pil_reseized_img))
688 689 690 691 692 693 694 695
        np.testing.assert_almost_equal(
            np_reseized_img,
            tensor_reseized_img.numpy().transpose((1, 2, 0)),
            decimal=3)
        np.testing.assert_almost_equal(
            np_reseized_img,
            tensor_reseized_img2.numpy().transpose((1, 2, 0)),
            decimal=3)
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727

        gray_img = (np.zeros([28, 32])).astype('uint8')
        gray_resize_img = F.resize(gray_img, 40)

    def test_to_tensor(self):
        np_img = (np.random.rand(28, 28) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img)

        np_tensor = F.to_tensor(np_img, data_format='HWC')
        pil_tensor = F.to_tensor(pil_img, data_format='HWC')

        np.testing.assert_allclose(np_tensor.numpy(), pil_tensor.numpy())

        # test float dtype 
        float_img = np.random.rand(28, 28)
        float_tensor = F.to_tensor(float_img)

        pil_img = Image.fromarray(np_img).convert('I')
        pil_tensor = F.to_tensor(pil_img)

        pil_img = Image.fromarray(np_img).convert('I;16')
        pil_tensor = F.to_tensor(pil_img)

        pil_img = Image.fromarray(np_img).convert('F')
        pil_tensor = F.to_tensor(pil_img)

        pil_img = Image.fromarray(np_img).convert('1')
        pil_tensor = F.to_tensor(pil_img)

        pil_img = Image.fromarray(np_img).convert('YCbCr')
        pil_tensor = F.to_tensor(pil_img)

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    def test_erase(self):
        np_img = (np.random.rand(28, 28, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img).convert('RGB')

        expected = np_img.copy()
        expected[10:15, 10:15, :] = 0

        F.erase(np_img, 10, 10, 5, 5, 0, inplace=True)
        np.testing.assert_equal(np_img, expected)

        pil_result = F.erase(pil_img, 10, 10, 5, 5, 0)
        np.testing.assert_equal(np.array(pil_result), expected)

        np_data = np.random.rand(3, 28, 28).astype('float32')
        places = ['cpu']
        if paddle.device.is_compiled_with_cuda():
            places.append('gpu')
        for place in places:
            paddle.set_device(place)
            tensor_img = paddle.to_tensor(np_data)
            expected_tensor = tensor_img.clone()
            expected_tensor[:, 10:15, 10:15] = paddle.to_tensor([0.88])

            tensor_result = F.erase(tensor_img, 10, 10, 5, 5,
                                    paddle.to_tensor([0.88]))
            np.testing.assert_equal(tensor_result.numpy(),
                                    expected_tensor.numpy())

    def test_erase_backward(self):
        img = paddle.randn((3, 14, 14), dtype=np.float32)
        img.stop_gradient = False
        erased = F.erase(
            img, 3, 3, 5, 5, paddle.ones(
                (1, 1, 1), dtype='float32'))
        loss = erased.sum()
        loss.backward()

        expected_grad = np.ones((3, 14, 14), dtype=np.float32)
        expected_grad[:, 3:8, 3:8] = 0.
        np.testing.assert_equal(img.grad.numpy(), expected_grad)

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
    def test_image_load(self):
        fake_img = Image.fromarray((np.random.random((32, 32, 3)) * 255).astype(
            'uint8'))

        path = 'temp.jpg'
        fake_img.save(path)

        set_image_backend('pil')

        pil_img = image_load(path).convert('RGB')

        print(type(pil_img))

        set_image_backend('cv2')

        np_img = image_load(path)

        os.remove(path)
L
LielinJiang 已提交
787

788 789 790 791 792 793
    def test_rotate(self):
        np_img = (np.random.rand(28, 28, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img).convert('RGB')
        rotated_np_img = F.rotate(np_img, 80, expand=True)
        rotated_pil_img = F.rotate(pil_img, 80, expand=True)

794 795 796 797 798 799 800 801 802 803 804
        tensor_img = F.to_tensor(pil_img, 'CHW')

        rotated_tensor_img1 = F.rotate(tensor_img, 80, expand=True)

        rotated_tensor_img2 = F.rotate(
            tensor_img,
            80,
            interpolation='bilinear',
            center=(10, 10),
            expand=False)

805 806
        np.testing.assert_equal(rotated_np_img.shape,
                                np.array(rotated_pil_img).shape)
807 808
        np.testing.assert_equal(rotated_np_img.shape,
                                rotated_tensor_img1.transpose((1, 2, 0)).shape)
809

810 811 812 813 814 815 816 817 818 819 820 821
    def test_rotate1(self):
        np_img = (np.random.rand(28, 28, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img).convert('RGB')

        rotated_np_img = F.rotate(
            np_img, 80, expand=True, center=[0, 0], fill=[0, 0, 0])
        rotated_pil_img = F.rotate(
            pil_img, 80, expand=True, center=[0, 0], fill=[0, 0, 0])

        np.testing.assert_equal(rotated_np_img.shape,
                                np.array(rotated_pil_img).shape)

L
LielinJiang 已提交
822 823 824

if __name__ == '__main__':
    unittest.main()