在图像识别任务中,裁剪是一种比较常用的数据增强方法。通过numpy对图像数组进行截取就可以实现裁剪的功能。
对于像目标检测这类带标注框的图像识别任务,裁剪要确保目标不被裁掉,另外,还要更新标注框的位置,因为经过裁剪后目标在图中的位置发生了变化。以下函数实现了:
- 在保证目标点points不被裁掉的情况下,随机裁剪图像。
- 计算原图中坐标点points在裁剪后的图像中的位置坐标。
import numpy as np
import random
def random_crop_with_points(image, points):
"""随机裁剪图像,并计算points在裁剪后的图像中的位置.
Args:
image: 图像数组
points: [(x, y), ...],原图像中的坐标点集合
Return:
new_img: 裁剪后的图像
new_pts: [(x, y), ...],原图中的点在裁剪后的图中的位置
"""
h, w = image.shape[: 2]
points = np.array(points, np.int32)
min_x, min_y, max_x, max_y = np.min(points[:, 0]), np.min(points[:, 1]), np.max(points[:, 0]), np.max(points[:, 1])
t, b, lft, r = (random.randint(0, min_y),
random.randint(max_y + 1, h) if max_y + 1 < h else max_y + 1,
random.randint(0, min_x),
random.randint(max_x + 1, w) if max_x + 1 < w else max_x + 1)
new_img = image[t: b, lft: r, :]
new_pts = [[x - lft, y - t] for x, y in points]
return new_img, new_pts
版权声明:本文为CSDN博主「warpin」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lhp171302512/article/details/117388643
暂无评论