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