首页 > 编程语言 >Python工具箱系列(五十)

Python工具箱系列(五十)

时间:2024-03-05 09:23:03浏览次数:22  
标签:Python text imglist cols ImageFilter im 工具箱 五十 out

使用PIL加工图片

 



常见的图片操作包括但不限于:

•大小进行变化

•旋转

•翻转

•使用滤镜进行处理

•剪切

     以下python代码演示了如何将一幅美女图进行多种加工处理,并且汇集在一起,形成一个类似于照片墙的相关操作。

from PIL import Image
from PIL import ImageFilter
from PIL import ImageEnhance
from PIL import ImageDraw, ImageFont
import math


def text(image, text):
    """
    给图片加上文字
    truetype设置字体、文字大小
    stxingka.ttf华文行楷 simkai.ttf 楷体 simli.ttf 隶书

    Args:
        image (object): 图片对象
        text (string): 要加入的文字
    """

    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("C:\\WINDOWS\\Fonts\\simkai.ttf", 80)
    draw.text((50, 200), (text), fill='#0000ff', font=font)


def gallery(inputfilename, outputfilename,cols=3):
    """
    做一个图片墙

    Args:
        inputfilename (string): 输入文件名称
        outputfilename (string): 输出文件名称
        cols(int): 显示的列数。缺省是3列显示
    """
    filters = [ImageFilter.BLUR, ImageFilter.CONTOUR, ImageFilter.DETAIL, ImageFilter.EDGE_ENHANCE, ImageFilter.EDGE_ENHANCE_MORE,
               ImageFilter.EMBOSS, ImageFilter.FIND_EDGES, ImageFilter.SHARPEN, ImageFilter.SMOOTH, ImageFilter.SMOOTH_MORE]

    filtername = ['ImageFilter.BLUR', 'ImageFilter.CONTOUR', 'ImageFilter.DETAIL', 'ImageFilter.EDGE_ENHANCE', 'ImageFilter.EDGE_ENHANCE_MORE',
                  'ImageFilter.EMBOSS', 'ImageFilter.FIND_EDGES', 'ImageFilter.SHARPEN', 'ImageFilter.SMOOTH', 'ImageFilter.SMOOTH_MORE']

    imglist = list()

    # 原图
    im = Image.open(inputfilename)

    # 计算缩放比例
    imagewidth, imageheight = im.size

    # 以宽为标准进行缩。
    targetwidth = math.floor(1920/cols)
    rate = targetwidth/imagewidth
    targetheight = math.ceil(imageheight*rate)

    out = im.copy()
    text(out, "原图")
    imglist.append(out)

    # 旋转
    out = im.copy().rotate(45)
    text(out, '旋转45度')
    imglist.append(out)

    # 对称翻转
    out = im.copy().transpose(Image.Transpose.FLIP_LEFT_RIGHT)
    text(out, '对称翻转')
    imglist.append(out)

    # 加滤镜
    for fi, name in zip(filters, filtername):
        out = im.filter(fi)
        text(out, name)
        imglist.append(out)

    # 强化对比
    enh = ImageEnhance.Contrast(im)
    out = enh.enhance(1.3)
    text(out, 'enhanced')
    imglist.append(out)

    # cut
    box = (500, 400,  900, 800)
    out = im.crop(box)
    text(out, 'cut')
    imglist.append(out)

    # 水平排列
    count = len(imglist)
    if count % cols == 0:
        rows = count // cols
    else:
        rows = count // cols + 1

    new_width = 1920
    new_height = math.ceil(rows * targetheight)

    final = Image.new('RGB', (new_width, new_height))

    for row in range(rows):
        for col in range(cols):
            index = row*cols+col
            if index < count:
                img = imglist[row*cols+col]
                width, _ = img.size
                if width > targetwidth:
                    out = img.resize((targetwidth, targetheight))
                else:
                    out = img

                final.paste(out, (col * targetwidth, row * targetheight))
    final.save(outputfilename)


gallery(r'd:\test\girl.png',r'd:\test\gallery.png')

