【问题标题】:How to resize a square image to rectangle with white borders in Python如何在Python中将方形图像调整为带白色边框的矩形
【发布时间】:2020-03-13 22:40:00
【问题描述】:

我有许多 708x708 的图片,我需要将它们调整为 500x250 像素,并保持比例不变。我想这可以通过Image.thumbnail('image.jpg') 将实际图像的大小调整为 250x250 并添加两个白色边框来填充剩余空间来完成。但是,我不知道如何做后者。下面的代码给了我 250x250px 的缩略图。

image = img
img
image.thumbnail((500, 250))
image.save('image_thumbnail.jpg')

print(image.size) 

问题类似于this one

任何建议将不胜感激!

【问题讨论】:

标签: python image-processing python-imaging-library


【解决方案1】:

我尝试了以下方法:首先,我制作了一个尺寸为 (250,250) 的缩略图,并使用 ImageOps.expand 更改图像以添加两个白色边框以形成尺寸 (250, 250)。

from PIL import Image, ImageOps
img = Image.open('801595.jpg')
img.thumbnail((500, 250))
print(img.size)
img_with_border = ImageOps.expand(img, border = (125, 0) ,fill='white')
img_with_border.save('imaged-with-border2.jpg')

【讨论】:

    【解决方案2】:

    尝试以下方法:

    import cv2
    import numpy as np
    
    img = cv2.imread('myimage.jpg', cv2.IMREAD_UNCHANGED)
    
    print('Original Dimensions : ',img.shape)
    
    width = int(img.shape[1] * 35.31 / 100) # 250/708 is 35%
    height = int(img.shape[0] * 35.31 / 100)
    dim = (width, height)
    resized_image = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
    
    print('Resized_image Dimensions : ',resized_image.shape)
    
    
    row, col = resized_image.shape[:2]
    bottom = resized_image[row-2:row, 0:col]
    
    bordersize = 125
    border = cv2.copyMakeBorder(
        resized_image,
        top=bordersize,
        bottom=bordersize,
        left=0,
        right=0,
        borderType=cv2.BORDER_CONSTANT,
        value=[255, 255, 255]
    )
    
    cv2.imshow('image', resized_image)
    cv2.imshow('left', bottom)
    cv2.imshow('right', border)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    【讨论】:

    • 代码只是重新定位图像,并没有按要求调整大小。
    【解决方案3】:

    skimage 包中检查此method。有一个名为mode 的参数,您可以在其中控制所需的行为。

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 2012-08-11
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多