使用 PIL 的 ImageOps 模块中的 expand() 函数后,您可以做您想做的事情。
from PIL import Image
from PIL import ImageOps
filename = 'C:/Users/Desktop/Maine_Coon_263.jpg'
img = Image.open(filename)
val = 10 #--- pixels to be cropped
#--- a new image with a border of 10 pixels on all sides
#--- also notice fill takes in the color of white as (255, 255, 255)
new_img = ImageOps.expand(img, border = val, fill = (255, 255, 255))
#--- cropping the image above will not result in any black portion
cropped = new_img.crop((val, val, 150, 150))
crop() 函数只接受一个参数,即需要裁剪多少部分。当传入负值时,没有功能可以处理这种情况。因此,在传递负值时,图像会被填充为黑色像素。
使用expand() 函数,您可以设置您选择的颜色,然后继续进行裁剪。
编辑
作为对您的编辑的回应,我的想法很天真,但它确实有效。
- 获取所有要裁剪的值的绝对值。您可以使用
numpy.abs()。
- 接下来是这些值中的最大值,使用
numpy.max()。
- 最后使用此值扩展图像并进行相应裁剪。
此代码将帮助您:
#--- Consider these values in a tuple that are to crop your image
crop_vals = (-10, -20, 1000, 500)
#--- get maximum value after obtaining the absolute of each
max_val = np.max(np.abs(crop_vals))
#--- add border to the image using this maximum value and crop
new_img = ImageOps.expand(img, border = max_val, fill = (255, 255, 255))
cropped = new_img.crop((max_val - 10, max_val - 20, new_img.size[0], new_img.size[1]))