Python PIL.Image.TRANSPOSE Examples

The following are 12 code examples of PIL.Image.TRANSPOSE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PIL.Image , or try the search function .
Example #1
Source File: predict.py    From Custom-vision-service-iot-edge-raspberry-pi with MIT License 7 votes vote down vote up
def update_orientation(image):
    exif_orientation_tag = 0x0112
    if hasattr(image, '_getexif'):
        exif = image._getexif()
        if exif != None and exif_orientation_tag in exif:
            orientation = exif.get(exif_orientation_tag, 1)
            log_msg('Image has EXIF Orientation: ' + str(orientation))
            # orientation is 1 based, shift to zero based and flip/transpose based on 0-based values
            orientation -= 1
            if orientation >= 4:
                image = image.transpose(Image.TRANSPOSE)
            if orientation == 2 or orientation == 3 or orientation == 6 or orientation == 7:
                image = image.transpose(Image.FLIP_TOP_BOTTOM)
            if orientation == 1 or orientation == 2 or orientation == 5 or orientation == 6:
                image = image.transpose(Image.FLIP_LEFT_RIGHT)
    return image 
Example #2
Source File: predict-amd64.py    From Custom-vision-service-iot-edge-raspberry-pi with MIT License 6 votes vote down vote up
def update_orientation(image):
    exif_orientation_tag = 0x0112
    if hasattr(image, '_getexif'):
        exif = image._getexif()
        if exif != None and exif_orientation_tag in exif:
            orientation = exif.get(exif_orientation_tag, 1)
            log_msg('Image has EXIF Orientation: ' + str(orientation))
            # orientation is 1 based, shift to zero based and flip/transpose based on 0-based values
            orientation -= 1
            if orientation >= 4:
                image = image.transpose(Image.TRANSPOSE)
            if orientation == 2 or orientation == 3 or orientation == 6 or orientation == 7:
                image = image.transpose(Image.FLIP_TOP_BOTTOM)
            if orientation == 1 or orientation == 2 or orientation == 5 or orientation == 6:
                image = image.transpose(Image.FLIP_LEFT_RIGHT)
    return image 
Example #3
Source File: preprocess.py    From instance-segmentation-pytorch with GNU General Public License v3.0 6 votes vote down vote up
def transpose(img):
    """Transpose the given PIL Image.
    Args:
        img (PIL Image): Image to be transposed.
    Returns:
        PIL Image: Transposed image.
    """

    is_numpy = isinstance(img, np.ndarray)

    if not _is_pil_image(img):
        if is_numpy:
            img = Image.fromarray(img)
        else:
            raise TypeError(
                'img should be PIL Image or numpy array. \
                Got {}'.format(type(img)))

    img = img.transpose(Image.TRANSPOSE)

    if is_numpy:
        img = np.array(img)

    return img 
Example #4
Source File: data.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def next(self):
        from PIL import Image
        if self.count + self.batch_size <= len(self.filenames):
            data = []
            label = []
            for i in range(self.batch_size):
                fn = self.filenames[self.count]
                self.count += 1
                image = Image.open(fn).convert('YCbCr').split()[0]
                if image.size[0] > image.size[1]:
                    image = image.transpose(Image.TRANSPOSE)
                image = mx.nd.expand_dims(mx.nd.array(image), axis=2)
                target = image.copy()
                for aug in self.input_aug:
                    image = aug(image)
                for aug in self.target_aug:
                    target = aug(target)
                data.append(image)
                label.append(target)

            data = mx.nd.concat(*[mx.nd.expand_dims(d, axis=0) for d in data], dim=0)
            label = mx.nd.concat(*[mx.nd.expand_dims(d, axis=0) for d in label], dim=0)
            data = [mx.nd.transpose(data, axes=(0, 3, 1, 2)).astype('float32')/255]
            label = [mx.nd.transpose(label, axes=(0, 3, 1, 2)).astype('float32')/255]

            return mx.io.DataBatch(data=data, label=label)
        else:
            raise StopIteration 
