使用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 thread 并发且顺序运行示例
Apr 09 Python
Python3 入门教程 简单但比较不错
Nov 29 Python
python设置检查点简单实现代码
Jul 01 Python
在Python中操作文件之truncate()方法的使用教程
May 25 Python
python实现将文本转换成语音的方法
May 28 Python
Python实现句子翻译功能
Nov 14 Python
Python遍历pandas数据方法总结
Feb 09 Python
python实现requests发送/上传多个文件的示例
Jun 04 Python
Python第三方Window模块文件的几种安装方法
Nov 22 Python
利用pyinstaller打包exe文件的基本教程
May 02 Python
Django继承自带user表并重写的例子
Nov 18 Python
python基础之类属性和实例属性
Oct 24 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
CI框架给视图添加动态数据
2014/12/01 PHP
PHP文件读取功能的应用实例
2015/05/08 PHP
php通过前序遍历树实现无需递归的无限极分类
2015/07/10 PHP
Laravel如何友好的修改.env配置文件详解
2017/06/07 PHP
关于js日期转化为毫秒数“节省20%的效率和和节省9个字符“问题
2012/03/01 Javascript
jQuery移动和复制dom节点实用DOM操作案例
2012/12/17 Javascript
js获得网页背景色和字体色的方法
2014/03/21 Javascript
javascript中setTimeout的问题解决方法
2014/05/08 Javascript
Javascript BOM学习小结(六)
2015/11/26 Javascript
快速学习jQuery插件 Form表单插件使用方法
2015/12/01 Javascript
简单实现jQuery进度条轮播实例代码
2016/06/20 Javascript
JS定时检测任务任务完成后执行下一步的解决办法
2016/12/22 Javascript
canvas快速绘制圆形、三角形、矩形、多边形方法介绍
2016/12/29 Javascript
JavaScript实现数值自动增加动画
2017/12/28 Javascript
基于jQuery实现无缝轮播与左右点击效果
2018/05/13 jQuery
详解如何使用babel进行es6文件的编译
2018/05/29 Javascript
mpvue小程序仿qq左滑置顶删除组件
2018/08/03 Javascript
微信小程序获取音频时长与实时获取播放进度问题
2018/08/28 Javascript
详解vue 兼容IE报错解决方案
2018/12/29 Javascript
p5.js实现简单货车运动动画
2019/10/23 Javascript
vue学习笔记之作用域插槽实例分析
2020/02/01 Javascript
vue中选中多个选项并且改变选中的样式的实例代码
2020/09/16 Javascript
构建一个JavaScript插件系统
2020/10/20 Javascript
js实现筛选功能
2020/11/24 Javascript
python中(str,list,tuple)基础知识汇总
2018/02/20 Python
pytorch使用Variable实现线性回归
2019/05/21 Python
pytorch实现对输入超过三通道的数据进行训练
2020/01/15 Python
2020最新pycharm汉化安装(python工程狮亲测有效)
2020/04/26 Python
美国潜水装备、水肺潜水和浮潜设备商店:Leisure Pro
2018/08/08 全球购物
Coccinelle官网:意大利的著名皮具品牌
2019/05/15 全球购物
水利公司纪检监察自我鉴定
2014/02/25 职场文书
我爱我校演讲稿
2014/05/21 职场文书
举起手来观后感
2015/06/09 职场文书
2016年领导干部廉政承诺书
2016/03/24 职场文书
java实现对Hadoop的操作
2021/07/01 Java/Android
Python 读取千万级数据自动写入 MySQL 数据库
2022/06/28 Python