python 中心裁剪图片
时间: 2023-04-07 15:02:06 浏览: 266
可以使用PIL库中的Image类来实现中心裁剪图片,具体代码如下:
```python
from PIL import Image
def center_crop(image_path, output_path, size):
image = Image.open(image_path)
width, height = image.size
new_size = min(width, height)
left = (width - new_size) // 2
top = (height - new_size) // 2
right = (width + new_size) // 2
bottom = (height + new_size) // 2
image = image.crop((left, top, right, bottom))
image = image.resize((size, size), Image.ANTIALIAS)
image.save(output_path)
```
其中,image_path为原始图片路径,output_path为裁剪后保存的路径,size为裁剪后的尺寸。
相关问题
python opencv 裁剪图片
在Python中,使用OpenCV库可以很方便地进行图像和裁剪。下面是一个简单的示例代码,演示了如何使用OpenCV裁剪图片:
```python
import cv2
# 读取图片
image = cv2.imread('image.jpg')
# 设置裁剪区域的坐标
x = 100
y = 100
width = 200
height = 200
# 裁剪图片
cropped_image = image[y:y+height, x:x+width]
# 显示裁剪后的图片
cv2.imshow('Cropped Image', cropped_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上面的代码中,首先使用`cv2.imread()`函数读取待裁剪的图片。然后,通过设置裁剪区域的坐标和大小,使用切片操作来裁剪图片。最后,使用`cv2.imshow()`函数显示裁剪后的图片,并通过`cv2.waitKey()`和`cv2.destroyAllWindows()`函数来等待用户按下键盘并关闭窗口。
请注意,上述代码中的`image.jpg`是待裁剪的图片文件名,你需要将其替换为你自己的图片文件名。
python自动裁剪图片
要使用Python自动裁剪图片,可以使用Pillow库。以下是一个基本的示例代码,它将打开一个名为“image.jpg”的图像,然后将其裁剪为200x200像素大小的正方形。你可以根据需要修改此代码来适应你的应用场景:
```python
from PIL import Image
# 打开图像并获取其尺寸
image = Image.open('image.jpg')
width, height = image.size
# 裁剪图像并保存
if width > height:
left = (width - height) // 2
right = (width + height) // 2
top = 0
bottom = height
else:
left = 0
right = width
top = (height - width) // 2
bottom = (height + width) // 2
image = image.crop((left, top, right, bottom))
image = image.resize((200, 200))
image.save('cropped_image.jpg')
```
在上面的代码中,我们首先使用`Image.open()`打开要裁剪的图像。我们然后获取图像的宽度和高度,并使用这些值计算出要裁剪的区域。最后,我们使用`crop()`方法将图像裁剪为所需的大小,并使用`resize()`方法缩放图像以适应需要的大小。最终,我们使用`save()`方法将裁剪后的图像保存到磁盘上。
阅读全文
相关推荐












