pillow包

Pillow是Python 3中用于图像处理的库,基于PIL包。它提供了缩放、旋转、滤镜等功能。文章介绍了如何安装Pillow,并详细讲解了如何使用Pillow随机生成验证码,包括设置RGB颜色、随机字母数字、字体颜色和背景颜色,以及应用滤镜和保存图片的操作。
部署运行你感兴趣的模型镜像

pillow包

pillow:(了解)(python image library)是一个有关图像图片处理的包,这个包底层用的C C++,但PIL包是python2下使用。所以又更新了一个适合python3版本的、基于PIL包的新包pillow。

安装pillow:

(cmd) pip install pillow

引入:from PIL import Image, ImageFilter

image_path = Image.open('img.jpg')    
# image_path = Image.open('图片相对路径')

print(image_path.size)
width, height = image_path.size
print(width, height)

1.缩放 thumbnail

image_path.thumbnail((800,600))

两个参数,第一个参数是宽,第二个参数是高

2.保存为新图片 save

image_path.save('img', 'jpeg')    
  
# image_path.save('文件名', '保存文件格式(如:jpeg)')

3.旋转 rotate

image_rotate = image_path.rotate(90)
image_rotate.show()     
  
# 打开文件,用于临时打开

4.滤镜
ImageFilter(滤镜)
GaussianBlur高斯模糊
Color3DLUT颜色三地
BLUR默认颜色

image_ImageFilter = image_path1.filter(ImageFilter.BLUR)
image_ImageFilter.show()

image_path1.save('demo3.jpg','jpeg')
随机生成验证码

(了解)RGB:red green blue 色光三原色,(11,225,5)

引入:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random

1.随机字母

def random_char():
    return chr(random.randint(65, 90))

2.随机数字

def random_num():
    return random.randint(0,9)

3.随机字体颜色

def random_color():
    return (random.randint(150,255),random.randint(150,255),random.randint(150,255))

4.随机背景颜色

def random_color2():
    return (random.randint(30, 120), random.randint(30, 120), random.randint(30, 120))

5.生成空白背景图层

image = Image.new('RGB', size=(240, 60), color=(255, 255, 255))

6.生成绘制对象

draw = ImageDraw.Draw(image)

7.字体对象 ,字体、字号

font = ImageFont.truetype('arial.ttf', 36)

8.循环像素点并填充颜色

for x in range(0, 240):
    for y in range(0, 60):
        draw.point(xy=(x, y), fill=random_color2())

9.生成文字

for t in range(0, 4):
    draw.text((60*t+20, 10), random_char(), font=font, fill=random_color())

10.加模糊滤镜

image = image.filter(ImageFilter.BLUR)

11.保存

image.save('demo4.jpg', 'jpeg')

画点完整代码:

from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random


class Picture(object):
    def __init__(self, text_str, size, background):
        '''
        text_str: 验证码显示的字符组成的字符串
        size:  图片大小
        background: 背景颜色
        '''
        self.text_list = list(text_str)
        self.size = size
        self.background = background

    def create_pic(self):
        '''
        创建一张图片
        '''
        self.width, self.height = self.size
        self.img = Image.new("RGB", self.size, self.background)
        # 实例化画笔
        self.draw = ImageDraw.Draw(self.img)

    def create_point(self, num, color):
        '''
        num: 画点的数量
        color: 点的颜色
        功能:画点
        '''
        for i in range(num):
            self.draw.point(
                (random.randint(0, self.width), random.randint(0, self.height)),
                fill=color
            )

    def create_line(self, num, color):
        '''
        num: 线条的数量
        color: 线条的颜色
        功能:画线条
        '''
        for i in range(num):
            self.draw.line(
                [
                    (random.randint(0, self.width), random.randint(0, self.height)),
                    (random.randint(0, self.width), random.randint(0, self.height))
                ],
                fill=color
            )

    def create_text(self, font_type, font_size, font_color, font_num, start_xy):
        '''
        font_type: 字体
        font_size: 文字大小
        font_color: 文字颜色
        font_num:  文字数量
        start_xy:  第一个字左上角坐标,元组类型,如 (5,5)
        功能: 画文字
        '''
        font = ImageFont.truetype(font_type, font_size)
        self.draw.text(start_xy, " ".join(random.sample(self.text_list, font_num)), font=font, fill=font_color)

    def opera(self):
        '''
        功能:给画出来的线条,文字,扭曲一下,缩放一下,位移一下,滤镜一下。
        就是让它看起来有点歪,有点扭。
        '''
        params = [
            1 - float(random.randint(1, 2)) / 100,
            0,
            0,
            0,
            1 - float(random.randint(1, 10)) / 100,
            float(random.randint(1, 2)) / 500,
            0.001,
            float(random.randint(1, 2)) / 500
        ]
        self.img = self.img.transform(self.size, Image.PERSPECTIVE, params)
        self.img = self.img.filter(ImageFilter.EDGE_ENHANCE_MORE)


