使用Python将图片转正方形的两种方法实例代码详解


Posted in Python onApril 29, 2020

一、将原图粘贴到一张正方形的背景上

def trans_square(image):
  r"""Open the image using PIL."""
  image = image.convert('RGB')
  w, h = image.size
  background = Image.new('RGB', size=(max(w, h), max(w, h)), color=(127, 127, 127)) # 创建背景图,颜色值为127
  length = int(abs(w - h) // 2) # 一侧需要填充的长度
  box = (length, 0) if w < h else (0, length) # 粘贴的位置
  background.paste(image, box)
  return background

二、切片填充的方式使用numpy创建背景,使用切片将原图的值填充到背景中。

def trans_square(image):
  	r"""Open the image using PIL."""
    img = image.convert('RGB')
    img = np.array(img, dtype=np.uint8) # 图片转numpy
    img_h, img_w, img_c = img.shape
    if img_h != img_w:
      long_side = max(img_w, img_h)
      short_side = min(img_w, img_h)
      loc = abs(img_w - img_h) // 2
      img = img.transpose((1, 0, 2)) if img_w < img_h else img # 如果高是长边则换轴,最后再换回来
      background = np.zeros((long_side, long_side, img_c), dtype=np.uint8) # 创建正方形背景
      background[loc: loc + short_side] = img[...] # 数据填充在中间位置
      img = background.transpose((1, 0, 2)) if img_w < img_h else background
    return Image.fromarray(img, 'RGB')

使用 nn.ZeroPad2d() 或者 nn.ConstantPad2d() 进行填充

def trans_square(image):
  r"""transform square.
  :return PIL image
  """
  img = transforms.ToTensor()(image)
  C, H, W = img.shape
  pad_1 = int(abs(H - W) // 2) # 一侧填充长度
  pad_2 = int(abs(H - W) - pad_1) # 另一侧填充长度
  img = img.unsqueeze(0) # 加轴
  if H > W:
    img = nn.ZeroPad2d((pad_1, pad_2, 0, 0))(img) # 左右填充,填充值是0
    # img = nn.ConstantPad2d((pad_1, pad_2, 0, 0), 127)(img) # 左右填充,填充值是127
  elif H < W:
    img = nn.ZeroPad2d((0, 0, pad_1, pad_2))(img) # 上下填充,填充值是0
    # img = nn.ConstantPad2d((0, 0, pad_1, pad_2), 127)(img) # 上下填充,填充值是127
  img = img.squeeze(0) # 减轴
  img = transforms.ToPILImage()(img)
  return img

ps:下面看下python 将图片转换成九宫格形式

用到的模块PIL(安装:pip install pillow

完整代码:

from PIL import Image 
import sys 
#先将 input image 填充为正方形 
def fill_image(image): 
  width, height = image.size   
  #选取长和宽中较大值作为新图片的 
  new_image_length = width if width > height else height   
  #生成新图片[白底] 
  new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white')  #注意这个函数! 
  #将之前的图粘贴在新图上,居中  
  if width > height:#原图宽大于高,则填充图片的竖直维度 #(x,y)二元组表示粘贴上图相对下图的起始位置,是个坐标点。 
    new_image.paste(image, (0, int((new_image_length - height) / 2))) 
  else: 
    new_image.paste(image, (int((new_image_length - width) / 2),0))   
  return new_image 
def cut_image(image):
  width, height = image.size
  item_width = int(width / 3) 
  box_list = []
  # (left, upper, right, lower)
  for i in range(0,3):
    for j in range(0,3):
      #print((i*item_width,j*item_width,(i+1)*item_width,(j+1)*item_width))
      box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width)
      box_list.append(box)
  image_list = [image.crop(box) for box in box_list]
  return image_list
#保存 
def save_images(image_list): 
  index = 1  
  for image in image_list: 
    image.save(str(index) + '.png', 'PNG') 
    index += 1 
if __name__ == '__main__': 
  file_path = "***"#填入图片名 
  image = Image.open(file_path)   
  #image.show() 
  image = fill_image(image) 
  image_list = cut_image(image) 
  save_images(image_list)

原图:

使用Python将图片转正方形的两种方法实例代码详解

运行程序后效果图:

使用Python将图片转正方形的两种方法实例代码详解

到此这篇关于使用Python将图片转正方形的两种方法的文章就介绍到这了,更多相关python 图片转正方形内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
举例讲解Python面向对象编程中类的继承
Jun 17 Python
Python中list初始化方法示例
Sep 18 Python
Python安装官方whl包和tar.gz包的方法(推荐)
Jun 04 Python
Python使用pymysql小技巧
Jun 04 Python
Python实现基于PIL和tesseract的验证码识别功能示例
Jul 11 Python
Python matplotlib画图与中文设置操作实例分析
Apr 23 Python
python-序列解包(对可迭代元素的快速取值方法)
Aug 24 Python
Python中 CSV格式清洗与转换的实例代码
Aug 29 Python
Python对接支付宝支付自实现功能
Oct 10 Python
Python基于xlrd模块处理合并单元格
Jul 28 Python
使用jupyter notebook运行python和R的步骤
Aug 13 Python
python 如何读、写、解析CSV文件
Mar 03 Python
Python通过Pillow实现图片对比
Apr 29 #Python
Python unittest单元测试框架实现参数化
Apr 29 #Python
Python ORM框架Peewee用法详解
Apr 29 #Python
3种适用于Python的疯狂秘密武器及原因解析
Apr 29 #Python
Pytorch十九种损失函数的使用详解
Apr 29 #Python
Python格式化输出--%s,%d,%f的代码解析
Apr 29 #Python
Python爬虫工具requests-html使用解析
Apr 29 #Python
You might like
盘点被央视点名过的日本动画电影 一部比一部强
2020/03/08 日漫
自己前几天写的无限分类类
2007/02/14 PHP
Laravel框架学习笔记(一)环境搭建
2014/10/15 PHP
php可生成缩略图的文件上传类实例
2014/12/17 PHP
Laravel 5 框架入门(一)
2015/04/09 PHP
PHP自带方法验证邮箱是否存在
2016/02/01 PHP
PHP的中使用非缓冲模式查询数据库的方法
2017/02/05 PHP
PHP设计模式之注册树模式分析
2018/01/26 PHP
PHP tp5中使用原生sql查询代码实例
2020/10/28 PHP
JavaScript Event事件学习第一章 Event介绍
2010/02/07 Javascript
解决js中window.open弹出的是上次的缓存页面问题
2013/12/29 Javascript
在Node.js中实现文件复制的方法和实例
2014/06/05 Javascript
js实现类似于add(1)(2)(3)调用方式的方法
2015/03/04 Javascript
JavaScript实现计算字符串中出现次数最多的字符和出现的次数
2015/03/12 Javascript
jQuery form 表单验证插件(fieldValue)校验表单
2016/01/24 Javascript
JavaScript版经典游戏之扫雷游戏完整示例【附demo源码下载】
2016/12/12 Javascript
webpack2.0搭建前端项目的教程详解
2017/04/05 Javascript
JS回调函数基本定义与用法实例分析
2017/05/24 Javascript
Nodejs之http的表单提交
2017/07/07 NodeJs
Angular 2.0+ 的数据绑定的实现示例
2017/08/09 Javascript
python解析html开发库pyquery使用方法
2014/02/07 Python
Python删除n行后的其他行方法
2019/01/28 Python
python的内存管理和垃圾回收机制详解
2019/05/18 Python
python  ceiling divide 除法向上取整(或小数向上取整)的实例
2019/12/27 Python
CSS3 Pie工具推荐--让IE6-8支持一些优秀的CSS3特性
2014/09/02 HTML / CSS
亚洲独特体验旅游专家:eOasia
2018/08/15 全球购物
自荐信的两点禁忌
2013/10/30 职场文书
2014年教师培训的自我评价
2014/01/03 职场文书
优秀党支部事迹材料
2014/01/14 职场文书
教师自我鉴定范文
2014/03/20 职场文书
国家励志奖学金个人先进事迹材料
2014/05/04 职场文书
KTV门卫岗位职责
2014/10/09 职场文书
2015年度学校卫生工作总结
2015/05/12 职场文书
2016年寒假社会实践活动心得体会
2015/10/09 职场文书
Go语言基础知识点介绍
2021/07/04 Golang
Nginx内网单机反向代理的实现
2021/11/07 Servers