mindspore.dataset.ImageFolderDataset

View Source On Gitee
class mindspore.dataset.ImageFolderDataset(dataset_dir, num_samples=None, num_parallel_workers=None, shuffle=None, sampler=None, extensions=None, class_indexing=None, decode=False, num_shards=None, shard_id=None, cache=None, decrypt=None)[source]

A source dataset that reads images from a tree of directories. All images within one folder have the same label.

The generated dataset has two columns: [image, label] . The tensor of column image is of the uint8 type. The tensor of column label is of a scalar of uint32 type.

Parameters
  • dataset_dir (str) – Path to the root directory that contains the dataset.

  • num_samples (int, optional) – The number of images to be included in the dataset. Default: None , all images.

  • num_parallel_workers (int, optional) – Number of worker threads to read the data. Default: None , will use global default workers(8), it can be set by mindspore.dataset.config.set_num_parallel_workers() .

  • shuffle (bool, optional) – Whether or not to perform shuffle on the dataset. Default: None , expected order behavior shown in the table below.

  • sampler (Sampler, optional) – Object used to choose samples from the dataset. Default: None , expected order behavior shown in the table below.

  • extensions (list[str], optional) – List of file extensions to be included in the dataset. Default: None .

  • class_indexing (dict, optional) – A str-to-int mapping from folder name to index Default: None , the folder names will be sorted alphabetically and each class will be given a unique index starting from 0.

  • decode (bool, optional) – Decode the images after reading. Default: False.

  • num_shards (int, optional) – Number of shards that the dataset will be divided into. Default: None . When this argument is specified, num_samples reflects the maximum sample number of per shard.

  • shard_id (int, optional) – The shard ID within num_shards . Default: None . This argument can only be specified when num_shards is also specified.

  • cache (DatasetCache, optional) – Use tensor caching service to speed up dataset processing. More details: Single-Node Data Cache . Default: None , which means no cache is used.

  • decrypt (callable, optional) – Image decryption function, which accepts the path of the encrypted image file and returns the decrypted bytes data. Default: None , no decryption.

Raises
  • RuntimeError – If dataset_dir does not contain data files.

  • ValueError – If num_parallel_workers exceeds the max thread numbers.

  • RuntimeError – If sampler and shuffle are specified at the same time.

  • RuntimeError – If sampler and num_shards/shard_id are specified at the same time.

  • RuntimeError – If num_shards is specified but shard_id is None.

  • RuntimeError – If shard_id is specified but num_shards is None.

  • RuntimeError – If class_indexing is not a dictionary.

  • ValueError – If shard_id is not in range of [0, num_shards ).

Tutorial Examples:

Note

  • The shape of the image column is [image_size] if decode flag is False, or [H,W,C] otherwise.

  • The parameters num_samples , shuffle , num_shards , shard_id can be used to control the sampler used in the dataset, and their effects when combined with parameter sampler are as follows.

Sampler obtained by different combinations of parameters sampler and num_samples , shuffle , num_shards , shard_id

Parameter sampler

Parameter num_shards / shard_id

Parameter shuffle

Parameter num_samples

Sampler Used

mindspore.dataset.Sampler type

None

None

None

sampler

numpy.ndarray,list,tuple,int type

/

/

num_samples

SubsetSampler(indices = sampler , num_samples = num_samples )

iterable type

/

/

num_samples

IterSampler(sampler = sampler , num_samples = num_samples )

None

num_shards / shard_id

None / True

num_samples

DistributedSampler(num_shards = num_shards , shard_id = shard_id , shuffle = True , num_samples = num_samples )

None

num_shards / shard_id

False

num_samples

DistributedSampler(num_shards = num_shards , shard_id = shard_id , shuffle = False , num_samples = num_samples )

None

None

None / True

None

RandomSampler(num_samples = num_samples )

None

None

None / True

num_samples

RandomSampler(replacement = True , num_samples = num_samples )

None

None

False

num_samples

SequentialSampler(num_samples = num_samples )

Examples

