Convert images into TFRecord files

Updated at:

Use the easy_vision_ext data conversion command in Platform for AI (PAI) to convert a labeled image dataset into TFRecord files. PAI training components require TFRecord as their input format, so this conversion is a required step before model training.

When you need this conversion:

  • Your data is labeled with PAI iTAG: iTAG generates a labeled dataset automatically. Run the conversion command to produce TFRecord files from that dataset.

  • Your data is labeled with another platform: First run a PAI command to convert the labeled data into the PAI-compatible labeled dataset format, then run the conversion command.

Run PAI commands using the SQL Script component, the MaxCompute client (odpscmd), or an ODPS SQL node in DataWorks. For details, see MaxCompute client and Develop a MaxCompute SQL task.

Prerequisites

Before you begin, make sure you have:

  • A labeled dataset stored in an Object Storage Service (OSS) bucket (see Overview of labeled dataset format)

  • The OSS path of your label file (oss://your_bucket/xxx.csv)

  • Access to run PAI commands via the SQL Script component, MaxCompute client, or DataWorks

Convert a dataset for image classification

Run the following PAI command to convert a labeled dataset for single-label or multi-label image classification:

pai -name easy_vision_ext
      -Dbuckets='oss://{bucket_name}.{oss_host}/{path}/'
      -Darn='acs:ram::*******:role/aliyunodpspaidefaultrole'
      -DossHost='{oss_host}'
      -Dcmd  convert
      -Dlabel_file 'oss://{bucket_name}/path/to/your/{label_file}'
      -Dconvert_param_config ' --class_list_file oss://{bucket_name}/path/to/your/{class_list_file} --max_image_size 600 --write_parallel_num 8 --num_samples_per_tfrecord 128 --test_ratio 0.1 --model_type CLASSIFICATION'
      -Doutput_tfrecord 'oss://{bucket_name}/path/to/output/data_prefix'
      -Dcluster='{"worker" : {"count" : 1,"cpu" : 800}}'

Replace the placeholders with your actual values:

PlaceholderDescription
{bucket_name}Your OSS bucket name
{oss_host}Your OSS endpoint (for example, oss-ap-southeast-1.aliyuncs.com)
{path}Path prefix within the bucket
{label_file}Filename of your label file
{class_list_file}Filename of your category file

Convert a dataset for text detection or recognition

Run the following PAI command to convert a labeled dataset for text detection or recognition. The example below uses model_type TEXT_END2END for end-to-end optical character recognition (OCR):

pai -name easy_vision_ext
      -Dbuckets='oss://{bucket_name}.{oss_host}/{path}/'
      -Darn='acs:ram::*******:role/aliyunodpspaidefaultrole'
      -DossHost='{oss_host}'
      -Dcmd  convert
      -Dlabel_file 'oss://{bucket_name}/path/to/your/{label_file}'
      -Dconvert_param_config '--model_type TEXT_END2END --default_class text --max_image_size 2000 --char_replace_map_path oss://{bucket_name}/path/to/your_char_replace_map --default_char_dict_path oss://{bucket_name}/path/to/your_char_dict --test_ratio 0.1 --write_parallel_num 8 --num_samples_per_tfrecord 64'
      -Doutput_tfrecord 'oss://{bucket_name}/test/convert/recipt_text_end2end/data'

This command uses model_type TEXT_END2END. When model_type is set to TEXT_END2END, the following two additional files in OSS take effect:

  • `char_replace_map_path`: A CSV file with two columns (original and replaced) that maps original character strings to replacement strings.

  • `default_char_dict_path`: A text file that maps characters to IDs. Each character occupies one line; the ID equals the line number minus 1.

For single-line text recognition, set --model_type TEXT_RECOGNITION. Both char_replace_map_path and default_char_dict_path also apply to TEXT_RECOGNITION.

PAI command parameters

The following table describes the top-level parameters of the easy_vision_ext command.

ParameterRequiredDescriptionFormatDefault
bucketsNoOSS bucket name. Must end with a forward slash (/). Separate multiple bucket names with commas (,)."oss://bucket_name/?role_arn=xxx&host=yyy"Empty
cmdYesOperation to perform. Set to convert.STRINGconvert
label_fileYesOSS path of the labeled dataset.oss://your_bucket/xxx.csvN/A
convert_param_configNoConversion options. Can also be specified as convert_config.--parama valuea --paramb valueb""
output_tfrecordNoOSS path and file prefix for the output TFRecord files.oss://your_dir/prefix""
clusterNoWorker node configuration for distributed conversion.JSON string{"worker":{"count":3,"cpu":800,"gpu":0,"memory":20000}}

convert_param_config options

The following tables describe the options you can set inside convert_param_config.

Core options

OptionRequiredDescriptionFormatDefault
model_typeYesTarget model type. Determines which additional options apply. See Supported model types for valid values.STRINGN/A
class_list_fileNoOSS path of the category file. The file contains a list of category names. Category names may be presented in the following format: Category name: Name of the mapping category.oss://path/to/your/classlist""
test_ratioNoFraction of data held out for validation. Set to 0 to use all data for training; set to 0.1 to use 10% for validation.FLOAT0.1
max_image_sizeNoMaximum pixel size for the longer side of each image. Images exceeding this limit are resized before being saved to the TFRecord file.INTN/A
max_test_image_sizeNoMaximum pixel size for the longer side of test images. Defaults to the value of max_image_size.INT${max_image_size}
converter_classNoFormat of the input label file. Valid values: pai itag labeling format, pai labeling format(old version), qince labeling format, ssl labeling format.STRINGpai labeling format(old version)
default_classNoDefault category name for objects not listed in the category file.STRINGNone
error_classNoCategory name for invalid objects. Objects in this category are excluded from training.STRINGN/A
ignore_classNoCategory name for detection-only objects. Bounding boxes in this category are excluded from training.STRINGN/A
separatorNoSeparator used by the split() method when dividing the label file into substrings.STRINGN/A
image_formatNoEncoding format for images stored in TFRecord files. Common values: jpg, png, bmp.STRINGjpg
read_parallel_numNoNumber of concurrent reads.INT10
write_parallel_numNoNumber of concurrent writes to TFRecord files.INT1
num_samples_per_tfrecordNoNumber of images stored in each TFRecord file.INT256
user_defined_converter_pathNoHTTP or OSS path of a custom converter script. Example: http://path/to/your/converter.py.STRINGN/A
user_defined_generator_pathNoHTTP or OSS path of a custom generator script. Example: http://path/to/your/generator.py.STRINGN/A
generator_classNoName of the custom generator class.STRINGN/A

Options for OCR model types

These options apply only when model_type is TEXT_END2END or TEXT_RECOGNITION.

OptionRequiredDescriptionFormatDefault
char_replace_map_pathNoOSS path of the CSV file for character map replacement. Contains two columns: original (original strings) and replaced (replacement strings).STRINGN/A
default_char_dict_pathNoOSS path of the character-to-ID mapping file. Each character occupies one line; the ID equals the line number minus 1.STRINGN/A

Options for video classification

These options apply only when model_type is VIDEO_CLASSIFICATION.

OptionRequiredDescriptionFormatDefault
decode_typeNoVideo decoding mode. Valid values: 1 (intra only), 2 (keyframe only), 3 (without bidirectional frames), 4 (decode all).INT4
sample_fpsNoNumber of frames extracted per second for sampling.FLOAT5
reshape_sizeNoOutput frame size in pixels.INT224
decode_batch_sizeNoNumber of frames decoded simultaneously.INT10
decode_keep_sizeNoNumber of overlapping frames between consecutive batches.INT0

Supported model types

The model_type option determines the kind of training data the converted TFRecord files are designed for.

ValueTaskAdditional options required
CLASSIFICATIONSingle-label or multi-label image classificationNone beyond core options
DETECTIONObject detectionNone beyond core options
SEGMENTATIONSemantic image segmentationNone beyond core options
INSTANCE_SEGMENTATIONInstance segmentationNone beyond core options
TEXT_END2ENDEnd-to-end OCRchar_replace_map_path, default_char_dict_path
TEXT_RECOGNITIONSingle-line text recognitionchar_replace_map_path, default_char_dict_path
TEXT_DETECTIONText detectionNone beyond core options
VIDEO_CLASSIFICATIONVideo classificationdecode_type, sample_fps, reshape_size, decode_batch_size, decode_keep_size
SELF_DEFINEDCustom conversionuser_defined_converter_path, user_defined_generator_path, generator_class