将图像调整为正方形
Resizing image to square
我有很多不同尺寸的图片,从 1100x200 到 100x20。现在,我想将所有这些图像调整为大小相等的正方形(例如 256x256)。
我想调整这样一张图片的大小:
我想要一张像这样的新方形图片:
我试过这段代码:
from PIL import Image, ImageOps
original_image = Image.open(r"path\to\images\*.png")
size = (256, 256)
fit_and_resized_image = ImageOps.fit(original_image, size, Image.ANTIALIAS)
我得到的不是所需的方形图像,而是这样的图像:
很遗憾,这是一张裁剪后的原始比例图片,而不是我想要的图片类型。
使用缩略图
from PIL import Image
original_image = Image.open(r"path\to\images\*.png")
size = (256, 256)
original_image.thumbnail(size, Image.ANTIALIAS)
如果您要进行大量图像处理,OpenCV 是一个不错的选择。
import cv2
img = cv2.imread('path/to/file.png')
print (img.shape)
size = (256, 256)
img2 = cv2.resize(img, size)
print (img2.shape) # (256, 256)
cv2.imshow('img1', img)
cv2.imshow('img2', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
我有很多不同尺寸的图片,从 1100x200 到 100x20。现在,我想将所有这些图像调整为大小相等的正方形(例如 256x256)。
我想调整这样一张图片的大小:
我想要一张像这样的新方形图片:
我试过这段代码:
from PIL import Image, ImageOps
original_image = Image.open(r"path\to\images\*.png")
size = (256, 256)
fit_and_resized_image = ImageOps.fit(original_image, size, Image.ANTIALIAS)
我得到的不是所需的方形图像,而是这样的图像:
很遗憾,这是一张裁剪后的原始比例图片,而不是我想要的图片类型。
使用缩略图
from PIL import Image
original_image = Image.open(r"path\to\images\*.png")
size = (256, 256)
original_image.thumbnail(size, Image.ANTIALIAS)
如果您要进行大量图像处理,OpenCV 是一个不错的选择。
import cv2
img = cv2.imread('path/to/file.png')
print (img.shape)
size = (256, 256)
img2 = cv2.resize(img, size)
print (img2.shape) # (256, 256)
cv2.imshow('img1', img)
cv2.imshow('img2', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()