轻量化数据处理

image0image1image2

在资源条件允许的情况下,为了追求更高的性能,一般使用数据管道模式进行数据增强操作。基于数据管道模式执行的最大特点是需要定义map算子,由其负责启动和执行给定的数据增强算子,对数据管道的数据进行映射变换。

import mindspore.dataset.vision.c_transforms as C

random_crop = C.RandomCrop([10, 10])
dataset = dataset1.map(operations=random_crop, input_columns=["image"])

除此之外,MindSpore还提供了一种轻量化数据处理方式,称为Eager模式。在算子的Eager模式下,不需要构建数据管道,因此代码编写会更为简洁且能立即执行得到运行结果,推荐在小型数据增强实验、模型推理等轻量化场景中使用。

使用Eager模式,只需要将数据增强算子本身当成可执行函数使用即可,编写如下代码即可以Eager模式执行数据增强算子。

[1]:
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import mindspore.dataset.vision.c_transforms as C
import mindspore.dataset.vision.py_transforms as P

!wget -N https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/datasets/banana.jpg --no-check-certificate
img_ori = Image.open("banana.jpg").convert("RGB")
print("Image.type: {}, Image.shape: {}".format(type(img_ori), img_ori.size))

# Define a Resize op from c_transform and execute it immediately
op1 = C.Resize(size=(320))
img = op1(img_ori)
print("Image.type: {}, Image.shape: {}".format(type(img), img.shape))

# Define a CenterCrop op from c_transform and execute it immediately
op2 = C.CenterCrop((280, 280))
img = op2(img)
print("Image.type: {}, Image.shape: {}".format(type(img), img.shape))

# Define a Pad op from py_transform and execute it immediately
# Before calling Pad, you need to call ToPIL()
op3 = P.ToPIL()
op4 = P.Pad(40)
img = op4(op3(img))
print("Image.type: {}, Image.shape: {}".format(type(img), img.size))

# Show the result
plt.subplot(1, 2, 1)
plt.imshow(img_ori)
plt.title("original image")
plt.subplot(1, 2, 2)
plt.imshow(img)
plt.title("transformed image")
plt.show()
Image.type: <class 'PIL.Image.Image'>, Image.shape: (356, 200)
Image.type: <class 'numpy.ndarray'>, Image.shape: (320, 570, 3)
Image.type: <class 'numpy.ndarray'>, Image.shape: (280, 280, 3)
Image.type: <class 'PIL.Image.Image'>, Image.shape: (360, 360)
_images/eager_4_1.svg

MindSpore目前支持Eager模式的数据增强算子包括:mindspore.dataset.transformsmindspore.dataset.visionmindspore.dataset.text.transforms