targetran


Nametargetran JSON
Version 0.13.2 PyPI version JSON
download
home_pagehttps://github.com/bhky/targetran
SummaryTarget transformation for data augmentation in objection detection
upload_time2025-01-24 09:38:47
maintainerNone
docs_urlNone
authorattr: targetran.__author__
requires_python>=3.8
licenseNone
keywords
VCS
bugtrack_url
requirements keras-cv matplotlib numpy opencv-python pandas tensorflow torch
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ![logo](logo/targetran_logo.png)

[![ci](https://github.com/bhky/targetran/actions/workflows/ci.yml/badge.svg)](https://github.com/bhky/targetran/actions)
[![License MIT 1.0](https://img.shields.io/badge/license-MIT%201.0-blue.svg)](LICENSE)

# Motivation

[Data augmentation](https://en.wikipedia.org/wiki/Data_augmentation) 
is a technique commonly used for training machine learning models in the
computer vision field, where one can increase the amount of image data by
creating transformed copies of the original images.

In the object detection sub-field, the transformation has to be done also
to the target rectangular bounding-boxes. However, such functionality is not 
readily available in frameworks such as TensorFlow and PyTorch.

While there are other powerful augmentation tools available, many of those 
do not work well with the 
[TPU](https://cloud.google.com/tpu)
when accessing from [Google Colab](https://colab.research.google.com/) or 
[Kaggle Notebooks](https://www.kaggle.com/code),
which are popular options nowadays for a lot of people who do not have their
own hardware resources.

Here comes Targetran to fill the gap.

# What is Targetran?

- A light-weight data augmentation library to assist object detection or 
  image classification model training.
- Has simple Python API to transform both the images and the target rectangular 
  bounding-boxes.
- Use dataset-idiomatic approach for TensorFlow and PyTorch.
- Can be used with the TPU for acceleration (TensorFlow Dataset only).

![example](docs/example.png)

(Figure produced by the example code [here](examples/local/run_tf_dataset_local_example.py).)

# Table of contents

- [Installation](#installation)
- [Usage](#usage)
  - [Notations](#notations)
  - [Data format](#data-format)
  - [Design principles](#design-principles)
  - [TensorFlow Dataset](#tensorflow-dataset)
    - [Using with KerasCV](#using-with-kerascv)
  - [PyTorch Dataset](#pytorch-dataset)
  - [Image classification](#image-classification)
- [Examples](#examples)
- [API](#api)

# Installation

Tested for Python 3.9, 3.10, and 3.11.

The best way to install Targetran with its dependencies is from PyPI:
```shell
python3 -m pip install --upgrade targetran
```
Alternatively, to obtain the latest version from this repository:
```shell
git clone https://github.com/bhky/targetran.git
cd targetran
python3 -m pip install .
```

# Usage

## Notations

- `NDFloatArray`: NumPy float array type. The values are converted to `np.float32` internally.
- `tf.Tensor`: General TensorFlow Tensor type. The values are converted to `tf.float32` internally.

## Data format

For object detection model training, which is the primary usage here, the following data are needed.
- `image_seq` (Sequence of `NDFloatArray` or `tf.Tensor` of shape `(height, width, num_channels)`):
  - images in channel-last format;
  - image sizes can be different.
- `bboxes_seq` (Sequence of `NDFloatArray` or `tf.Tensor` of shape `(num_bboxes_per_image, 4)`):
  - each `bboxes` array/tensor provides the bounding-boxes associated with an image;
  - each single bounding-box is given as `[top_left_x, top_left_y, bbox_width, bbox_height]`;
  - empty array/tensor means no bounding-boxes (and labels) for that image.
- `labels_seq` (Sequence of `NDFloatArray` or `tf.Tensor` of shape `(num_bboxes_per_image,)`):
  - each `labels` array/tensor provides the bounding-box labels associated with an image;
  - empty array/tensor means no labels (and bounding-boxes) for that image.

Some dummy data are created below for illustration. Please note the required format.
```python
import numpy as np

# Each image could have different sizes, but they must follow the channel-last format, 
# i.e., (height, width, num_channels).
image_seq = [np.random.rand(480, 512, 3) for _ in range(3)]

# The bounding-boxes (bboxes) are given as a sequence of NumPy arrays (or TF tensors).
# Each array represents the bboxes for one corresponding image.
#
# Each bbox is given as [top_left_x, top_left_y, bbox_width, bbox_height].
# 
# In case an image has no bboxes, an empty array should be provided.
bboxes_seq = [
    np.array([  # Image with 2 bboxes.
        [214, 223, 10, 11],
        [345, 230, 21, 9],
    ]),
    np.array([]),  # Empty array for image with no bboxes.
    np.array([  # Image with 3 bboxes.
        [104, 151, 22, 10],
        [99, 132, 20, 15],
        [340, 220, 31, 12],
    ]),
]

# Labels for the bboxes are also given as a sequence of NumPy arrays (or TF tensors).
# The number of bboxes and labels should match. An empty array indicates no bboxes/labels.
labels_seq = [
    np.array([0, 1]),  # 2 labels.
    np.array([]),  # No labels.
    np.array([2, 3, 0]),  # 3 labels.
]

# During operation, all the data values will be converted to float32.
```

## Design principles

- Bounding-boxes will always be rectangular with sides parallel to the image frame.
- After transformation, each resulting bounding-box is determined by the smallest 
  rectangle (with sides parallel to the image frame) enclosing the original transformed bounding-box.
- After transformation, resulting bounding-boxes with their centroids outside the 
  image frame will be removed, together with the corresponding labels.

## TensorFlow Dataset

```python
import tensorflow as tf

from targetran.tf import (
  to_tf_dataset,
  TFCombineAffine,
  TFRandomFlipLeftRight,
  TFRandomFlipUpDown,
  TFRandomRotate,
  TFRandomShear,
  TFRandomTranslate,
  TFRandomCrop,
  TFResize,
)

# Convert the above data sequences into a TensorFlow Dataset.
# Users can have their own way to create the Dataset, as long as for each iteration 
# it returns a tuple of tensors for a single example: (image, bboxes, labels).
ds = to_tf_dataset(image_seq, bboxes_seq, labels_seq)

# Alternatively, users can provide a sequence of image paths instead of image tensors/arrays,
# and set `image_seq_is_paths=True`. In that case, the actual image loading will be done during
# the dataset operation (i.e., lazy-loading). This is useful when dealing with huge data.
ds = to_tf_dataset(image_paths, bboxes_seq, labels_seq, image_seq_is_paths=True)

# The affine transformations can be combined into one operation for better performance.
# Note that cropping and resizing are not affine and cannot be combined.
# Option (1):
affine_transform = TFCombineAffine(
  [TFRandomRotate(probability=0.8),  # Probability to include each affine transformation step 
   TFRandomShear(probability=0.6),  # can be specified, otherwise the default value is used.
   TFRandomTranslate(),  # Thus, the number of selected steps could vary.
   TFRandomFlipLeftRight(),
   TFRandomFlipUpDown()],
  probability=1.0  # Probability to apply this single combined transformation.
)
# Option (2):
# Alternatively, one can decide the exact number of randomly selected transformations,
# e.g., use only any two of them. This could be a better option because too many 
# transformation steps may deform the images too much.
affine_transform = TFCombineAffine(
  [TFRandomRotate(),  # Individual `probability` has no effect in this approach.
   TFRandomShear(),
   TFRandomTranslate(),
   TFRandomFlipLeftRight(),
   TFRandomFlipUpDown()],
  num_selected_transforms=2,  # Only two steps from the list will be selected.
  selected_probabilities=[0.5, 0.0, 0.3, 0.2, 0.0],  # Must sum up to 1.0, if given.
  keep_order=True,  # If True, the selected steps must be performed in the given order.
  probability=1.0  # Probability to apply this single combined transformation.
)
# Please refer to the API manual for more parameter options.

# Apply transformations.
auto_tune = tf.data.AUTOTUNE
ds = (
  ds
  .map(TFRandomCrop(probability=0.5), num_parallel_calls=auto_tune)
  .map(affine_transform, num_parallel_calls=auto_tune)
  .map(TFResize((256, 256)), num_parallel_calls=auto_tune)
)

# In the Dataset `map` call, the parameter `num_parallel_calls` can be set to,
# e.g., tf.data.AUTOTUNE, for better performance. See docs for TensorFlow Dataset.
```
```python
# Batching:
# Since the array/tensor shape of each example could be different, conventional
# way of batching may not work. Users will have to consider their own use cases.
# One possibly useful way is the padded-batch.
ds = ds.padded_batch(batch_size=2, padding_values=-1.0)
```

### Using with KerasCV
The [KerasCV](https://keras.io/keras_cv/) API is a little bit confusing 
in terms of its input data format. The requirement is different between
a preprocessing layer and a model.

Targetran provides easy conversion tools to make the process smoother.
```python
import keras_cv
from targetran.tf import to_keras_cv_dict, to_keras_cv_model_input

# Let's assume `ds` contains Targetran ops as in the above illustration, without batching.
# To map the outputs to a KerasCV preprocessing layer, the following can be done.
ds = to_keras_cv_dict(ds, batch_size=2)

# The resulting dataset yields batches readily to be passed to a KerasCV preprocessing layer.
# Batching in the appropriate format will be included, therefore the `padded_batch` example
# is not relevant here.

# Assume the user would like to add a jittered-resize op.
jittered_resize = keras_cv.layers.JitteredResize(
    target_size=(640, 640),
    scale_factor=(0.8, 1.25),
    bounding_box_format="xywh",
)

ds = ds.map(jittered_resize) # Other KerasCV preprocessing layers can be added subsequently.

# When the data is about to be passed to a KerasCV `model.fit`, the following can be done.
ds = to_keras_cv_model_input(ds)
```

## PyTorch Dataset

```python
from typing import Optional, Sequence, Tuple

import numpy.typing
from torch.utils.data import Dataset

from targetran.np import (
    CombineAffine,
    RandomFlipLeftRight,
    RandomFlipUpDown,
    RandomRotate,
    RandomShear,
    RandomTranslate,
    RandomCrop,
    Resize,
)
from targetran.utils import Compose

NDFloatArray = numpy.typing.NDArray[numpy.float_]


class PTDataset(Dataset):
    """
    A very simple PyTorch Dataset.
    As per common practice, transforms are done on NumPy arrays.
    """
    
    def __init__(
            self,
            image_seq: Sequence[NDFloatArray],
            bboxes_seq: Sequence[NDFloatArray],
            labels_seq: Sequence[NDFloatArray],
            transforms: Optional[Compose]
    ) -> None:
        # It is also possible to provide image paths instead of image arrays here,
        # and load the image in __getitem__. The details are skipped in this example.
        self.image_seq = image_seq
        self.bboxes_seq = bboxes_seq
        self.labels_seq = labels_seq
        self.transforms = transforms

    def __len__(self) -> int:
        return len(self.image_seq)

    def __getitem__(
            self,
            idx: int
    ) -> Tuple[NDFloatArray, NDFloatArray, NDFloatArray]:
        if self.transforms:
            return self.transforms(
                self.image_seq[idx],
                self.bboxes_seq[idx],
                self.labels_seq[idx]
            )
        return (
            self.image_seq[idx],
            self.bboxes_seq[idx],
            self.labels_seq[idx]
        )


# The affine transformations can be combined into one operation for better performance.
# Note that cropping and resizing are not affine and cannot be combined.
# Option (1):
affine_transform = CombineAffine(
    [RandomRotate(probability=0.8),  # Probability to include each affine transformation step 
     RandomShear(probability=0.6),   # can be specified, otherwise the default value is used.
     RandomTranslate(),              # Thus, the number of selected steps could vary.
     RandomFlipLeftRight(),
     RandomFlipUpDown()],
    probability=1.0  # Probability to apply this single combined transformation.
)
# Option (2):
# Alternatively, one can decide the exact number of randomly selected transformations,
# e.g., use only any two of them. This could be a better option because too many 
# transformation steps may deform the images too much.
affine_transform = CombineAffine(
    [RandomRotate(),  # Individual `probability` has no effect in this approach.
     RandomShear(),
     RandomTranslate(),
     RandomFlipLeftRight(),
     RandomFlipUpDown()],
    num_selected_transforms=2,  # Only two steps from the list will be selected.
    selected_probabilities=[0.5, 0.0, 0.3, 0.2, 0.0],  # Must sum up to 1.0, if given.
    keep_order=True,  # If True, the selected steps must be performed in the given order.
    probability=1.0  # Probability to apply this single combined transformation.
)
# Please refer to the API manual for more parameter options.

# The `Compose` here is similar to that from the torchvision package, except 
# that here it also supports callables with multiple inputs and outputs needed
# for objection detection tasks, i.e., (image, bboxes, labels).
transforms = Compose([
    RandomCrop(probability=0.5),
    affine_transform,
    Resize((256, 256)),
])

# Convert the above data sequences into a PyTorch Dataset.
# Users can have their own way to create the Dataset, as long as for each iteration 
# it returns a tuple of arrays for a single example: (image, bboxes, labels).
ds = PTDataset(image_seq, bboxes_seq, labels_seq, transforms=transforms)
```
```python
# Batching:
# In PyTorch, it is common to use a Dataset with a DataLoader, which provides
# batching functionality. However, since the array/tensor shape of each example 
# could be different, the default batching may not work. Targetran provides
# a `collate_fn` that helps producing batches of (image_seq, bboxes_seq, labels_seq).
from torch.utils.data import DataLoader
from targetran.utils import collate_fn

data_loader = DataLoader(ds, batch_size=2, collate_fn=collate_fn)
```

## Image classification

While the tools here are primarily designed for object detection tasks, they can 
also be used for image classification in which only the images are to be transformed,
e.g., given a dataset that returns `(image, label)` examples, or even only `image` examples. 
The `image_only` function can be used to convert a transformation class for this purpose.

If the dataset returns a tuple `(image, ...)` in each iteration, only the `image`
will be transformed, other parameters that followed such as `(..., label, weight)` 
will be returned untouched.

If the dataset returns `image` only (not a tuple), then only the transformed `image` will be returned. 
```python
from targetran.utils import image_only
```
```python
# TensorFlow.
ds = to_tf_dataset(image_seq)

ds = (
  ds
  .map(image_only(TFRandomCrop()))
  .map(image_only(affine_transform))
  .map(image_only(TFResize((256, 256))))
  .batch(32)  # Conventional batching can be used for classification setup.
)
```
```python
# PyTorch.
transforms = Compose([
    image_only(RandomCrop()),
    image_only(affine_transform),
    image_only(Resize((256, 256))),
])
ds = PTDataset(..., transforms=transforms)
data_loader = DataLoader(ds, batch_size=32)
```

# Examples

- [Code examples in this repository](examples) 
- [Construct a TensorFlow Dataset with Targetran 
   and object detection data](https://www.kaggle.com/boscoyung/targetran-example-with-tensorflow-dataset) 
  (Kaggle Notebook)
- [Image classification with TensorFlow and Targetran on TPU](https://www.kaggle.com/boscoyung/targetran-tpu-for-image-classification-example)
  (Kaggle Notebook)

# API

See [here](docs/API.md) for API details.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/bhky/targetran",
    "name": "targetran",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "attr: targetran.__author__",
    "author_email": "bhky.dev@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/0d/c2/f649a2f8844089d8dcac34c5b764562252735d64ff7a6c559573f207b19f/targetran-0.13.2.tar.gz",
    "platform": null,
    "description": "![logo](logo/targetran_logo.png)\n\n[![ci](https://github.com/bhky/targetran/actions/workflows/ci.yml/badge.svg)](https://github.com/bhky/targetran/actions)\n[![License MIT 1.0](https://img.shields.io/badge/license-MIT%201.0-blue.svg)](LICENSE)\n\n# Motivation\n\n[Data augmentation](https://en.wikipedia.org/wiki/Data_augmentation) \nis a technique commonly used for training machine learning models in the\ncomputer vision field, where one can increase the amount of image data by\ncreating transformed copies of the original images.\n\nIn the object detection sub-field, the transformation has to be done also\nto the target rectangular bounding-boxes. However, such functionality is not \nreadily available in frameworks such as TensorFlow and PyTorch.\n\nWhile there are other powerful augmentation tools available, many of those \ndo not work well with the \n[TPU](https://cloud.google.com/tpu)\nwhen accessing from [Google Colab](https://colab.research.google.com/) or \n[Kaggle Notebooks](https://www.kaggle.com/code),\nwhich are popular options nowadays for a lot of people who do not have their\nown hardware resources.\n\nHere comes Targetran to fill the gap.\n\n# What is Targetran?\n\n- A light-weight data augmentation library to assist object detection or \n  image classification model training.\n- Has simple Python API to transform both the images and the target rectangular \n  bounding-boxes.\n- Use dataset-idiomatic approach for TensorFlow and PyTorch.\n- Can be used with the TPU for acceleration (TensorFlow Dataset only).\n\n![example](docs/example.png)\n\n(Figure produced by the example code [here](examples/local/run_tf_dataset_local_example.py).)\n\n# Table of contents\n\n- [Installation](#installation)\n- [Usage](#usage)\n  - [Notations](#notations)\n  - [Data format](#data-format)\n  - [Design principles](#design-principles)\n  - [TensorFlow Dataset](#tensorflow-dataset)\n    - [Using with KerasCV](#using-with-kerascv)\n  - [PyTorch Dataset](#pytorch-dataset)\n  - [Image classification](#image-classification)\n- [Examples](#examples)\n- [API](#api)\n\n# Installation\n\nTested for Python 3.9, 3.10, and 3.11.\n\nThe best way to install Targetran with its dependencies is from PyPI:\n```shell\npython3 -m pip install --upgrade targetran\n```\nAlternatively, to obtain the latest version from this repository:\n```shell\ngit clone https://github.com/bhky/targetran.git\ncd targetran\npython3 -m pip install .\n```\n\n# Usage\n\n## Notations\n\n- `NDFloatArray`: NumPy float array type. The values are converted to `np.float32` internally.\n- `tf.Tensor`: General TensorFlow Tensor type. The values are converted to `tf.float32` internally.\n\n## Data format\n\nFor object detection model training, which is the primary usage here, the following data are needed.\n- `image_seq` (Sequence of `NDFloatArray` or `tf.Tensor` of shape `(height, width, num_channels)`):\n  - images in channel-last format;\n  - image sizes can be different.\n- `bboxes_seq` (Sequence of `NDFloatArray` or `tf.Tensor` of shape `(num_bboxes_per_image, 4)`):\n  - each `bboxes` array/tensor provides the bounding-boxes associated with an image;\n  - each single bounding-box is given as `[top_left_x, top_left_y, bbox_width, bbox_height]`;\n  - empty array/tensor means no bounding-boxes (and labels) for that image.\n- `labels_seq` (Sequence of `NDFloatArray` or `tf.Tensor` of shape `(num_bboxes_per_image,)`):\n  - each `labels` array/tensor provides the bounding-box labels associated with an image;\n  - empty array/tensor means no labels (and bounding-boxes) for that image.\n\nSome dummy data are created below for illustration. Please note the required format.\n```python\nimport numpy as np\n\n# Each image could have different sizes, but they must follow the channel-last format, \n# i.e., (height, width, num_channels).\nimage_seq = [np.random.rand(480, 512, 3) for _ in range(3)]\n\n# The bounding-boxes (bboxes) are given as a sequence of NumPy arrays (or TF tensors).\n# Each array represents the bboxes for one corresponding image.\n#\n# Each bbox is given as [top_left_x, top_left_y, bbox_width, bbox_height].\n# \n# In case an image has no bboxes, an empty array should be provided.\nbboxes_seq = [\n    np.array([  # Image with 2 bboxes.\n        [214, 223, 10, 11],\n        [345, 230, 21, 9],\n    ]),\n    np.array([]),  # Empty array for image with no bboxes.\n    np.array([  # Image with 3 bboxes.\n        [104, 151, 22, 10],\n        [99, 132, 20, 15],\n        [340, 220, 31, 12],\n    ]),\n]\n\n# Labels for the bboxes are also given as a sequence of NumPy arrays (or TF tensors).\n# The number of bboxes and labels should match. An empty array indicates no bboxes/labels.\nlabels_seq = [\n    np.array([0, 1]),  # 2 labels.\n    np.array([]),  # No labels.\n    np.array([2, 3, 0]),  # 3 labels.\n]\n\n# During operation, all the data values will be converted to float32.\n```\n\n## Design principles\n\n- Bounding-boxes will always be rectangular with sides parallel to the image frame.\n- After transformation, each resulting bounding-box is determined by the smallest \n  rectangle (with sides parallel to the image frame) enclosing the original transformed bounding-box.\n- After transformation, resulting bounding-boxes with their centroids outside the \n  image frame will be removed, together with the corresponding labels.\n\n## TensorFlow Dataset\n\n```python\nimport tensorflow as tf\n\nfrom targetran.tf import (\n  to_tf_dataset,\n  TFCombineAffine,\n  TFRandomFlipLeftRight,\n  TFRandomFlipUpDown,\n  TFRandomRotate,\n  TFRandomShear,\n  TFRandomTranslate,\n  TFRandomCrop,\n  TFResize,\n)\n\n# Convert the above data sequences into a TensorFlow Dataset.\n# Users can have their own way to create the Dataset, as long as for each iteration \n# it returns a tuple of tensors for a single example: (image, bboxes, labels).\nds = to_tf_dataset(image_seq, bboxes_seq, labels_seq)\n\n# Alternatively, users can provide a sequence of image paths instead of image tensors/arrays,\n# and set `image_seq_is_paths=True`. In that case, the actual image loading will be done during\n# the dataset operation (i.e., lazy-loading). This is useful when dealing with huge data.\nds = to_tf_dataset(image_paths, bboxes_seq, labels_seq, image_seq_is_paths=True)\n\n# The affine transformations can be combined into one operation for better performance.\n# Note that cropping and resizing are not affine and cannot be combined.\n# Option (1):\naffine_transform = TFCombineAffine(\n  [TFRandomRotate(probability=0.8),  # Probability to include each affine transformation step \n   TFRandomShear(probability=0.6),  # can be specified, otherwise the default value is used.\n   TFRandomTranslate(),  # Thus, the number of selected steps could vary.\n   TFRandomFlipLeftRight(),\n   TFRandomFlipUpDown()],\n  probability=1.0  # Probability to apply this single combined transformation.\n)\n# Option (2):\n# Alternatively, one can decide the exact number of randomly selected transformations,\n# e.g., use only any two of them. This could be a better option because too many \n# transformation steps may deform the images too much.\naffine_transform = TFCombineAffine(\n  [TFRandomRotate(),  # Individual `probability` has no effect in this approach.\n   TFRandomShear(),\n   TFRandomTranslate(),\n   TFRandomFlipLeftRight(),\n   TFRandomFlipUpDown()],\n  num_selected_transforms=2,  # Only two steps from the list will be selected.\n  selected_probabilities=[0.5, 0.0, 0.3, 0.2, 0.0],  # Must sum up to 1.0, if given.\n  keep_order=True,  # If True, the selected steps must be performed in the given order.\n  probability=1.0  # Probability to apply this single combined transformation.\n)\n# Please refer to the API manual for more parameter options.\n\n# Apply transformations.\nauto_tune = tf.data.AUTOTUNE\nds = (\n  ds\n  .map(TFRandomCrop(probability=0.5), num_parallel_calls=auto_tune)\n  .map(affine_transform, num_parallel_calls=auto_tune)\n  .map(TFResize((256, 256)), num_parallel_calls=auto_tune)\n)\n\n# In the Dataset `map` call, the parameter `num_parallel_calls` can be set to,\n# e.g., tf.data.AUTOTUNE, for better performance. See docs for TensorFlow Dataset.\n```\n```python\n# Batching:\n# Since the array/tensor shape of each example could be different, conventional\n# way of batching may not work. Users will have to consider their own use cases.\n# One possibly useful way is the padded-batch.\nds = ds.padded_batch(batch_size=2, padding_values=-1.0)\n```\n\n### Using with KerasCV\nThe [KerasCV](https://keras.io/keras_cv/) API is a little bit confusing \nin terms of its input data format. The requirement is different between\na preprocessing layer and a model.\n\nTargetran provides easy conversion tools to make the process smoother.\n```python\nimport keras_cv\nfrom targetran.tf import to_keras_cv_dict, to_keras_cv_model_input\n\n# Let's assume `ds` contains Targetran ops as in the above illustration, without batching.\n# To map the outputs to a KerasCV preprocessing layer, the following can be done.\nds = to_keras_cv_dict(ds, batch_size=2)\n\n# The resulting dataset yields batches readily to be passed to a KerasCV preprocessing layer.\n# Batching in the appropriate format will be included, therefore the `padded_batch` example\n# is not relevant here.\n\n# Assume the user would like to add a jittered-resize op.\njittered_resize = keras_cv.layers.JitteredResize(\n    target_size=(640, 640),\n    scale_factor=(0.8, 1.25),\n    bounding_box_format=\"xywh\",\n)\n\nds = ds.map(jittered_resize) # Other KerasCV preprocessing layers can be added subsequently.\n\n# When the data is about to be passed to a KerasCV `model.fit`, the following can be done.\nds = to_keras_cv_model_input(ds)\n```\n\n## PyTorch Dataset\n\n```python\nfrom typing import Optional, Sequence, Tuple\n\nimport numpy.typing\nfrom torch.utils.data import Dataset\n\nfrom targetran.np import (\n    CombineAffine,\n    RandomFlipLeftRight,\n    RandomFlipUpDown,\n    RandomRotate,\n    RandomShear,\n    RandomTranslate,\n    RandomCrop,\n    Resize,\n)\nfrom targetran.utils import Compose\n\nNDFloatArray = numpy.typing.NDArray[numpy.float_]\n\n\nclass PTDataset(Dataset):\n    \"\"\"\n    A very simple PyTorch Dataset.\n    As per common practice, transforms are done on NumPy arrays.\n    \"\"\"\n    \n    def __init__(\n            self,\n            image_seq: Sequence[NDFloatArray],\n            bboxes_seq: Sequence[NDFloatArray],\n            labels_seq: Sequence[NDFloatArray],\n            transforms: Optional[Compose]\n    ) -> None:\n        # It is also possible to provide image paths instead of image arrays here,\n        # and load the image in __getitem__. The details are skipped in this example.\n        self.image_seq = image_seq\n        self.bboxes_seq = bboxes_seq\n        self.labels_seq = labels_seq\n        self.transforms = transforms\n\n    def __len__(self) -> int:\n        return len(self.image_seq)\n\n    def __getitem__(\n            self,\n            idx: int\n    ) -> Tuple[NDFloatArray, NDFloatArray, NDFloatArray]:\n        if self.transforms:\n            return self.transforms(\n                self.image_seq[idx],\n                self.bboxes_seq[idx],\n                self.labels_seq[idx]\n            )\n        return (\n            self.image_seq[idx],\n            self.bboxes_seq[idx],\n            self.labels_seq[idx]\n        )\n\n\n# The affine transformations can be combined into one operation for better performance.\n# Note that cropping and resizing are not affine and cannot be combined.\n# Option (1):\naffine_transform = CombineAffine(\n    [RandomRotate(probability=0.8),  # Probability to include each affine transformation step \n     RandomShear(probability=0.6),   # can be specified, otherwise the default value is used.\n     RandomTranslate(),              # Thus, the number of selected steps could vary.\n     RandomFlipLeftRight(),\n     RandomFlipUpDown()],\n    probability=1.0  # Probability to apply this single combined transformation.\n)\n# Option (2):\n# Alternatively, one can decide the exact number of randomly selected transformations,\n# e.g., use only any two of them. This could be a better option because too many \n# transformation steps may deform the images too much.\naffine_transform = CombineAffine(\n    [RandomRotate(),  # Individual `probability` has no effect in this approach.\n     RandomShear(),\n     RandomTranslate(),\n     RandomFlipLeftRight(),\n     RandomFlipUpDown()],\n    num_selected_transforms=2,  # Only two steps from the list will be selected.\n    selected_probabilities=[0.5, 0.0, 0.3, 0.2, 0.0],  # Must sum up to 1.0, if given.\n    keep_order=True,  # If True, the selected steps must be performed in the given order.\n    probability=1.0  # Probability to apply this single combined transformation.\n)\n# Please refer to the API manual for more parameter options.\n\n# The `Compose` here is similar to that from the torchvision package, except \n# that here it also supports callables with multiple inputs and outputs needed\n# for objection detection tasks, i.e., (image, bboxes, labels).\ntransforms = Compose([\n    RandomCrop(probability=0.5),\n    affine_transform,\n    Resize((256, 256)),\n])\n\n# Convert the above data sequences into a PyTorch Dataset.\n# Users can have their own way to create the Dataset, as long as for each iteration \n# it returns a tuple of arrays for a single example: (image, bboxes, labels).\nds = PTDataset(image_seq, bboxes_seq, labels_seq, transforms=transforms)\n```\n```python\n# Batching:\n# In PyTorch, it is common to use a Dataset with a DataLoader, which provides\n# batching functionality. However, since the array/tensor shape of each example \n# could be different, the default batching may not work. Targetran provides\n# a `collate_fn` that helps producing batches of (image_seq, bboxes_seq, labels_seq).\nfrom torch.utils.data import DataLoader\nfrom targetran.utils import collate_fn\n\ndata_loader = DataLoader(ds, batch_size=2, collate_fn=collate_fn)\n```\n\n## Image classification\n\nWhile the tools here are primarily designed for object detection tasks, they can \nalso be used for image classification in which only the images are to be transformed,\ne.g., given a dataset that returns `(image, label)` examples, or even only `image` examples. \nThe `image_only` function can be used to convert a transformation class for this purpose.\n\nIf the dataset returns a tuple `(image, ...)` in each iteration, only the `image`\nwill be transformed, other parameters that followed such as `(..., label, weight)` \nwill be returned untouched.\n\nIf the dataset returns `image` only (not a tuple), then only the transformed `image` will be returned. \n```python\nfrom targetran.utils import image_only\n```\n```python\n# TensorFlow.\nds = to_tf_dataset(image_seq)\n\nds = (\n  ds\n  .map(image_only(TFRandomCrop()))\n  .map(image_only(affine_transform))\n  .map(image_only(TFResize((256, 256))))\n  .batch(32)  # Conventional batching can be used for classification setup.\n)\n```\n```python\n# PyTorch.\ntransforms = Compose([\n    image_only(RandomCrop()),\n    image_only(affine_transform),\n    image_only(Resize((256, 256))),\n])\nds = PTDataset(..., transforms=transforms)\ndata_loader = DataLoader(ds, batch_size=32)\n```\n\n# Examples\n\n- [Code examples in this repository](examples) \n- [Construct a TensorFlow Dataset with Targetran \n   and object detection data](https://www.kaggle.com/boscoyung/targetran-example-with-tensorflow-dataset) \n  (Kaggle Notebook)\n- [Image classification with TensorFlow and Targetran on TPU](https://www.kaggle.com/boscoyung/targetran-tpu-for-image-classification-example)\n  (Kaggle Notebook)\n\n# API\n\nSee [here](docs/API.md) for API details.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Target transformation for data augmentation in objection detection",
    "version": "0.13.2",
    "project_urls": {
        "Homepage": "https://github.com/bhky/targetran"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "df725d9c1b20fc626dcddccc830596e6d9d50647e453d2d2a0894eb8c7e83edf",
                "md5": "795409bb646964d7365e216c9bc91e6e",
                "sha256": "9858d6c917aa6735bf96e9747a8c163c4ac23d95d8796575b03cb95197a33dfe"
            },
            "downloads": -1,
            "filename": "targetran-0.13.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "795409bb646964d7365e216c9bc91e6e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 29248,
            "upload_time": "2025-01-24T09:38:45",
            "upload_time_iso_8601": "2025-01-24T09:38:45.493592Z",
            "url": "https://files.pythonhosted.org/packages/df/72/5d9c1b20fc626dcddccc830596e6d9d50647e453d2d2a0894eb8c7e83edf/targetran-0.13.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "0dc2f649a2f8844089d8dcac34c5b764562252735d64ff7a6c559573f207b19f",
                "md5": "d7849fa9bfa903072aac294f43a61c7c",
                "sha256": "fa5ff162a74f6305491ae304b1e6de1208800bdf9bd17e296679dafa4ce12958"
            },
            "downloads": -1,
            "filename": "targetran-0.13.2.tar.gz",
            "has_sig": false,
            "md5_digest": "d7849fa9bfa903072aac294f43a61c7c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 28381,
            "upload_time": "2025-01-24T09:38:47",
            "upload_time_iso_8601": "2025-01-24T09:38:47.240120Z",
            "url": "https://files.pythonhosted.org/packages/0d/c2/f649a2f8844089d8dcac34c5b764562252735d64ff7a6c559573f207b19f/targetran-0.13.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-01-24 09:38:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "bhky",
    "github_project": "targetran",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "keras-cv",
            "specs": [
                [
                    ">=",
                    "0.9.0"
                ]
            ]
        },
        {
            "name": "matplotlib",
            "specs": []
        },
        {
            "name": "numpy",
            "specs": [
                [
                    ">=",
                    "1.22.0"
                ]
            ]
        },
        {
            "name": "opencv-python",
            "specs": []
        },
        {
            "name": "pandas",
            "specs": [
                [
                    ">=",
                    "1.1.0"
                ]
            ]
        },
        {
            "name": "tensorflow",
            "specs": [
                [
                    ">=",
                    "2.4.0"
                ]
            ]
        },
        {
            "name": "torch",
            "specs": [
                [
                    ">=",
                    "1.7.0"
                ]
            ]
        }
    ],
    "lcname": "targetran"
}
        
Elapsed time: 1.29269s