使用pthon将图片裁剪成指定正方形大小
时间: 2023-06-04 11:04:40 浏览: 243
可以使用PIL库来实现这个功能。具体步骤如下:
1. 使用PIL库打开图片:`img = Image.open('path/to/image.jpg')`
2. 获取原始图片的宽和高:`width, height = img.size`
3. 计算要裁剪的区域:如果宽大于高,裁剪出中心部分的正方形区域;如果高大于宽,同样裁剪出中心部分的正方形区域。具体代码如下:
```
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
region = img.crop((left, top, right, bottom))
```
4. 将裁剪后的区域重新调整为指定大小:`square_img = region.resize((size, size), Image.ANTIALIAS)`
5. 保存新图片:`square_img.save('path/to/new_image.jpg')`
相关问题
请为我提供代码将图片按照指定大小裁剪成正方形
好的,以下是一段 Python 代码可以将图片按照指定大小裁剪成正方形:
```python
from PIL import Image
def crop_to_square(image_path, size):
with Image.open(image_path) as image:
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))
return image
# example usage
square_image = crop_to_square("path/to/image.jpg", 256)
square_image.save("path/to/square_image.jpg")
```
请注意,上述代码依赖于 `Pillow` 库,你需要首先安装 `Pillow` 才能运行该代码。
torch的transform中用什么可以把图片变成正方形,并且没有裁剪
在PyTorch的`torchvision.transforms`模块中,你可以使用`CenterCrop`或`Pad`函数来把图片变成正方形,同时保持原始尺寸不变,而不会进行裁剪。
1. `CenterCrop(size)`:这个函数会从输入图像的中心裁取指定大小`size`的区域。如果原图不是正方形且需要变为正方形,你需要保证输入的裁切尺寸能整除原始宽度和高度,使得两边都能对齐。
2. `Pad(padding, fill=0, padding_mode='constant')`:此函数会在图片四周添加填充,使得图片变大成为正方形。通过设置合适的padding值,可以将图片的长边和短边都加宽到相同的长度,不会丢失任何内容。
例如,假设你有一个原始图片`img`,原先是HxW像素,想要使其变成正方形,可以这样做:
```python
import torchvision.transforms as transforms
# 假设目标边长是128
target_size = 128
# 如果图片原本不是正方形,用Pad
if img.shape[0] != img.shape[1]:
transform = transforms.Pad((target_size - img.shape[0] % target_size, 0), fill=0)
img = transform(img)
# 然后再转换为正方形
img = transforms.CenterCrop(target_size)(img)
```
阅读全文
相关推荐













