【翻转】水平翻转(HorizontalFlip)

本文介绍了如何在Python中使用torch和imgaug库进行图像水平翻转,包括torch的`hflip`函数、imgaug的`Fliplr`操作以及自定义手写编码实现。着重讲解了如何在处理图像、bboxes和关键点时应用这些翻转变换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理

  1. 概念:将图像沿着水平方向进行镜像翻转,即左右对称。(将图像的左边像素点与右边像素点位置互换)
    在这里插入图片描述

实战

#!/usr/bin/python3
# -*- coding:utf-8 -*-

import torch
from imgaug import augmenters as iaa
from torchvision.transforms import functional as TF


def imgaug_example(image):
    augmenter = iaa.Fliplr(p=1.0)
    image = augmenter(image=image)
    return image


def torch_example(image):
    return TF.hflip(image)


def hand_coding(image):
    imw = image.shape[-1]
    index = torch.arange(imw - 1, -1, -1)  # 创建索引张量
    return image[..., index]


class HorizontalFlip:

    def __init__(self) -> None:
        """HorizontalFlip, 水平翻转
        """
        super().__init__()

    @staticmethod
    def _augment_image(image):
        return TF.hflip(image)

    @staticmethod
    def _augment_bboxes(bboxes, imw):
        bboxes[:, [0, 2]] = imw - bboxes[:, [2, 0]]
        return bboxes

    @staticmethod
    def _augment_keypoints(keypoints, imw):
        keypoints[:, 0] = imw - keypoints[:, 0]
        return keypoints

    def __call__(self, doc):
        """
        doc = {
            'image': torch.Tensor,  # C*H*W
            'mask': torch.Tensor,  # C*H*W
            'bboxes': torch.Tensor,  # [[x1, y1, x2, y2, label], ...]
            'heatmap': torch.Tensor,  # C*H*W
            'keypoints': torch.Tensor,  # [[x1, y1], [x2, y2], ...]
            'shape': torch.Size,  # image's shape [C, H, W]
        }
        """
        image = doc.get('image')
        if image is None:
            return doc

        doc['image'] = self._augment_image(image)

        bboxes = doc.get('bboxes')
        if bboxes is not None:
            imw = doc['shape'][-1]
            doc['bboxes'] = self._augment_bboxes(bboxes, imw)

        mask = doc.get('mask')
        if mask is not None:
            doc['mask'] = self._augment_image(mask)

        heatmap = doc.get('heatmap')
        if heatmap is not None:
            doc['heatmap'] = self._augment_image(heatmap)

        keypoints = doc.get('keypoints')
        if keypoints is not None:
            imw = doc['shape'][-1]
            doc['keypoints'] = self._augment_keypoints(keypoints, imw)

        return doc

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值