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

你可能感兴趣的文章
OA项目之我的审批(会议查询&会议签字)
查看>>
OA项目之项目简介&会议发布
查看>>
ObjC的复制操作
查看>>
Object c将一个double值转换为时间格式
查看>>
object detection之Win10配置
查看>>
object detection训练自己数据
查看>>
object detection错误Message type "object_detection.protos.SsdFeatureExtractor" has no field named "bat
查看>>
object detection错误之Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
查看>>
object detection错误之no module named nets
查看>>
Object of type 'ndarray' is not JSON serializable
查看>>
Object Oriented Programming in JavaScript
查看>>
object references an unsaved transient instance - save the transient instance before flushing
查看>>
Object 类的常见方法有哪些?
查看>>
Object-c动态特性
查看>>
Object.assign用法
查看>>
Object.create
查看>>
Object.defineProperty详解
查看>>
Object.keys()的详解和用法
查看>>
objectForKey与valueForKey在NSDictionary中的差异
查看>>
Objective - C 小谈:消息机制的原理与使用
查看>>