本文共 1329 字,大约阅读时间需要 4 分钟。
图像加灰条避免缩放失真是深度学习训练中常见的一个问题,特别是在目标检测等任务中,通常要求输入图片为正方形尺寸。但实际应用中,图片常常以长宽比例不等的形式存在。因此,在缩放图片时,为了保持图片的长宽比例不变,避免因高缩放率导致的图像缺失细节问题,需要使用加灰条的方法来处理。
以下是实现图像加灰条的核心代码:[1]ew_image = Image.new('RGB', size, (128,128,128))new_image.paste(image, ((w-nw)//2, (h-nh)//2))
这个代码通过首先计算原图与目标尺寸的缩放比,然后根据缩放比确定图片的缩放后宽高,最后再将缩放后的图片粘贴到一个灰色背景的新图片上,实现了加灰条的效果。灰条的颜色可以根据实际需求任意设定。在实际应用中,常用的灰色阴影为(128,128,128),但可以根据具体需求进行调整。
以下是完整的批量添加灰条代码:[2]
import osimport numpy as npimport cv2from PIL import Image
def letterbox_image(image, size):iw, ih = image.sizew, h = sizescale = min(w / iw, h / ih)nw = int(iw * scale)nh = int(ih * scale)image = image.resize((nw, nh), Image.BICUBIC)new_image = Image.new('RGB', size, (128, 128, 128))new_image.paste(image, ((w - nw) // 2, (h - nh) // 2))return new_image
def search_files(directory):directory = os.path.normpath(directory)objects = {}for curdir, subdirs, files in os.walk(directory):for file in files:if file.endswith('.jpg'):label = curdir.split(os.path.sep)[-1]if label not in objects:objects[label] = []objects[label].append(os.path.join(curdir, file))return objects
if name == "main":train_samples = search_files('E:\python\learning\tree_learn\crossFork')for label, filenames in train_samples.items():for filename in filenames:img = Image.open(filename)new_img = letterbox_image(img, (224, 224))new_img.save(filename)
转载地址:http://hlhtz.baihongyu.com/