Python 使用PIL进行 旋转数据增强并去除黑边。

Python 使用PIL进行 旋转数据增强并去除黑边。

说明

  使用PIL等包进行数据增强时往往会旋转图像;一般旋转的图像会带有黑边如图:

在这里插入图片描述
我们希望在旋转完图像後仍去掉黑边,并使图像保持原来设定的大小。
这就涉及到弧度制的一些变化。
博主在Stackflow搜索到了一个不错的方法并做了简单的更新,去除过时的包并替换为PIL。
原作者:http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders

def _rotate_and_crop(image, output_height, output_width, rotation_degree, do_crop):
    """以给定的角,旋转一张图片,设置输出大小。根据需要旋转是否去除黑边。
    Args:
        image: A `Tensor` representing an image of arbitrary size.
        output_height: The height of the image after preprocessing.
        output_width: The width of the image after preprocessing.
        rotation_degree: The degree of rotation on the image.
        do_crop: Do cropping if it is True.
    Returns:
        A rotated image.
    """

    # Rotate the given image with the given rotation degree
    if rotation_degree != 0:
       
        image=image.rotate(math.radians(rotation_degree),Image.NEAREST,expand = False)

        # Center crop to ommit black noise on the edges
        if do_crop == True:
            lrr_width, lrr_height = _largest_rotated_rect(output_height, output_width, math.radians(rotation_degree))
            box
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值