运行后的效果如下图所示。

image.png

在这个照片墙上,每种加工的名称都输出到图片的左上侧。 最后一个图是剪切图,小于照片墙预留的空间,所以显得奇怪一些。

 

 

标签:Python,text,imglist,cols,ImageFilter,im,工具箱,五十,out
From: https://www.cnblogs.com/shanxihualu/p/18053258

相关文章

  • python与人工智能
    由于无文化是机器学习学是大模型一些就用开发,大部份教学都是python方便实验,就导致了要对python第二遍在过一下相关知识,虽然10年前学一遍python和web开发,估记也忘记差不多了,主要是针对ES文件检索,向量数据库,字符串处理,ESP32 fask这些也不太熟了,所以整理一下pythonAI应用开发......
  • python 语法之 print 函数和 input 函数
    print函数input函数案例一:圆的周长importmaths=input("圆的半径:\n")s=float(s)c=2*math.pi*sprint(f"圆的周长,{c:.2f}")w=input("请输入天气情况(可选项:晴、阴):")ifw=="晴天":print("play")else:print(f"天气{w}不玩")......
  • python益智游戏五子棋的二次创新
    五子棋是一种源自中国的传统棋类游戏,起源可以追溯到古代。它是一种两人对弈的游戏,使用棋盘和棋子进行。棋盘通常是一个15×15的网格,棋子分为黑白两色,双方轮流在棋盘上落子。游戏的目标是通过在棋盘上落子,使自己的五个棋子在横向、纵向或斜向形成连续的线路,从而获胜。五子棋被认......
  • WSGI介绍:Python 首先了解
    1.1什么是WSGI首先介绍几个关于WSGI相关的概念WSGI:全称是WebServerGatewayInterface,WSGI不是服务器,python模块,框架,API或者任何软件,只是一种规范,描述webserver如何与webapplication通信的规范。server和application的规范在PEP3333中有具体描述。要实现WSGI协议,必须同时实......
  • python-pip更改下载路径,解决超时问题
    有时pip安装包时,会提示pip._vendor.urllib3.exceptions.ReadTimeoutError:HTTPSConnectionPool(host='files.pythonhosted.org',port=443):Readtimedout.原因跟解决方式PyPI镜像:考虑使用PyPI的镜像站点。中国用户经常遇到与files.pythonhosted.org的连接问题,因此他们经常......
  • python内置方法(重点)
    方法作用示例输出upper全部大写"hello".upper()"HELLO"lower全部小写"Hello".lower()"hello"startswith()是否以a开头"Yuan".startswith("Yu")Trueendswith()是否以a结尾"Yuan".endswith("a&qu......
  • python运算符
    【1】算数运算符运算符说明实例结果+加1+12-减1-10*乘1*33/除法(和数学中的规则一样)4/22//整除(只保留商的整数部分)7//23%取余,即返回除法的余数7%21**幂运算/次方运算,即返回x的y次方2**416,即24【2】赋值运算符......
  • python数据类型与字符串常用方法
    int-py2中有:int/long;py3中有int。-强制转换:int(''76"")-除法:py2(多加一行代码)和py3(正常)boolTrue/False(其他语言:true/false)特殊为False的其他类型:0和""str独有功能upper/lowerreplacestrip/lstrip/rstripisdigitsplit/r......
  • python基础语法
    (1)注释注释就是对代码的解释和说明,其目的是让人们能够更加轻松地了解代码。注释是编写程序时,写程序的人给一个语句、程序段、函数等的解释或提示,能提高程序代码的可读性。一般情况下,合理的代码注释应该占源代码的1/3左右。注释只是为了提高公认阅读,不会被解释器执行。Python......
  • python变量命名规范
    简单地理解,标识符就是一个名字,就好像我们每个人都有属于自己的名字,它的主要作用就是作为变量、函数、类、模块以及其他对象的名称。Python中标识符的命名不是随意的,而是要遵守一定的命令规则标识符是由字符(A~Z和a~z)、下划线和数字组成,但第一个字符不能是数字。标识符不能和......