图像加灰条避免缩放失真
在深度学习的训练中,大多需要使用正方形的图片,但是我们平常拍摄的图像大多都是长方形的,所以在缩放图片时,要给图片加灰条,代码很简单:
def letterbox_image(image, size):
iw, ih = image.size
w, h = size
scale = min(w/iw, h/ih)
nw = int(iwscale)
nh = int(ihscale)
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
讯享网
讯享网import os import numpy as np import cv2 from PIL import Image def letterbox_image(image, size): iw, ih = image.size w, h = size scale = 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] = [] path = os.path.join(curdir, file) objects[label].append(path) return objects if __name__ == "__main__": train_samples = search_files('E:\\python\\learning\\tree_learn\\crossFork') print(train_samples) 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)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/123805.html