【扒代码】调整图像大小
·
函数
类里的函数 叫方法
class resizeImage(object):
"""
If either the width or height of an image exceed a specified value, resize the image so that:
如果图像的宽度或高度超过了指定的值,则调整图像大小,使得:
1. The maximum of the new height and new width does not exceed a specified value
新的高度和新的宽度的最大值不超过指定的值;
2. The new height and new width are divisible by 8
新的高度和新的宽度都能被8整除;
3. The aspect ratio is preserved
图像的原始宽高比得到保持。
No resizing is done if both height and width are smaller than the specified value
如果图像的高度和宽度都小于指定的值,则不进行任何调整大小的操作
By: Minh Hoai Nguyen (minhhoai@gmail.com)
"""
def __init__(self, MAX_HW=1504):
# 初始化方法,接受一个参数 MAX_HW,默认值为1504。这个参数定义了图像的最大高度或宽度
# 保存最大高度或宽度的值。
self.max_hw = MAX_HW
def __call__(self, sample):
image,lines_boxes = sample['image'], sample['lines_boxes'] # 从样本中获取图像和边界框信息
W, H = image.size # 获取图像的宽度和高度
# 如果图像的宽度或高度超过最大值,则进行缩放
if W > self.max_hw or H > self.max_hw:
# 计算缩放比例,使得最大边不超过MAX_HW,同时保持宽高比
scale_factor = float(self.max_hw)/ max(H, W)
# 计算新的宽度和高度,并确保它们是8的倍数
new_H = 8*int(H*scale_factor/8)
new_W = 8*int(W*scale_factor/8)
# 使用transforms.Resize调整图像大小
resized_image = transforms.Resize((new_H, new_W))(image)
else:
# 如果图像宽度和高度都小于指定值,则不进行缩放
scale_factor = 1
resized_image = image
# 根据缩放比例调整边界框的大小
boxes = list()
for box in lines_boxes:
# 缩放边界框坐标
box2 = [int(k*scale_factor) for k in box]
# 提取边界框的坐标
y1, x1, y2, x2 = box2[0], box2[1], box2[2], box2[3]
# 将缩放后的边界框添加到列表中
boxes.append([0, y1,x1,y2,x2])
# 将边界框列表转换为张量,并增加一个维度
boxes = torch.Tensor(boxes).unsqueeze(0)
# 对调整大小后的图像进行归一化处理
resized_image = Normalize(resized_image)
# 更新样本中的图像和边界框信息
sample = {'image':resized_image,'boxes':boxes}
return sample
更多推荐
所有评论(0)