博客
关于我
图像加灰条避免缩放失真
阅读量:592 次
发布时间:2019-03-12

本文共 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/

你可能感兴趣的文章
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>
NPOI
查看>>