if __name__ == "__main__":
    strings = "abcdefghjkmnpqrstwxyz23456789ABCDEFGHJKLMNPQRSTWXYZ"
    size = (150, 50)
    background = 'white'
    pic = Picture(strings, size, background)
    pic.create_pic()
    pic.create_point(500, (220, 220, 220))
    pic.create_line(30, (220, 220, 220))
    pic.create_text("simsun.ttc", 24, (0, 0, 205), 5, (7, 7))
    pic.opera()
    pic.img.show()

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

<think>我们正在解决如何安装Pillow的问题。根据引用[2],我们可以使用pip命令安装Pillow。同时,引用[3]提供了使用pip安装的步骤(虽然它展示的是从源码安装,但通常我们推荐直接使用pip)。引用[1]和引用[4]则提醒我们安装后需要验证。 安装步骤: 1. 打开命令提示符(Windows键+R,输入cmd,回车) 2. 确保pip可用:输入`pip --version`查看是否正常 3. 使用pip安装Pillow:`pip install Pillow` 如果遇到网络问题,可以按照引用[2]中的方法使用国内镜像源加速下载: `pip install --default-timeout=100 Pillow -i http://pypi.douban.com/simple --trusted-host pypi.douban.com` 安装完成后,按照引用[1]的方法验证: 在Python交互环境或脚本中运行: from PIL import Image im = Image.open('1.jpg') # 需要一张名为1.jpg的图片放在当前目录 width, height = im.size print(width, height) im.show() 注意:如果安装后仍然报错,请检查: - 是否在正确的Python环境中安装?如果系统中有多个Python,可能需要使用`pip3`或指定具体Python版本的pip(如`python -m pip install Pillow`) - 安装过程是否出现错误?如果安装失败,需要根据错误信息进一步解决(如缺少依赖、权限问题等) 对于Windows环境,如果安装过程中遇到编译问题(如引用[5]中的表情可能暗示了问题),可以尝试下载预编译的二进制(通常Pillow在Windows上有预编译的wheel)。 最后,如果安装成功但导入时仍然出错,请检查安装路径(如引用[1]提到的`Lib\site-packages`)下是否有PIL文件夹(Pillow安装后名为PIL,但模块导入时使用`from PIL import Image`)。 因此,我们推荐使用pip安装,并验证安装结果。</think>要解决 Python 中 `ModuleNotFoundError: No module named 'PIL'` 错误并安装 Pillow ,请按照以下步骤操作: ### 安装步骤 1. **打开命令提示符** Windows 系统按 `Win+R` 输入 `cmd` 并回车 2. **使用 pip 安装 Pillow** 执行以下命令(推荐使用国内镜像加速): ```bash pip install --default-timeout=100 Pillow -i http://pypi.douban.com/simple --trusted-host pypi.douban.com ``` - 如果提示权限不足,添加 `--user` 参数: ```bash pip install --user Pillow ``` - 多 Python 环境时指定版本: ```bash python3.8 -m pip install Pillow # 替换为你的 Python 版本 ``` 3. **验证安装结果** ```bash pip show Pillow # 应显示版本信息如 Version: 9.5.0 ``` 4. **测试功能** 创建测试脚本 `test_pillow.py`: ```python from PIL import Image # 生成测试图片 img = Image.new('RGB', (100, 50), color='blue') img.save('test.png') print("Pillow 安装成功!") ``` 运行脚本: ```bash python test_pillow.py ``` ### 常见问题解决 | 问题现象 | 解决方案 | |---------|----------| | 超时错误 | 增加 `--default-timeout=100` 参数[^2] | | 权限拒绝 | 使用 `pip install --user Pillow` | | 多版本冲突 | 明确指定 Python 路径:`C:\Python38\python.exe -m pip install Pillow` | | 安装后仍报错 | 检查 IDE 使用的 Python 解释器是否匹配安装环境 | > **关键提示**:安装成功后导入时需使用 `from PIL import Image`(注意 `PIL` 全大写),这是 Pillow 为兼容 PIL 保留的命名空间[^1]。 ### 安装验证示例 ```python from PIL import Image im = Image.open('test_image.jpg') # 替换为实际图片路径 width, height = im.size print(f"图片尺寸: {width}x{height}") im.show() # 显示图片预览 ``` 成功执行将输出图片尺寸并显示预览窗口[^1]。 --- ### 相关问题 1. 如何解决 Pillow 安装时的 SSL 证书验证失败错误? 2. 在虚拟环境中安装 Pillow 需要注意哪些特殊步骤? 3. Pillow 如何处理不同格式的图片文件(如 JPEG/PNG/GIF)? 4. 如何通过 Pillow 实现图片的批量处理和水印添加? 5. 安装 Pillow 后出现 `ImportError: cannot import name 'ImageTK'` 错误如何解决[^1]? [^1]: 安装后需验证功能和正确导入语句 [^2]: 使用镜像源和超时参数解决网络问题
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值