Example #5
Source File: data.py    From training_results_v0.6 with Apache License 2.0 5 votes vote down vote up
def next(self):
        from PIL import Image
        if self.count + self.batch_size <= len(self.filenames):
            data = []
            label = []
            for i in range(self.batch_size):
                fn = self.filenames[self.count]
                self.count += 1
                image = Image.open(fn).convert('YCbCr').split()[0]
                if image.size[0] > image.size[1]:
                    image = image.transpose(Image.TRANSPOSE)
                image = mx.nd.expand_dims(mx.nd.array(image), axis=2)
                target = image.copy()
                for aug in self.input_aug:
                    image = aug(image)
                for aug in self.target_aug:
                    target = aug(target)
                data.append(image)
                label.append(target)

            data = mx.nd.concat(*[mx.nd.expand_dims(d, axis=0) for d in data], dim=0)
            label = mx.nd.concat(*[mx.nd.expand_dims(d, axis=0) for d in label], dim=0)
            data = [mx.nd.transpose(data, axes=(0, 3, 1, 2)).astype('float32')/255]
            label = [mx.nd.transpose(label, axes=(0, 3, 1, 2)).astype('float32')/255]

            return mx.io.DataBatch(data=data, label=label)
        else:
            raise StopIteration 
Example #6
Source File: data.py    From deeplearning-benchmark with Apache License 2.0 5 votes vote down vote up
def next(self):
        from PIL import Image
        if self.count + self.batch_size <= len(self.filenames):
            data = []
            label = []
            for i in range(self.batch_size):
                fn = self.filenames[self.count]
                self.count += 1
                image = Image.open(fn).convert('YCbCr').split()[0]
                if image.size[0] > image.size[1]:
                    image = image.transpose(Image.TRANSPOSE)
                image = mx.nd.expand_dims(mx.nd.array(image), axis=2)
                target = image.copy()
                for aug in self.input_aug:
                    image = aug(image)[0]
                for aug in self.target_aug:
                    target = aug(target)[0]
                data.append(image)
                label.append(target)

            data = mx.nd.concat(*[mx.nd.expand_dims(d, axis=0) for d in data], dim=0)
            label = mx.nd.concat(*[mx.nd.expand_dims(d, axis=0) for d in label], dim=0)
            data = [mx.nd.transpose(data, axes=(0, 3, 1, 2)).astype('float32')/255]
            label = [mx.nd.transpose(label, axes=(0, 3, 1, 2)).astype('float32')/255]

            return mx.io.DataBatch(data=data, label=label)
        else:
            raise StopIteration 
Example #7
Source File: preprocess.py    From instance-segmentation-pytorch with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, img, flip):
        """
        Args:
            img (PIL Image): Image to be flipped.
        Returns:
            PIL Image: Flipped image.
        """
        if flip:
            return vflip(img)
        return img


# TRANSPOSE # 
Example #8
Source File: extract_edof.py    From dual-camera-edof with GNU General Public License v2.0 5 votes vote down vote up
def extract_edof(data, idx, fname):
	if data[idx + 4:idx + 8] != b'edof':
		print("ERROR: Frame is not EDOF")
		return False
	
	idx += 8
	columns = int.from_bytes(data[idx + 16: idx + 18], byteorder='little')
	rows = int.from_bytes(data[idx + 18: idx + 20], byteorder='little')
	print("\t* found EDOF at %d with geometry=%dx%d" % (idx, columns, rows))

	orientation = data[idx + 7]

	idx += 68
	img = Image.frombuffer('L', (columns, rows), data[idx:], 'raw', 'L', 0, 0)
	if orientation == 0x10:
		img = img.transpose(Image.FLIP_TOP_BOTTOM)
	elif orientation == 0x12:
		img = img.transpose(Image.FLIP_LEFT_RIGHT)
	elif orientation == 0x13:
		img = img.transpose(Image.TRANSPOSE)

	if show_edof:
		img.show()

	if save_edof:
		outfname = (''.join(fname.split('.')[:-1])) + '-EDOF.png'
		print("\t  * saving to %s" % outfname)
		img.save(outfname)

	return True 
