包含编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!!
pip install pillow
from PIL import Image
# 打开图片
img = Image.open('example.jpg')
# 显示图片
img.show()
width, height = img.size
print(f"图片尺寸: {width}x{height}")
# 裁剪参数:左上角坐标 (left, top) 和右下角坐标 (right, bottom)
cropped_img = img.crop((50, 50, 200, 200))
cropped_img.show()
resized_img = img.resize((400, 400))
resized_img.show()
rotated_img = img.rotate(90) # 逆时针旋转 90 度
rotated_img.show()
# 水平翻转
flipped_horizontal = img.transpose(Image.FLIP_LEFT_RIGHT)
flipped_horizontal.show()
# 垂直翻转
flipped_vertical = img.transpose(Image.FLIP_TOP_BOTTOM)
flipped_vertical.show()
# 转换为灰度图
gray_img = img.convert('L')
gray_img.show()
# 转换为黑白图
bw_img = img.convert('1')
bw_img.show()
bordered_img = ImageOps.expand(img, border=10, fill='red')
bordered_img.show()
from PIL import ImageDraw
# 打开另一张图片
overlay_img = Image.open('overlay.png')
# 创建一个新的空白图像
result = Image.new('RGB', img.size)
# 将两张图片粘贴到新图像上
result.paste(img, (0, 0))
result.paste(overlay_img, (0, 0), overlay_img)
result.show()
# 创建一个新的空白图像
new_img = Image.new('RGB', (img.width * 2, img.height))
# 将两张图片拼接在一起
new_img.paste(img, (0, 0))
new_img.paste(img, (img.width, 0))
new_img.show()
from PIL import ImageFilter
# 应用模糊滤镜
blurred_img = img.filter(ImageFilter.BLUR)
blurred_img.show()
# 应用锐化滤镜
sharpened_img = img.filter(ImageFilter.SHARPEN)
sharpened_img.show()
from PIL import Image, ImageDraw, ImageFont
# 打开背景图片
background = Image.open('background.jpg')
# 打开员工照片
photo = Image.open('employee.jpg')
# 调整照片大小
photo_resized = photo.resize((200, 200))
# 添加边框
photo_bordered = ImageOps.expand(photo_resized, border=10, fill='white')
# 粘贴照片
background.paste(photo_bordered, (50, 50), photo_bordered)
# 创建绘图对象
draw = ImageDraw.Draw(background)
# 设置字体
font = ImageFont.truetype('arial.ttf', 36)
# 绘制名字
name_text = 'John Doe'
draw.text((300, 100), name_text, font=font, fill=(0, 0, 0))
# 绘制职位
position_text = 'Software Engineer'
draw.text((300, 150), position_text, font=font, fill=(0, 0, 0))
# 应用模糊滤镜
background_blurred = background.filter(ImageFilter.BLUR)
background_blurred.show()
from PIL import Image, ImageDraw, ImageFont, ImageOps, ImageFilter
# 打开背景图片
background = Image.open('background.jpg')
# 打开员工照片
photo = Image.open('employee.jpg')
# 调整照片大小
photo_resized = photo.resize((200, 200))
# 添加边框
photo_bordered = ImageOps.expand(photo_resized, border=10, fill='white')
# 粘贴照片
background.paste(photo_bordered, (50, 50), photo_bordered)
# 创建绘图对象
draw = ImageDraw.Draw(background)
# 设置字体
font = ImageFont.truetype('arial.ttf', 36)
# 绘制名字
name_text = 'John Doe'
draw.text((300, 100), name_text, font=font, fill=(0, 0, 0))
# 绘制职位
position_text = 'Software Engineer'
draw.text((300, 150), position_text, font=font, fill=(0, 0, 0))
# 应用模糊滤镜
background_blurred = background.filter(ImageFilter.BLUR)
# 显示最终结果
background_blurred.show()
在这个实战案例中,我们综合运用了前面介绍的各种图像处理技术:
包含编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!!