简介

选择合适的库

Pillow库

from PIL import Image

# 打开图像
img = Image.open('image.jpg')

# 定义裁剪区域
left = 100
top = 100
right = 300
bottom = 300

# 裁剪图像
cropped_img = img.crop((left, top, right, bottom))

# 保存裁剪后的图像
cropped_img.save('cropped_image.jpg')

OpenCV库

import cv2

# 读取图像
img = cv2.imread('image.jpg')

# 定义裁剪区域
left = 100
top = 100
right = 300
bottom = 300

# 裁剪图像
cropped_img = img[top:bottom, left:right]

# 保存裁剪后的图像
cv2.imwrite('cropped_image.jpg', cropped_img)

裁剪技巧

按比例裁剪

from PIL import Image

# 打开图像
img = Image.open('image.jpg')

# 获取原始图像的宽度和高度
width, height = img.size

# 定义裁剪比例
ratio = 0.5

# 计算裁剪区域
left = (width - int(width * ratio)) // 2
top = (height - int(height * ratio)) // 2
right = left + int(width * ratio)
bottom = top + int(height * ratio)

# 裁剪图像
cropped_img = img.crop((left, top, right, bottom))

# 保存裁剪后的图像
cropped_img.save('cropped_image.jpg')

裁剪特定区域

如果我们需要裁剪图像的特定区域,可以使用以下代码:

from PIL import Image

# 打开图像
img = Image.open('image.jpg')

# 定义裁剪区域
left = 100
top = 100
right = 200
bottom = 200

# 裁剪图像
cropped_img = img.crop((left, top, right, bottom))

# 保存裁剪后的图像
cropped_img.save('cropped_image.jpg')

总结