| 1 | # Licensed to the Apache Software Foundation (ASF) under one | ||
| 2 | # or more contributor license agreements. See the NOTICE file | ||
| 3 | # distributed with this work for additional information | ||
| 4 | # regarding copyright ownership. The ASF licenses this file | ||
| 5 | # to you under the Apache License, Version 2.0 (the | ||
| 6 | # "License"); you may not use this file except in compliance | ||
| 7 | # with the License. You may obtain a copy of the License at | ||
| 8 | # | ||
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
| 10 | # | ||
| 11 | # Unless required by applicable law or agreed to in writing, | ||
| 12 | # software distributed under the License is distributed on an | ||
| 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| 14 | # KIND, either express or implied. See the License for the | ||
| 15 | # specific language governing permissions and limitations | ||
| 16 | # under the License. | ||
| 17 | |||
| 18 | package AI::MXNet::Image; | ||
| 19 | use strict; | ||
| 20 | use warnings; | ||
| 21 | use Scalar::Util qw(blessed); | ||
| 22 | use AI::MXNet::NS; | ||
| 23 | use AI::MXNet::Base; | ||
| 24 | use AI::MXNet::Function::Parameters; | ||
| 25 | use AI::MXNet::Image::NDArray; | ||
| 26 | use AI::MXNet::Image::Symbol; | ||
| 27 | |||
| 28 | =head1 NAME | ||
| 29 | |||
| 30 | AI::MXNet:Image - Read individual image files and perform augmentations. | ||
| 31 | =cut | ||
| 32 | |||
| 33 | =head2 imread | ||
| 34 | |||
| 35 | Read and decode an image to an NDArray. | ||
| 36 | |||
| 37 | Note: `imread` uses OpenCV. | ||
| 38 | MXNet must have been built with USE_OPENCV=1 for `imdecode` to work. | ||
| 39 | |||
| 40 | Parameters | ||
| 41 | ---------- | ||
| 42 | $filename : str | ||
| 43 | Name of the image file to be loaded. | ||
| 44 | :$flag : int | ||
| 45 | 0 for grayscale. 1 for colored. | ||
| 46 | :$to_rgb : int | ||
| 47 | 0 for BGR format (OpenCV default). 1 for RGB format (MXNet default). | ||
| 48 | :$out : NDArray | ||
| 49 | Output buffer. Do not specify for automatic allocation. | ||
| 50 | |||
| 51 | Returns | ||
| 52 | ------- | ||
| 53 | An NDArray containing the image. | ||
| 54 | |||
| 55 | Example | ||
| 56 | ------- | ||
| 57 | >>> mx->img->imread("flower.jpg"); | ||
| 58 | <NDArray 224x224x3 @cpu(0)> | ||
| 59 | |||
| 60 | Set `flag` parameter to 0 to get grayscale output | ||
| 61 | |||
| 62 | >>> mx->img->imdecode("flower.jpg", flag=>0); | ||
| 63 | <NDArray 224x224x1 @cpu(0)> | ||
| 64 | |||
| 65 | Set `to_rgb` parameter to 0 to get output in OpenCV format (BGR) | ||
| 66 | |||
| 67 | >>> mx->img->imdecode($str_image, to_rgb=>0); | ||
| 68 | <NDArray 224x224x3 @cpu(0)> | ||
| 69 | =cut | ||
| 70 | |||
| 71 | method imread(Str $filename, Int :$flag=1, Int :$to_rgb=1, Maybe[AI::MXNet::NDArray] :$out=) | ||
| 72 | { | ||
| 73 | return AI::MXNet::NDArray->_cvimread($filename, { flag => $flag, to_rgb => $to_rgb, ($out ? (out => $out) : ()) }); | ||
| 74 | } | ||
| 75 | |||
| 76 | =head2 imdecode | ||
| 77 | |||
| 78 | Decode an image from string. Requires OpenCV to work. | ||
| 79 | |||
| 80 | Parameters | ||
| 81 | ---------- | ||
| 82 | $buf : str, array ref, pdl, ndarray | ||
| 83 | Binary image data. | ||
| 84 | :$flag : int | ||
| 85 | 0 for grayscale. 1 for colored. | ||
| 86 | :$to_rgb : int | ||
| 87 | 0 for BGR format (OpenCV default). 1 for RGB format (MXNet default). | ||
| 88 | :$out : NDArray | ||
| 89 | Output buffer. Do not specify for automatic allocation. | ||
| 90 | =cut | ||
| 91 | |||
| 92 | method imdecode(Str|PDL $buf, Int :$flag=1, Int :$to_rgb=1, Maybe[AI::MXNet::NDArray] :$out=) | ||
| 93 | { | ||
| 94 | if(not ref $buf) | ||
| 95 | { | ||
| 96 | my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{'uint8'}); | ||
| 97 | my $len; { use bytes; $len = length $buf; } | ||
| 98 | my $pdl = PDL->new_from_specification($pdl_type, $len); | ||
| 99 | ${$pdl->get_dataref} = $buf; | ||
| 100 | $pdl->upd_data; | ||
| 101 | $buf = $pdl; | ||
| 102 | } | ||
| 103 | if(not (blessed $buf and $buf->isa('AI::MXNet::NDArray'))) | ||
| 104 | { | ||
| 105 | $buf = AI::MXNet::NDArray->array($buf, dtype=>'uint8'); | ||
| 106 | } | ||
| 107 | return AI::MXNet::NDArray->_cvimdecode($buf, { flag => $flag, to_rgb => $to_rgb, ($out ? (out => $out) : ()) }); | ||
| 108 | } | ||
| 109 | |||
| 110 | =head2 scale_down | ||
| 111 | |||
| 112 | Scale down crop size if it's bigger than the image size. | ||
| 113 | |||
| 114 | Parameters: | ||
| 115 | ----------- | ||
| 116 | Shape $src_size | ||
| 117 | Shape $size | ||
| 118 | |||
| 119 | Returns: | ||
| 120 | -------- | ||
| 121 | ($w, $h) | ||
| 122 | =cut | ||
| 123 | |||
| 124 | method scale_down(Shape $src_size, Shape $size) | ||
| 125 | { | ||
| 126 | my ($w, $h) = @{ $size }; | ||
| 127 | my ($sw, $sh) = @{ $src_size }; | ||
| 128 | if($sh < $h) | ||
| 129 | { | ||
| 130 | ($w, $h) = (($w*$sh)/$h, $sh); | ||
| 131 | } | ||
| 132 | if($sw < $w) | ||
| 133 | { | ||
| 134 | ($w, $h) = ($sw, ($h*$sw)/$w); | ||
| 135 | } | ||
| 136 | return (int($w), int($h)); | ||
| 137 | } | ||
| 138 | |||
| 139 | =head2 resize_short | ||
| 140 | |||
| 141 | Resize shorter edge to the size. | ||
| 142 | |||
| 143 | Parameters: | ||
| 144 | ----------- | ||
| 145 | AI::MXNet::NDArray $src | ||
| 146 | Int $size | ||
| 147 | Int $interp=2 | ||
| 148 | |||
| 149 | Returns: | ||
| 150 | -------- | ||
| 151 | AI::MXNet::NDArray $resized_image | ||
| 152 | =cut | ||
| 153 | |||
| 154 | method resize_short(AI::MXNet::NDArray $src, Int $size, Int $interp=2) | ||
| 155 | { | ||
| 156 | my ($new_h, $new_w); | ||
| 157 | my ($h, $w) = @{ $src->shape }; | ||
| 158 | if($h > $w) | ||
| 159 | { | ||
| 160 | ($new_h, $new_w) = ($size*$h/$w, $size); | ||
| 161 | } | ||
| 162 | else | ||
| 163 | { | ||
| 164 | ($new_h, $new_w) = ($size, $size*$w/$h); | ||
| 165 | } | ||
| 166 | return AI::MXNet::NDArray->_cvimresize($src, int $new_w, int $new_h, { interp=>$interp }); | ||
| 167 | } | ||
| 168 | |||
| 169 | =head2 fixed_crop | ||
| 170 | |||
| 171 | Crop src at fixed location, and (optionally) resize it to the size. | ||
| 172 | |||
| 173 | Parameters: | ||
| 174 | ----------- | ||
| 175 | AI::MXNet::NDArray $src | ||
| 176 | Int $x0 | ||
| 177 | Int $y0 | ||
| 178 | Int $w | ||
| 179 | Int $h | ||
| 180 | Maybe[Shape] $size= | ||
| 181 | Int $interp=2 | ||
| 182 | |||
| 183 | Returns: | ||
| 184 | -------- | ||
| 185 | AI::MXNet::NDArray $cropped_image | ||
| 186 | =cut | ||
| 187 | |||
| 188 | method fixed_crop(AI::MXNet::NDArray $src, Int $x0, Int $y0, Int $w, Int $h, Maybe[Shape] $size=, Int $interp=2) | ||
| 189 | { | ||
| 190 | my $out = AI::MXNet::NDArray->crop($src, { begin=>[$y0, $x0, 0], end=>[$y0+$h, $x0+$w, $src->shape->[2]] }); | ||
| 191 | if(defined $size and join(',', $w, $h) ne join(',', @{ $size })) | ||
| 192 | { | ||
| 193 | $out = AI::MXNet::NDArray->_cvimresize($out, (map { int } @{ $size }), { interp=>$interp }); | ||
| 194 | } | ||
| 195 | return $out; | ||
| 196 | } | ||
| 197 | |||
| 198 | =head2 random_crop | ||
| 199 | |||
| 200 | Randomly crop src with size. Upsample result if src is smaller than the size. | ||
| 201 | |||
| 202 | Parameters: | ||
| 203 | ----------- | ||
| 204 | AI::MXNet::NDArray $src | ||
| 205 | Shape $size= | ||
| 206 | Int $interp=2 | ||
| 207 | |||
| 208 | Returns: | ||
| 209 | -------- | ||
| 210 | ($cropped_image, [$x0, $y0, $new_w, $new_h]) | ||
| 211 | =cut | ||
| 212 | |||
| 213 | method random_crop(AI::MXNet::NDArray $src, Shape $size, Int $interp=2) | ||
| 214 | { | ||
| 215 | my ($h, $w) = @{ $src->shape }; | ||
| 216 | my ($new_w, $new_h) = __PACKAGE__->scale_down([$w, $h], $size); | ||
| 217 | |||
| 218 | my $x0 = int(rand($w - $new_w + 1)); | ||
| 219 | my $y0 = int(rand($h - $new_h + 1)); | ||
| 220 | |||
| 221 | my $out = __PACKAGE__->fixed_crop($src, $x0, $y0, $new_w, $new_h, $size, $interp); | ||
| 222 | return ($out, [$x0, $y0, $new_w, $new_h]); | ||
| 223 | } | ||
| 224 | |||
| 225 | =head2 center_crop | ||
| 226 | |||
| 227 | Randomly crop src with size around the center. Upsample result if src is smaller than the size. | ||
| 228 | |||
| 229 | Parameters: | ||
| 230 | ----------- | ||
| 231 | AI::MXNet::NDArray $src | ||
| 232 | Shape $size= | ||
| 233 | Int $interp=2 | ||
| 234 | |||
| 235 | Returns: | ||
| 236 | -------- | ||
| 237 | ($cropped_image, [$x0, $y0, $new_w, $new_h]) | ||
| 238 | =cut | ||
| 239 | |||
| 240 | method center_crop(AI::MXNet::NDArray $src, Shape $size, Int $interp=2) | ||
| 241 | { | ||
| 242 | my ($h, $w) = @{ $src->shape }; | ||
| 243 | my ($new_w, $new_h) = __PACKAGE__->scale_down([$w, $h], $size); | ||
| 244 | |||
| 245 | my $x0 = int(($w - $new_w)/2); | ||
| 246 | my $y0 = int(($h - $new_h)/2); | ||
| 247 | |||
| 248 | my $out = __PACKAGE__->fixed_crop($src, $x0, $y0, $new_w, $new_h, $size, $interp); | ||
| 249 | return ($out, [$x0, $y0, $new_w, $new_h]); | ||
| 250 | } | ||
| 251 | |||
| 252 | =head2 color_normalize | ||
| 253 | |||
| 254 | Normalize src with mean and std. | ||
| 255 | |||
| 256 | Parameters: | ||
| 257 | ----------- | ||
| 258 | AI::MXNet::NDArray $src | ||
| 259 | Num|AI::MXNet::NDArray $mean | ||
| 260 | Maybe[Num|AI::MXNet::NDArray] $std= | ||
| 261 | Int $interp=2 | ||
| 262 | |||
| 263 | Returns: | ||
| 264 | -------- | ||
| 265 | AI::MXNet::NDArray $normalized_image | ||
| 266 | =cut | ||
| 267 | |||
| 268 | method color_normalize(AI::MXNet::NDArray $src, Num|AI::MXNet::NDArray $mean, Maybe[Num|AI::MXNet::NDArray] $std=) | ||
| 269 | { | ||
| 270 | $src -= $mean; | ||
| 271 | if(defined $std) | ||
| 272 | { | ||
| 273 | $src /= $std; | ||
| 274 | } | ||
| 275 | return $src; | ||
| 276 | } | ||
| 277 | |||
| 278 | =head2 random_size_crop | ||
| 279 | |||
| 280 | Randomly crop src with size. Randomize area and aspect ratio. | ||
| 281 | |||
| 282 | Parameters: | ||
| 283 | ----------- | ||
| 284 | AI::MXNet::NDArray $src | ||
| 285 | Shape $size | ||
| 286 | Num $min_area | ||
| 287 | ArrayRef[Int] [$from, $to] # $ratio | ||
| 288 | Maybe[Int] $interp=2 | ||
| 289 | |||
| 290 | Returns: | ||
| 291 | -------- | ||
| 292 | ($cropped_image, [$x0, $y0, $new_w, $new_h]) | ||
| 293 | =cut | ||
| 294 | |||
| 295 | method random_size_crop(AI::MXNet::NDArray $src, Shape $size, Num $min_area, ArrayRef[Num] $ratio, Maybe[Int] $interp=2) | ||
| 296 | { | ||
| 297 | my ($h, $w) = @{ $src->shape }; | ||
| 298 | my ($from, $to) = @{ $ratio }; | ||
| 299 | my $new_ratio = $from + ($to-$from) * rand; | ||
| 300 | my $max_area; | ||
| 301 | if($new_ratio * $h > $w) | ||
| 302 | { | ||
| 303 | $max_area = $w*int($w/$new_ratio); | ||
| 304 | } | ||
| 305 | else | ||
| 306 | { | ||
| 307 | $max_area = $h*int($h*$new_ratio); | ||
| 308 | } | ||
| 309 | |||
| 310 | $min_area *= $h*$w; | ||
| 311 | if($max_area < $min_area) | ||
| 312 | { | ||
| 313 | return __PACKAGE__->random_crop($src, $size, $interp); | ||
| 314 | } | ||
| 315 | my $new_area = $min_area + ($max_area-$min_area) * rand; | ||
| 316 | my $new_w = int(sqrt($new_area*$new_ratio)); | ||
| 317 | my $new_h = $new_w; | ||
| 318 | |||
| 319 | assert($new_w <= $w and $new_h <= $h); | ||
| 320 | my $x0 = int(rand($w - $new_w + 1)); | ||
| 321 | my $y0 = int(rand($h - $new_h + 1)); | ||
| 322 | |||
| 323 | my $out = __PACKAGE__->fixed_crop($src, $x0, $y0, $new_w, $new_h, $size, $interp); | ||
| 324 | return ($out, [$x0, $y0, $new_w, $new_h]); | ||
| 325 | } | ||
| 326 | |||
| 327 | =head2 ResizeAug | ||
| 328 | |||
| 329 | Makes "resize shorter edge to size augumenter" closure. | ||
| 330 | |||
| 331 | Parameters: | ||
| 332 | ----------- | ||
| 333 | Shape $size | ||
| 334 | Int $interp=2 | ||
| 335 | |||
| 336 | Returns: | ||
| 337 | -------- | ||
| 338 | CodeRef that accepts AI::MXNet::NDArray $src as input | ||
| 339 | and returns [__PACKAGE__->resize_short($src, $size, $interp)] | ||
| 340 | =cut | ||
| 341 | |||
| 342 | method ResizeAug(Shape $size, Int $interp=2) | ||
| 343 | { | ||
| 344 | my $aug = sub { | ||
| 345 | my $src = shift; | ||
| 346 | return [__PACKAGE__->resize_short($src, $size, $interp)]; | ||
| 347 | }; | ||
| 348 | return $aug; | ||
| 349 | } | ||
| 350 | |||
| 351 | =head2 RandomCropAug | ||
| 352 | |||
| 353 | Makes "random crop augumenter" closure. | ||
| 354 | |||
| 355 | Parameters: | ||
| 356 | ----------- | ||
| 357 | Shape $size | ||
| 358 | Int $interp=2 | ||
| 359 | |||
| 360 | Returns: | ||
| 361 | -------- | ||
| 362 | CodeRef that accepts AI::MXNet::NDArray $src as input | ||
| 363 | and returns [(__PACKAGE__->random_crop($src, $size, $interp))[0]] | ||
| 364 | =cut | ||
| 365 | |||
| 366 | method RandomCropAug(Shape $size, Int $interp=2) | ||
| 367 | { | ||
| 368 | my $aug = sub { | ||
| 369 | my $src = shift; | ||
| 370 | return [(__PACKAGE__->random_crop($src, $size, $interp))[0]]; | ||
| 371 | }; | ||
| 372 | return $aug; | ||
| 373 | } | ||
| 374 | |||
| 375 | =head2 RandomSizedCropAug | ||
| 376 | |||
| 377 | Makes "random crop augumenter" closure. | ||
| 378 | |||
| 379 | Parameters: | ||
| 380 | ----------- | ||
| 381 | Shape $size | ||
| 382 | Num $min_area | ||
| 383 | ArrayRef[Num] $ratio | ||
| 384 | Int $interp=2 | ||
| 385 | |||
| 386 | Returns: | ||
| 387 | CodeRef that accepts AI::MXNet::NDArray $src as input | ||
| 388 | and returns [(__PACKAGE__->random_size_crop($src, $size, $min_area, $ratio, $interp))[0]] | ||
| 389 | =cut | ||
| 390 | |||
| 391 | method RandomSizedCropAug(Shape $size, Num $min_area, ArrayRef[Num] $ratio, Int $interp=2) | ||
| 392 | { | ||
| 393 | my $aug = sub { | ||
| 394 | my $src = shift; | ||
| 395 | return [(__PACKAGE__->random_size_crop($src, $size, $min_area, $ratio, $interp))[0]]; | ||
| 396 | }; | ||
| 397 | return $aug; | ||
| 398 | } | ||
| 399 | |||
| 400 | =head2 CenterCropAug | ||
| 401 | |||
| 402 | Makes "center crop augumenter" closure. | ||
| 403 | |||
| 404 | Parameters: | ||
| 405 | ----------- | ||
| 406 | Shape $size | ||
| 407 | Int $interp=2 | ||
| 408 | |||
| 409 | Returns: | ||
| 410 | CodeRef that accepts AI::MXNet::NDArray $src as input | ||
| 411 | and returns [(__PACKAGE__->center_crop($src, $size, $interp))[0]] | ||
| 412 | =cut | ||
| 413 | |||
| 414 | method CenterCropAug(Shape $size, Int $interp=2) | ||
| 415 | { | ||
| 416 | my $aug = sub { | ||
| 417 | my $src = shift; | ||
| 418 | return [(__PACKAGE__->center_crop($src, $size, $interp))[0]]; | ||
| 419 | }; | ||
| 420 | return $aug; | ||
| 421 | } | ||
| 422 | |||
| 423 | =head2 RandomOrderAug | ||
| 424 | |||
| 425 | Makes "Apply list of augmenters in random order" closure. | ||
| 426 | |||
| 427 | Parameters: | ||
| 428 | ----------- | ||
| 429 | ArrayRef[CodeRef] $ts | ||
| 430 | |||
| 431 | Returns: | ||
| 432 | -------- | ||
| 433 | CodeRef that accepts AI::MXNet::NDArray $src as input | ||
| 434 | and returns ArrayRef[AI::MXNet::NDArray] | ||
| 435 | =cut | ||
| 436 | |||
| 437 | method RandomOrderAug(ArrayRef[CodeRef] $ts) | ||
| 438 | { | ||
| 439 | my $aug = sub { | ||
| 440 | my $src = shift; | ||
| 441 | my @ts = List::Util::shuffle(@{ $ts }); | ||
| 442 | my @tmp; | ||
| 443 | for my $t (@ts) | ||
| 444 | { | ||
| 445 | push @tmp, $t->($src); | ||
| 446 | } | ||
| 447 | return \@tmp; | ||
| 448 | }; | ||
| 449 | return $aug; | ||
| 450 | } | ||
| 451 | |||
| 452 | =head2 RandomOrderAug | ||
| 453 | |||
| 454 | Makes "Apply random brightness, contrast and saturation jitter in random order" closure | ||
| 455 | |||
| 456 | Parameters: | ||
| 457 | ----------- | ||
| 458 | Num $brightness | ||
| 459 | Num $contrast | ||
| 460 | Num $saturation | ||
| 461 | |||
| 462 | Returns: | ||
| 463 | -------- | ||
| 464 | CodeRef that accepts AI::MXNet::NDArray $src as input | ||
| 465 | and returns ArrayRef[AI::MXNet::NDArray] | ||
| 466 | =cut | ||
| 467 | |||
| 468 | method ColorJitterAug(Num $brightness, Num $contrast, Num $saturation) | ||
| 469 | { | ||
| 470 | my @ts; | ||
| 471 | my $coef = AI::MXNet::NDArray->array([[[0.299, 0.587, 0.114]]]); | ||
| 472 | if($brightness > 0) | ||
| 473 | { | ||
| 474 | my $baug = sub { my $src = shift; | ||
| 475 | my $alpha = 1 + -$brightness + 2 * $brightness * rand; | ||
| 476 | $src *= $alpha; | ||
| 477 | return [$src]; | ||
| 478 | }; | ||
| 479 | push @ts, $baug; | ||
| 480 | } | ||
| 481 | |||
| 482 | if($contrast > 0) | ||
| 483 | { | ||
| 484 | my $caug = sub { my $src = shift; | ||
| 485 | my $alpha = 1 + -$contrast + 2 * $contrast * rand; | ||
| 486 | my $gray = $src*$coef; | ||
| 487 | $gray = (3.0*(1.0-$alpha)/$gray->size)*$gray->sum; | ||
| 488 | $src *= $alpha; | ||
| 489 | $src += $gray; | ||
| 490 | return [$src]; | ||
| 491 | }; | ||
| 492 | push @ts, $caug; | ||
| 493 | } | ||
| 494 | |||
| 495 | if($saturation > 0) | ||
| 496 | { | ||
| 497 | my $saug = sub { my $src = shift; | ||
| 498 | my $alpha = 1 + -$saturation + 2 * $saturation * rand; | ||
| 499 | my $gray = $src*$coef; | ||
| 500 | $gray = AI::MXNet::NDArray->sum($gray, { axis=>2, keepdims =>1 }); | ||
| 501 | $gray *= (1.0-$alpha); | ||
| 502 | $src *= $alpha; | ||
| 503 | $src += $gray; | ||
| 504 | return [$src]; | ||
| 505 | }; | ||
| 506 | push @ts, $saug; | ||
| 507 | } | ||
| 508 | |||
| 509 | return __PACKAGE__->RandomOrderAug(\@ts); | ||
| 510 | } | ||
| 511 | |||
| 512 | =head2 LightingAug | ||
| 513 | |||
| 514 | Makes "Add PCA based noise" closure. | ||
| 515 | |||
| 516 | Parameters: | ||
| 517 | ----------- | ||
| 518 | Num $alphastd | ||
| 519 | PDL $eigval | ||
| 520 | PDL $eigvec | ||
| 521 | |||
| 522 | Returns: | ||
| 523 | -------- | ||
| 524 | CodeRef that accepts AI::MXNet::NDArray $src as input | ||
| 525 | and returns ArrayRef[AI::MXNet::NDArray] | ||
| 526 | =cut | ||
| 527 | |||
| 528 | method LightingAug(Num $alphastd, PDL $eigval, PDL $eigvec) | ||
| 529 | { | ||
| 530 | my $aug = sub { my $src = shift; | ||
| 531 | my $alpha = AI::MXNet::NDArray->zeros([3]); | ||
| 532 | AI::MXNet::Random->normal(0, $alphastd, { out => $alpha }); | ||
| 533 | my $rgb = ($eigvec*$alpha->aspdl) x $eigval; | ||
| 534 | $src += AI::MXNet::NDArray->array($rgb); | ||
| 535 | return [$src] | ||
| 536 | }; | ||
| 537 | return $aug | ||
| 538 | } | ||
| 539 | |||
| 540 | =head2 ColorNormalizeAug | ||
| 541 | |||
| 542 | Makes "Mean and std normalization" closure. | ||
| 543 | |||
| 544 | Parameters: | ||
| 545 | ----------- | ||
| 546 | PDL $mean | ||
| 547 | PDL $std | ||
| 548 | |||
| 549 | Returns: | ||
| 550 | -------- | ||
| 551 | CodeRef that accepts AI::MXNet::NDArray $src as input | ||
| 552 | and returns [__PACKAGE__->color_normalize($src, $mean, $std)] | ||
| 553 | =cut | ||
| 554 | |||
| 555 | method ColorNormalizeAug(PDL $mean, PDL $std) | ||
| 556 | { | ||
| 557 | $mean = AI::MXNet::NDArray->array($mean); | ||
| 558 | $std = AI::MXNet::NDArray->array($std); | ||
| 559 | my $aug = sub { my $src = shift; | ||
| 560 | return [__PACKAGE__->color_normalize($src, $mean, $std)] | ||
| 561 | }; | ||
| 562 | return $aug; | ||
| 563 | } | ||
| 564 | |||
| 565 | =head2 HorizontalFlipAug | ||
| 566 | |||
| 567 | Makes "Random horizontal flipping" closure. | ||
| 568 | |||
| 569 | Parameters: | ||
| 570 | ----------- | ||
| 571 | Num $p < 1 | ||
| 572 | |||
| 573 | Returns: | ||
| 574 | -------- | ||
| 575 | CodeRef that accepts AI::MXNet::NDArray $src as input | ||
| 576 | and returns [$p > rand ? AI::MXNet::NDArray->flip($src, axis=1>) : $src] | ||
| 577 | =cut | ||
| 578 | |||
| 579 | method HorizontalFlipAug(Num $p) | ||
| 580 | { | ||
| 581 | my $aug = sub { my $src = shift; | ||
| 582 | return [$p > rand() ? AI::MXNet::NDArray->flip($src, { axis=>1 }) : $src] | ||
| 583 | }; | ||
| 584 | return $aug; | ||
| 585 | } | ||
| 586 | |||
| 587 | =head2 CastAug | ||
| 588 | |||
| 589 | Makes "Cast to float32" closure. | ||
| 590 | |||
| 591 | Returns: | ||
| 592 | -------- | ||
| 593 | CodeRef that accepts AI::MXNet::NDArray $src as input | ||
| 594 | and returns [$src->astype('float32')] | ||
| 595 | =cut | ||
| 596 | |||
| 597 | method CastAug() | ||
| 598 | { | ||
| 599 | my $aug = sub { my $src = shift; | ||
| 600 | return [$src->astype('float32')] | ||
| 601 | }; | ||
| 602 | return $aug; | ||
| 603 | } | ||
| 604 | |||
| 605 | =head2 CreateAugmenter | ||
| 606 | |||
| 607 | Create augumenter list | ||
| 608 | |||
| 609 | Parameters: | ||
| 610 | ----------- | ||
| 611 | Shape :$data_shape, | ||
| 612 | Bool :$resize=0, | ||
| 613 | Bool :$rand_crop=0, | ||
| 614 | Bool :$rand_resize=0, | ||
| 615 | Bool :$rand_mirror=0, | ||
| 616 | Maybe[Num|PDL] :$mean=, | ||
| 617 | Maybe[Num|PDL] :$std=, | ||
| 618 | Num :$brightness=0, | ||
| 619 | Num :$contrast=0, | ||
| 620 | Num :$saturation=0, | ||
| 621 | Num :$pca_noise=0, | ||
| 622 | Int :$inter_method=2 | ||
| 623 | =cut | ||
| 624 | |||
| 625 | method CreateAugmenter( | ||
| 626 | Shape :$data_shape, | ||
| 627 | Bool :$resize=0, | ||
| 628 | Bool :$rand_crop=0, | ||
| 629 | Bool :$rand_resize=0, | ||
| 630 | Bool :$rand_mirror=0, | ||
| 631 | Maybe[Num|PDL] :$mean=, | ||
| 632 | Maybe[Num|PDL] :$std=, | ||
| 633 | Num :$brightness=0, | ||
| 634 | Num :$contrast=0, | ||
| 635 | Num :$saturation=0, | ||
| 636 | Num :$pca_noise=0, | ||
| 637 | Int :$inter_method=2 | ||
| 638 | ) | ||
| 639 | { | ||
| 640 | my @auglist; | ||
| 641 | if($resize > 0) | ||
| 642 | { | ||
| 643 | push @auglist, __PACKAGE__->ResizeAug($resize, $inter_method); | ||
| 644 | } | ||
| 645 | |||
| 646 | my $crop_size = [$data_shape->[2], $data_shape->[1]]; | ||
| 647 | if($rand_resize) | ||
| 648 | { | ||
| 649 | assert($rand_crop); | ||
| 650 | push @auglist, __PACKAGE__->RandomSizedCropAug($crop_size, 0.3, [3.0/4.0, 4.0/3.0], $inter_method); | ||
| 651 | } | ||
| 652 | elsif($rand_crop) | ||
| 653 | { | ||
| 654 | push @auglist, __PACKAGE__->RandomCropAug($crop_size, $inter_method); | ||
| 655 | } | ||
| 656 | else | ||
| 657 | { | ||
| 658 | push @auglist, __PACKAGE__->CenterCropAug($crop_size, $inter_method); | ||
| 659 | } | ||
| 660 | |||
| 661 | if($rand_mirror) | ||
| 662 | { | ||
| 663 | push @auglist, __PACKAGE__->HorizontalFlipAug(0.5); | ||
| 664 | } | ||
| 665 | |||
| 666 | push @auglist, __PACKAGE__->CastAug; | ||
| 667 | |||
| 668 | if($brightness or $contrast or $saturation) | ||
| 669 | { | ||
| 670 | push @auglist, __PACKAGE__->ColorJitterAug($brightness, $contrast, $saturation); | ||
| 671 | } | ||
| 672 | if($pca_noise > 0) | ||
| 673 | { | ||
| 674 | my $eigval = AI::MXNet::NDArray->array([55.46, 4.794, 1.148])->aspdl; | ||
| 675 | my $eigvec = AI::MXNet::NDArray->array([[-0.5675, 0.7192, 0.4009], | ||
| 676 | [-0.5808, -0.0045, -0.8140], | ||
| 677 | [-0.5836, -0.6948, 0.4203]])->aspdl; | ||
| 678 | push @auglist, __PACKAGE__->LightingAug($pca_noise, $eigval, $eigvec); | ||
| 679 | } | ||
| 680 | |||
| 681 | if($mean) | ||
| 682 | { | ||
| 683 | $mean = AI::MXNet::NDArray->array([123.68, 116.28, 103.53])->aspdl; | ||
| 684 | } | ||
| 685 | if($std) | ||
| 686 | { | ||
| 687 | $std = AI::MXNet::NDArray->array([58.395, 57.12, 57.375])->aspdl; | ||
| 688 | } | ||
| 689 | if(defined $mean) | ||
| 690 | { | ||
| 691 | assert(defined $std); | ||
| 692 | push @auglist, __PACKAGE__->ColorNormalizeAug($mean, $std); | ||
| 693 | } | ||
| 694 | |||
| 695 | return \@auglist; | ||
| 696 | } | ||
| 697 | |||
| 698 | method imresize(AI::MXNet::NDArray $src, Int $w, Int $h, Int $interp=2) | ||
| 699 | { | ||
| 700 | return AI::MXNet::NDArray->_cvimresize($src, int $w, int $h, { interp=>$interp }); | ||
| 701 | } | ||
| 702 | |||
| 703 | method ImageIter(@args) { AI::MXNet::ImageIter->new(@args) } | ||
| 704 | |||
| 705 | package AI::MXNet::ImageIter; | ||
| 706 | use Mouse; | ||
| 707 | use AI::MXNet::Base; | ||
| 708 | extends 'AI::MXNet::DataIter'; | ||
| 709 | |||
| 710 | =head1 NAME | ||
| 711 | |||
| 712 | AI::MXNet::ImageIter - Image data iterator. | ||
| 713 | =cut | ||
| 714 | |||
| 715 | =head1 DESCRIPTION | ||
| 716 | |||
| 717 | |||
| 718 | Image data iterator with a large number of augumentation choices. | ||
| 719 | Supports reading from both .rec files and raw image files with image list. | ||
| 720 | |||
| 721 | To load from .rec files, please specify path_imgrec. Also specify path_imgidx | ||
| 722 | to use data partition (for distributed training) or shuffling. | ||
| 723 | |||
| 724 | To load from raw image files, specify path_imglist and path_root. | ||
| 725 | |||
| 726 | Parameters | ||
| 727 | ---------- | ||
| 728 | batch_size : Int | ||
| 729 | Number of examples per batch | ||
| 730 | data_shape : Shape | ||
| 731 | Data shape in (channels, height, width). | ||
| 732 | For now, only RGB image with 3 channels is supported. | ||
| 733 | label_width : Int | ||
| 734 | dimension of label | ||
| 735 | path_imgrec : str | ||
| 736 | path to image record file (.rec). | ||
| 737 | Created with tools/im2rec.py or bin/im2rec | ||
| 738 | path_imglist : str | ||
| 739 | path to image list (.lst) | ||
| 740 | Created with tools/im2rec.py or with custom script. | ||
| 741 | Format: index\t[one or more label separated by \t]\trelative_path_from_root | ||
| 742 | imglist: array ref | ||
| 743 | a list of image with the label(s) | ||
| 744 | each item is a list [imagelabel: float or array ref of float, imgpath] | ||
| 745 | path_root : str | ||
| 746 | Root folder of image files | ||
| 747 | path_imgidx : str | ||
| 748 | Path to image index file. Needed for partition and shuffling when using .rec source. | ||
| 749 | shuffle : bool | ||
| 750 | Whether to shuffle all images at the start of each iteration. | ||
| 751 | Can be slow for HDD. | ||
| 752 | part_index : int | ||
| 753 | Partition index | ||
| 754 | num_parts : int | ||
| 755 | Total number of partitions. | ||
| 756 | data_name='data' Str | ||
| 757 | label_name='softmax_label' Str | ||
| 758 | kwargs : hash ref with any additional arguments for augmenters | ||
| 759 | =cut | ||
| 760 | |||
| 761 | has 'batch_size' => (is => 'ro', isa => 'Int', required => 1); | ||
| 762 | has 'data_shape' => (is => 'ro', isa => 'Shape', required => 1); | ||
| 763 | has 'label_width' => (is => 'ro', isa => 'Int', default => 1); | ||
| 764 | has 'data_name' => (is => 'ro', isa => 'Str', default => 'data'); | ||
| 765 | has 'label_name' => (is => 'ro', isa => 'Str', default => 'softmax_label'); | ||
| 766 | has [qw/path_imgrec | ||
| 767 | path_imglist | ||
| 768 | path_root | ||
| 769 | path_imgidx | ||
| 770 | /] => (is => 'ro', isa => 'Str'); | ||
| 771 | has 'shuffle' => (is => 'ro', isa => 'Bool', default => 0); | ||
| 772 | has 'part_index' => (is => 'ro', isa => 'Int', default => 0); | ||
| 773 | has 'num_parts' => (is => 'ro', isa => 'Int', default => 0); | ||
| 774 | has 'aug_list' => (is => 'rw', isa => 'ArrayRef[CodeRef]'); | ||
| 775 | has 'imglist' => (is => 'rw', isa => 'ArrayRef|HashRef'); | ||
| 776 | has 'kwargs' => (is => 'ro', isa => 'HashRef'); | ||
| 777 | has [qw/imgidx | ||
| 778 | imgrec | ||
| 779 | seq | ||
| 780 | cur | ||
| 781 | provide_data | ||
| 782 | provide_label | ||
| 783 | /] => (is => 'rw', init_arg => undef); | ||
| 784 | |||
| 785 | sub BUILD | ||
| 786 | { | ||
| 787 | my $self = shift; | ||
| 788 | assert($self->path_imgrec or $self->path_imglist or ref $self->imglist eq 'ARRAY'); | ||
| 789 | if($self->path_imgrec) | ||
| 790 | { | ||
| 791 | print("loading recordio...\n"); | ||
| 792 | if($self->path_imgidx) | ||
| 793 | { | ||
| 794 | $self->imgrec( | ||
| 795 | AI::MXNet::IndexedRecordIO->new( | ||
| 796 | idx_path => $self->path_imgidx, | ||
| 797 | uri => $self->path_imgrec, | ||
| 798 | flag => 'r' | ||
| 799 | ) | ||
| 800 | ); | ||
| 801 | $self->imgidx([@{ $self->imgrec->keys }]); | ||
| 802 | } | ||
| 803 | else | ||
| 804 | { | ||
| 805 | $self->imgrec(AI::MXNet::RecordIO->new(uri => $self->path_imgrec, flag => 'r')); | ||
| 806 | } | ||
| 807 | } | ||
| 808 | my %imglist; | ||
| 809 | my @imgkeys; | ||
| 810 | if($self->path_imglist) | ||
| 811 | { | ||
| 812 | print("loading image list...\n"); | ||
| 813 | open(my $f, $self->path_imglist) or confess("can't open ${\ $self->path_imglist } : $!"); | ||
| 814 | while(my $line = <$f>) | ||
| 815 | { | ||
| 816 | chomp($line); | ||
| 817 | my @line = split(/\t/, $line); | ||
| 818 | my $label = AI::MXNet::NDArray->array([@line[1..@line-2]]); | ||
| 819 | my $key = $line[0]; | ||
| 820 | $imglist{$key} = [$label, $line[-1]]; | ||
| 821 | push @imgkeys, $key; | ||
| 822 | } | ||
| 823 | $self->imglist(\%imglist); | ||
| 824 | } | ||
| 825 | elsif(ref $self->imglist eq 'ARRAY') | ||
| 826 | { | ||
| 827 | print("loading image list...\n"); | ||
| 828 | my %result; | ||
| 829 | my $index = 1; | ||
| 830 | for my $img (@{ $self->imglist }) | ||
| 831 | { | ||
| 832 | my $key = $index++; | ||
| 833 | my $label; | ||
| 834 | if(not ref $img->[0]) | ||
| 835 | { | ||
| 836 | $label = AI::MXNet::NDArray->array([$img->[0]]); | ||
| 837 | } | ||
| 838 | else | ||
| 839 | { | ||
| 840 | $label = AI::MXNet::NDArray->array($img->[0]); | ||
| 841 | $result{$key} = [$label, $img->[1]]; | ||
| 842 | push @imgkeys, $key; | ||
| 843 | } | ||
| 844 | } | ||
| 845 | $self->imglist(\%result); | ||
| 846 | } | ||
| 847 | assert(@{ $self->data_shape } == 3 and $self->data_shape->[0] == 3); | ||
| 848 | $self->provide_data([ | ||
| 849 | AI::MXNet::DataDesc->new( | ||
| 850 | name => $self->data_name, | ||
| 851 | shape => [$self->batch_size, @{ $self->data_shape }] | ||
| 852 | ) | ||
| 853 | ]); | ||
| 854 | if($self->label_width > 1) | ||
| 855 | { | ||
| 856 | $self->provide_label([ | ||
| 857 | AI::MXNet::DataDesc->new( | ||
| 858 | name => $self->label_name, | ||
| 859 | shape => [$self->batch_size, $self->label_width] | ||
| 860 | ) | ||
| 861 | ]); | ||
| 862 | } | ||
| 863 | else | ||
| 864 | { | ||
| 865 | $self->provide_label([ | ||
| 866 | AI::MXNet::DataDesc->new( | ||
| 867 | name => $self->label_name, | ||
| 868 | shape => [$self->batch_size] | ||
| 869 | ) | ||
| 870 | ]); | ||
| 871 | } | ||
| 872 | if(not defined $self->imgrec) | ||
| 873 | { | ||
| 874 | $self->seq(\@imgkeys); | ||
| 875 | } | ||
| 876 | elsif($self->shuffle or $self->num_parts > 1) | ||
| 877 | { | ||
| 878 | assert(defined $self->imgidx); | ||
| 879 | $self->seq($self->imgidx); | ||
| 880 | } | ||
| 881 | if($self->num_parts > 1) | ||
| 882 | { | ||
| 883 | assert($self->part_index < $self->num_parts); | ||
| 884 | my $N = @{ $self->seq }; | ||
| 885 | my $C = $N/$self->num_parts; | ||
| 886 | $self->seq([@{ $self->seq }[$self->part_index*$C..($self->part_index+1)*$C-1]]); | ||
| 887 | } | ||
| 888 | if(defined $self->aug_list or defined $self->kwargs) | ||
| 889 | { | ||
| 890 | $self->aug_list(AI::MXNet::Image->CreateAugmenter(data_shape => $self->data_shape, %{ $self->kwargs//{} })); | ||
| 891 | } | ||
| 892 | else | ||
| 893 | { | ||
| 894 | $self->aug_list([]); | ||
| 895 | } | ||
| 896 | $self->cur(0); | ||
| 897 | $self->reset(); | ||
| 898 | } | ||
| 899 | |||
| 900 | method reset() | ||
| 901 | { | ||
| 902 | if($self->shuffle) | ||
| 903 | { | ||
| 904 | @{ $self->seq } = List::Util::shuffle(@{ $self->seq }); | ||
| 905 | } | ||
| 906 | if(defined $self->imgrec) | ||
| 907 | { | ||
| 908 | $self->imgrec->reset; | ||
| 909 | } | ||
| 910 | $self->cur(0); | ||
| 911 | } | ||
| 912 | |||
| 913 | method next_sample() | ||
| 914 | { | ||
| 915 | if(defined $self->seq) | ||
| 916 | { | ||
| 917 | return undef if($self->cur >= @{ $self->seq }); | ||
| 918 | my $idx = $self->seq->[$self->cur]; | ||
| 919 | $self->cur($self->cur + 1); | ||
| 920 | if(defined $self->imgrec) | ||
| 921 | { | ||
| 922 | my $s = $self->imgrec->read_idx($idx); | ||
| 923 | my ($header, $img) = AI::MXNet::RecordIO->unpack($s); | ||
| 924 | if(not defined $self->imglist) | ||
| 925 | { | ||
| 926 | return ($header->label, $img); | ||
| 927 | } | ||
| 928 | else | ||
| 929 | { | ||
| 930 | return ($self->imglist->{$idx}[0], $img); | ||
| 931 | } | ||
| 932 | } | ||
| 933 | else | ||
| 934 | { | ||
| 935 | my ($label, $fname) = @{ $self->imglist->{$idx} }; | ||
| 936 | if(not defined $self->imgrec) | ||
| 937 | { | ||
| 938 | open(F, $self->path_root . "/$fname") or confess("can't open $fname $!"); | ||
| 939 | my $img; | ||
| 940 | { local $/ = undef; $img = <F> }; | ||
| 941 | close(F); | ||
| 942 | return ($label, $img); | ||
| 943 | } | ||
| 944 | } | ||
| 945 | } | ||
| 946 | else | ||
| 947 | { | ||
| 948 | my $s = $self->imgrec->read; | ||
| 949 | return undef if(not defined $s); | ||
| 950 | my ($header, $img) = AI::MXNet::RecordIO->unpack($s); | ||
| 951 | return ($header->label, $img) | ||
| 952 | } | ||
| 953 | } | ||
| 954 | |||
| 955 | method next() | ||
| 956 | { | ||
| 957 | my $batch_size = $self->batch_size; | ||
| 958 | my ($c, $h, $w) = @{ $self->data_shape }; | ||
| 959 | my $batch_data = AI::MXNet::NDArray->empty([$batch_size, $c, $h, $w]); | ||
| 960 | my $batch_label = AI::MXNet::NDArray->empty(@{$self->provide_label->[0]}[1]); | ||
| 961 | my $i = 0; | ||
| 962 | while ($i < $batch_size) | ||
| 963 | { | ||
| 964 | my ($label, $s) = $self->next_sample; | ||
| 965 | last if not defined $label; | ||
| 966 | my $data = [AI::MXNet::Image->imdecode($s)]; | ||
| 967 | if(@{ $data->[0]->shape } == 0) | ||
| 968 | { | ||
| 969 | AI::MXNet::Logging->debug('Invalid image, skipping.'); | ||
| 970 | next; | ||
| 971 | } | ||
| 972 | for my $aug (@{ $self->aug_list }) | ||
| 973 | { | ||
| 974 | $data = [map { @{ $aug->($_) } } @$data]; | ||
| 975 | } | ||
| 976 | for my $d (@$data) | ||
| 977 | { | ||
| 978 | assert(($i < $batch_size), 'Batch size must be multiples of augmenter output length'); | ||
| 979 | $batch_data->at($i) .= AI::MXNet::NDArray->transpose($d, { axes=>[2, 0, 1] }); | ||
| 980 | $batch_label->at($i) .= $label; | ||
| 981 | $i++; | ||
| 982 | } | ||
| 983 | } | ||
| 984 | return undef if not $i; | ||
| 985 | return AI::MXNet::DataBatch->new(data=>[$batch_data], label=>[$batch_label], pad => $batch_size-$i); | ||
| 986 | } | ||
| 987 | |||
| 988 | package AI::MXNet::Image; | ||
| 989 | sub sym { 'AI::MXNet::Image::Symbol' } | ||
| 990 | sub symbol { 'AI::MXNet::Image::Symbol' } | ||
| 991 | sub nd { 'AI::MXNet::Image::NDArray' } | ||
| 992 | sub ndarray { 'AI::MXNet::Image::NDArray' } | ||
| 993 | |||
| 994 | 1; |