>>> import mindspore.dataset as ds
>>> image_folder_dataset_dir = "/path/to/image_folder_dataset_directory"
>>>
>>> # 1) Read all samples (image files) in image_folder_dataset_dir with 8 threads
>>> dataset = ds.ImageFolderDataset(dataset_dir=image_folder_dataset_dir,
...                                 num_parallel_workers=8)
>>>
>>> # 2) Read all samples (image files) from folder cat and folder dog with label 0 and 1
>>> dataset = ds.ImageFolderDataset(dataset_dir=image_folder_dataset_dir,
...                                 class_indexing={"cat":0, "dog":1})
>>>
>>> # 3) Read all samples (image files) in image_folder_dataset_dir with extensions .JPEG
>>> #    and .png (case sensitive)
>>> dataset = ds.ImageFolderDataset(dataset_dir=image_folder_dataset_dir,
...                                 extensions=[".JPEG", ".png"])

About ImageFolderDataset:

You can construct the following directory structure from your dataset files and read by MindSpore’s API.

.
└── image_folder_dataset_directory
     ├── class1
     │    ├── 000000000001.jpg
     │    ├── 000000000002.jpg
     │    ├── ...
     ├── class2
     │    ├── 000000000001.jpg
     │    ├── 000000000002.jpg
     │    ├── ...
     ├── class3
     │    ├── 000000000001.jpg
     │    ├── 000000000002.jpg
     │    ├── ...
     ├── classN
     ├── ...

Pre-processing Operation

mindspore.dataset.Dataset.apply

Apply a function in this dataset.

mindspore.dataset.Dataset.concat

Concatenate the dataset objects in the input list.

mindspore.dataset.Dataset.filter

Filter dataset by prediction.

mindspore.dataset.Dataset.flat_map

Map func to each row in dataset and flatten the result.

mindspore.dataset.Dataset.map

Apply each operation in operations to this dataset.

mindspore.dataset.Dataset.project

The specified columns will be selected from the dataset and passed into the pipeline with the order specified.

mindspore.dataset.Dataset.rename

Rename the columns in input datasets.

mindspore.dataset.Dataset.repeat

Repeat this dataset count times.

mindspore.dataset.Dataset.reset

Reset the dataset for next epoch.

mindspore.dataset.Dataset.save

Save the dynamic data processed by the dataset pipeline in common dataset format.

mindspore.dataset.Dataset.shuffle

Shuffle the dataset by creating a cache with the size of buffer_size .

mindspore.dataset.Dataset.skip

Skip the first N elements of this dataset.

mindspore.dataset.Dataset.split

Split the dataset into smaller, non-overlapping datasets.

mindspore.dataset.Dataset.take

Take the first specified number of samples from the dataset.

mindspore.dataset.Dataset.zip

Zip the datasets in the sense of input tuple of datasets.

Batch

mindspore.dataset.Dataset.batch

Combine batch_size number of consecutive rows into batch which apply per_batch_map to the samples first.

mindspore.dataset.Dataset.bucket_batch_by_length

Bucket elements according to their lengths.

mindspore.dataset.Dataset.padded_batch

Combine batch_size number of consecutive rows into batch which apply pad_info to the samples first.

Iterator

mindspore.dataset.Dataset.create_dict_iterator

Create an iterator over the dataset.

mindspore.dataset.Dataset.create_tuple_iterator

Create an iterator over the dataset.

Attribute

mindspore.dataset.Dataset.get_batch_size

Return the size of batch.

mindspore.dataset.Dataset.get_class_indexing

Get the mapping dictionary from category names to category indexes.

mindspore.dataset.Dataset.get_col_names

Return the names of the columns in dataset.

mindspore.dataset.Dataset.get_dataset_size

Return the number of batches in an epoch.

mindspore.dataset.Dataset.get_repeat_count

Get the replication times in RepeatDataset.

mindspore.dataset.Dataset.input_indexs

Get the column index, which represents the corresponding relationship between the data column order and the network when using the sink mode.

mindspore.dataset.Dataset.num_classes

Get the number of classes in a dataset.

mindspore.dataset.Dataset.output_shapes

Get the shapes of output data.

mindspore.dataset.Dataset.output_types

Get the types of output data.

Apply Sampler

mindspore.dataset.MappableDataset.add_sampler

Add a child sampler for the current dataset.

mindspore.dataset.MappableDataset.use_sampler

Replace the last child sampler of the current dataset, remaining the parent sampler unchanged.

Others

mindspore.dataset.Dataset.device_que

Return a transferred Dataset that transfers data through a device.

mindspore.dataset.Dataset.sync_update

Release a blocking condition and trigger callback with given data.

mindspore.dataset.Dataset.sync_wait

Add a blocking condition to the input Dataset and a synchronize action will be applied.

mindspore.dataset.Dataset.to_json

Serialize a pipeline into JSON string and dump into file if filename is provided.