Example #9
Source File: __init__.py    From core with Apache License 2.0 5 votes vote down vote up
def transpose_image(image, method):
    """"Transpose (i.e. flip or rotate in 90° multiples) an image.

    Given a PIL.Image ``image`` and a transposition mode ``method``,
    apply the respective operation:

    - ``PIL.Image.FLIP_LEFT_RIGHT``:
      all pixels get mirrored at half the width of the image
    - ``PIL.Image.FLIP_TOP_BOTTOM``:
      all pixels get mirrored at half the height of the image
    - ``PIL.Image.ROTATE_180``:
      all pixels get mirrored at both, the width and half the height
      of the image,
      i.e. the image gets rotated by 180° counter-clockwise
    - ``PIL.Image.ROTATE_90``:
      rows become columns (but counted from the right) and
      columns become rows,
      i.e. the image gets rotated by 90° counter-clockwise;
      width becomes height and vice versa
    - ``PIL.Image.ROTATE_270``:
      rows become columns and
      columns become rows (but counted from the bottom),
      i.e. the image gets rotated by 270° counter-clockwise;
      width becomes height and vice versa
    - ``PIL.Image.TRANSPOSE``:
      rows become columns and vice versa,
      i.e. all pixels get mirrored at the main diagonal;
      width becomes height and vice versa
    - ``PIL.Image.TRANSVERSE``:
      rows become columns (but counted from the right) and
      columns become rows (but counted from the bottom),
      i.e. all pixels get mirrored at the opposite diagonal;
      width becomes height and vice versa
    
    Return a new PIL.Image.
    """
    LOG.debug('transposing image with %s', membername(Image, method))
    return image.transpose(method) 
Example #10
Source File: __init__.py    From core with Apache License 2.0 5 votes vote down vote up
def adjust_canvas_to_transposition(size, method):
    """Calculate the flipped image size after transposition.
    
    Given a numpy array ``size`` of an original canvas (width and height),
    and a transposition mode ``method`` (see ``transpose_image``),
    calculate the new size after transposition.
    
    Return a numpy array of the enlarged width and height.
    """
    if method in [Image.ROTATE_90,
                  Image.ROTATE_270,
                  Image.TRANSPOSE,
                  Image.TRANSVERSE]:
        size = size[::-1]
    return size 
Example #11
Source File: data.py    From SNIPER-mxnet with Apache License 2.0 5 votes vote down vote up
def next(self):
        from PIL import Image
        if self.count + self.batch_size <= len(self.filenames):
            data = []
            label = []
            for i in range(self.batch_size):
                fn = self.filenames[self.count]
                self.count += 1
                image = Image.open(fn).convert('YCbCr').split()[0]
                if image.size[0] > image.size[1]:
                    image = image.transpose(Image.TRANSPOSE)
                image = mx.nd.expand_dims(mx.nd.array(image), axis=2)
                target = image.copy()
                for aug in self.input_aug:
                    image = aug(image)
                for aug in self.target_aug:
                    target = aug(target)
                data.append(image)
                label.append(target)

            data = mx.nd.concat(*[mx.nd.expand_dims(d, axis=0) for d in data], dim=0)
            label = mx.nd.concat(*[mx.nd.expand_dims(d, axis=0) for d in label], dim=0)
            data = [mx.nd.transpose(data, axes=(0, 3, 1, 2)).astype('float32')/255]
            label = [mx.nd.transpose(label, axes=(0, 3, 1, 2)).astype('float32')/255]

            return mx.io.DataBatch(data=data, label=label)
        else:
            raise StopIteration 
Example #12
Source File: detection_utils.py    From detectron2 with Apache License 2.0 4 votes vote down vote up
def _apply_exif_orientation(image):
    """
    Applies the exif orientation correctly.

    This code exists per the bug:
      https://github.com/python-pillow/Pillow/issues/3973
    with the function `ImageOps.exif_transpose`. The Pillow source raises errors with
    various methods, especially `tobytes`

    Function based on:
      https://github.com/wkentaro/labelme/blob/v4.5.4/labelme/utils/image.py#L59
      https://github.com/python-pillow/Pillow/blob/7.1.2/src/PIL/ImageOps.py#L527

    Args:
        image (PIL.Image): a PIL image

    Returns:
        (PIL.Image): the PIL image with exif orientation applied, if applicable
    """
    if not hasattr(image, "getexif"):
        return image

    exif = image.getexif()

    if exif is None:
        return image

    orientation = exif.get(_EXIF_ORIENT)

    method = {
        2: Image.FLIP_LEFT_RIGHT,
        3: Image.ROTATE_180,
        4: Image.FLIP_TOP_BOTTOM,
        5: Image.TRANSPOSE,
        6: Image.ROTATE_270,
        7: Image.TRANSVERSE,
        8: Image.ROTATE_90,
    }.get(orientation)

    if method is not None:
        return image.transpose(method)
    return image