原圖是這樣的:

通過以下設定使用此
我試圖重現的最終結果(唯一的區別是我要對頂部的影像進行重新調整,寬度也為 1080)是這樣的:

很明顯,模糊影像中有縮放效果,所以當我使用調整大小來保持縱橫比和盡可能高的質量時,我im = im.resize((1080,1080), resample=Image.Resampling.LANCZOS)使用resample=Image.Resampling.LANCZOS了不按比例生成縮放:
from PIL import Image, ImageFilter, ImageChops
import numpy
import cv2
def remove_border(file_img):
im = Image.open(file_img)
bg = Image.new("RGB", im.size, im.getpixel((0,0)))
diff = ImageChops.difference(im.convert("RGB"), bg)
diff = ImageChops.add(diff, diff, 2.0, -30)
bbox = diff.getbbox()
if bbox:
return im.crop(bbox)
def resize_blur(img_blur,sizers):
img_blur = img_blur.resize(sizers, resample=Image.Resampling.LANCZOS)
img_blur = img_blur.filter(ImageFilter.GaussianBlur(10))
return img_blur
def resize_width_main(img_border,size_width):
img_width = img_border
basewidth = size_width
wpercent = (basewidth/float(img_width.size[0]))
hsize = int((float(img_width.size[1])*float(wpercent)))
img_width = img_width.resize((basewidth,hsize), Image.Resampling.LANCZOS)
return img_width
def center_overlay(name_file,overlay,background):
img = numpy.asarray(overlay)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
h, w = img.shape[:2]
back = numpy.asarray(background)
back = cv2.cvtColor(back, cv2.COLOR_RGB2BGR)
hh, ww = back.shape[:2]
yoff = round((hh-h)/2)
xoff = round((ww-w)/2)
result = back.copy()
result[yoff:yoff h, xoff:xoff w] = img
cv2.imwrite(name_file, result)
def main():
img_border = remove_border('resized_download.png')
img_blur = resize_blur(img_border, (1080,1080))
img_width = resize_width_main(img_border, 1080)
center_overlay('resized.png', img_width, img_blur)
if __name__ == '__main__':
main()
但目前的結果是這樣的:

uj5u.com熱心網友回復:
幾點觀察。
你的remove_border功能做的不多;當我用你的測驗影像嘗試它時,它所做的只是從左側移除 9 個像素。也許它有一個錯誤。冒著忽略切斯特頓圍欄的教訓的風險,我會說你不需要它并且可以完全消除它。
在調整大小之前進行模糊比反過來做更有意義。
當您調整模糊影像的大小時,您無需過多擔心重采樣過濾器的質量。我不會使用NEAREST,但BILINEAR應該完全足夠且相當快。
調整影像大小時,新舊尺寸應具有相同的縱橫比,否則會失真。resample 方法對此沒有任何影響。您正在將矩形調整為正方形,從而導致嚴重失真。您可以在調整大小之前將原件裁剪為所需的縱橫比,或在調整大小后對其進行裁剪。先收割會更有效率。
def resize_to_target(im, target_size, resample=Image.BILINEAR):
''' Resize an image to a target size. If the aspect ratio
of the original image is different from the target, the
image will be cropped to the destination aspect ratio
before resizing.
'''
if (im.size[0] / im.size[1]) < (target_size[0] / target_size[1]):
# if (im.size[0] * target_size[1]) != (target_size[0] * im.size[1]):
# Existing image is narrower, crop top and bottom
crop_height = round(im.size[0] * target_size[1] / target_size[0])
if crop_height < im.size[1]:
top = (im.size[1] - crop_height) // 2
bottom = top crop_height
im = im.crop((0, top, im.size[0], bottom))
else:
# existing image is wider, crop left and right
crop_width = round(im.size[1] * target_size[0] / target_size[1])
if crop_width < im.size[0]:
left = (im.size[0] - crop_width) // 2
right = left crop_width
im = im.crop((left, 0, right, im.size[1]))
return im.resize(target_size, resample=resample)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/495958.html
