博客
关于我
图像加灰条避免缩放失真
阅读量: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/

你可能感兴趣的文章
NoSQL介绍
查看>>
Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
查看>>
Notepad++在线和离线安装JSON格式化插件
查看>>
notepad++最详情汇总
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>