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

你可能感兴趣的文章
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>