Skip to content
Snippets Groups Projects
Commit 992e72c0 authored by Amir MOHAMMADI's avatar Amir MOHAMMADI
Browse files

[preprocessor][scale] Rewrite the Scale transformer using simpler and more efficient code

parent 39eb03b8
No related branches found
No related tags found
2 merge requests!71Face crop improvements,!64Dask pipelines
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.preprocessing import FunctionTransformer
from skimage.transform import resize
import numpy as np
from sklearn.utils import check_array
from bob.io.image import to_matplotlib, to_bob
class Scale(TransformerMixin, BaseEstimator):
"""
Simple scales an images
def scale(images, target_img_size):
"""Scales a list of images to the target size
Parameters
-----------
----------
images : array_like
A list of images (in Bob format) to be scaled to the target size
target_img_size : tuple
Target image size
A tuple of size 2 as (H, W)
Returns
-------
numpy.ndarray
Scaled images
"""
images = check_array(images, allow_nd=True)
images = to_matplotlib(images)
def __init__(self, target_img_size, **kwargs):
# images are always batched
output_shape = tuple(target_img_size)
output_shape = tuple(images.shape[0:1]) + output_shape
images = resize(images, output_shape=output_shape)
self.target_img_size = target_img_size
return to_bob(images)
def _more_tags(self):
return {"stateless": True, "requires_fit": False}
def fit(self, X, y=None):
return self
def transform(self, X, annotations=None):
def Scale(target_img_size):
"""
Resize an image given a shape
A transformer that scales images.
It accepts a list of inputs
Parameters
----------
img:
Input image
-----------
target_img_size: tuple
Target image size
"""
def _resize(x):
return resize(x, self.target_img_size, anti_aliasing=True)
Target image size, specified as a tuple of (H, W)
X = check_array(X, allow_nd=True)
if X.ndim < 2 or X.ndim > 4:
raise ValueError(f"Invalid image shape {X.shape}")
if X.ndim == 2:
# Checking if it's bob format CxHxW
return _resize(X)
if X.ndim == 3:
# Checking if it's bob format CxHxW
if X.shape[0] == 3:
X = np.moveaxis(X, -1, 0)
return _resize(X)
# Batch of images
if X.ndim == 4:
# Checking if it's bob format NxCxHxW
if X.shape[1] == 3:
X = np.moveaxis(X, 1, -1)
return [_resize(x) for x in X]
"""
return FunctionTransformer(
func=scale, validate=False, kw_args=dict(target_img_size=target_img_size)
)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment