使用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之用Python计算
Sep 12 Python
Python实现的简单文件传输服务器和客户端
Apr 08 Python
如何使用七牛Python SDK写一个同步脚本及使用教程
Aug 23 Python
用Python编写简单的微博爬虫
Mar 04 Python
python 连接各类主流数据库的实例代码
Jan 30 Python
python opencv之SURF算法示例
Feb 24 Python
Python实现正则表达式匹配任意的邮箱方法
Dec 20 Python
python+opencv实现阈值分割
Dec 26 Python
在Django admin中编辑ManyToManyField的实现方法
Aug 09 Python
基于Python的微信机器人开发 微信登录和获取好友列表实现解析
Aug 21 Python
Django操作session 的方法
Mar 09 Python
python如何停止递归
Sep 09 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
php+ajax实现的点击浏览量加1
2015/04/16 PHP
Yii框架使用魔术方法实现跨文件调用功能示例
2017/05/20 PHP
PHP让数组中有相同值的组成新的数组实例
2017/12/31 PHP
JQuery jsonp 使用示例代码
2009/08/12 Javascript
jQuery选择没有colspan属性的td的代码
2010/07/06 Javascript
js DOM的学习笔记
2011/12/22 Javascript
Javascript 面向对象(三)接口代码
2012/05/23 Javascript
多个表单中如何获得这个文件上传的网址实现js代码
2013/03/25 Javascript
密码框显示提示文字jquery示例
2013/08/29 Javascript
JavaScript中for-in遍历方式示例介绍
2014/02/11 Javascript
Iframe 自动适应页面的高度示例代码
2014/02/26 Javascript
Jquery遍历Json数据的方法
2015/04/20 Javascript
常用的Javascript数据验证插件
2015/08/04 Javascript
第四章之BootStrap表单与图片
2016/04/25 Javascript
基于BootStarp的Dailog
2016/04/28 Javascript
将List对象列表转换成JSON格式的类实现方法
2016/07/04 Javascript
深入理解Angularjs向指令传递数据双向绑定机制
2016/12/31 Javascript
jQuery动态追加页面数据以及事件委托详解
2017/05/06 jQuery
详解Windows下安装Nodejs步骤
2017/05/18 NodeJs
js实现城市级联菜单的2种方法
2017/06/23 Javascript
JS之if语句对接事件动作逻辑(详解)
2017/06/28 Javascript
vue动态路由配置及路由传参的方式
2018/05/23 Javascript
详解基于vue-cli3.0如何构建功能完善的前端架子
2018/10/09 Javascript
使用layui的layer组件做弹出层的例子
2019/09/27 Javascript
使用axios请求接口,几种content-type的区别详解
2019/10/29 Javascript
pygame学习笔记(6):完成一个简单的游戏
2015/04/15 Python
PyCharm安装Markdown插件的两种方法
2019/06/24 Python
Python实现的北京积分落户数据分析示例
2020/03/27 Python
简单了解Java Netty Reactor三种线程模型
2020/04/26 Python
中国最大隐形眼镜网上商城:视客眼镜网
2016/10/30 全球购物
解释一下ArrayList Vector和LinkedList的实现和区别
2013/04/26 面试题
普通简短的个人自我评价
2014/02/15 职场文书
小学生毕业评语
2014/12/26 职场文书
聘用合同范本
2015/09/21 职场文书
500字作文之难忘的同学
2019/12/20 职场文书
javascript条件式访问属性和箭头函数介绍
2021/11/17 Javascript