我有一個解析度為 816x624 的影像,需要從中制作一個 640x640 的影像。
為此,我必須裁剪長邊(居中),并用黑色(居中)填充短邊。生成的影像應該是起始影像的中心,頂部和底部有一個黑色的小條。
如何才能做到這一點?
我試過:
crop_img = img1[int(h1 / 2 - 640 / 2):int(h1 / 2 640 / 2),
int(w1 / 2 - 640 / 2):int(w1 / 2 640/ 2)]
但這不起作用,因為 h1 我小于 640。

uj5u.com熱心網友回復:
給定輸入影像img、預期高度h和預期寬度w:
def resize_img(img, h, w):
#cut the image
cutted_img = img[
max(0, int(img.shape[0]/2-h/2)):min(img.shape[0], int(img.shape[0]/2 h/2)),
max(0, int(img.shape[1]/2-w/2)):min(img.shape[1], int(img.shape[1]/2 w/2)),
]
#pad the image
padded_img = np.zeros(shape=(h,w,3), dtype=img.dtype)
padded_img[
int(padded_img.shape[0]/2-cutted_img.shape[0]/2):int(padded_img.shape[0]/2 cutted_img.shape[0]/2),
int(padded_img.shape[1]/2-cutted_img.shape[1]/2):int(padded_img.shape[1]/2 cutted_img.shape[1]/2),
] = cutted_img
return padded_img
一些例子:
url = "https://www.planetware.com/wpimages/2020/02/france-in-pictures-beautiful-places-to-photograph-eiffel-tower.jpg"
response = requests.get(url)
start_img = np.array(PIL.Image.open(BytesIO(response.content)))
plt.imshow(start_img)
plt.show() #shape = (487, 730, 3)

plt.imshow(resize_img(start_img, 640, 640))
plt.show() #shape = (640, 640, 3)

我在其他一些圖片上進行了測驗:
shape = (1020, 680, 3)

shape = (450, 254, 3)

shape = (847, 564, 3)

所有調整大小的影像都有大小(640, 640, 3)并且似乎被正確填充。
PS。我使用了以下庫:
import numpy as np
from matplotlib import pyplot as plt
import PIL
import requests
from io import BytesIO
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/528663.html
