我得到了一個形狀為 388x388x1 的 1 通道 numpy 陣列,其值在 1-150 范圍內作為 ML 推理的輸出。我需要使用最近鄰插值調整陣列大小以形成 5000x4000x1。
目前我正在使用 PILs 調整大小。它可以作業,但必須為此匯入 PIL 感覺過于復雜。
output = np.random.randint(150, size=(388, 388))
width, height = 4000, 5000
pilImage = Image.fromarray(pred.astype(np.uint8))
pilImageResized = pilImage.resize((width, height), Image.NEAREST)
resizedOutput = np.array(pilImageResized).astype(np.uint8)
是否有更簡單的方法可以在 numpy 中實作我想要的?(不使用cv2.resize,scipy.interpolate或PIL)
uj5u.com熱心網友回復:
您可以通過構建將每個輸出位置映射到輸入中的源的索引陣列來非常簡單地進行 NN 插值。您必須定義/假設一些事情才能有意義地做到這一點。例如,我假設您希望將每個輸出行的左邊緣與輸入行的左邊緣相匹配,將像素視為表面元素,而不是點源。在后一種情況下,我會將中心匹配起來,從而導致邊緣區域看起來略微被截斷。
一種簡單的方法是引入一個坐標系,其中整數位置指向輸入像素的中心。這意味著影像實際上在每個軸上從 -0.5px 到 (N - 0.5)px。這也意味著舍入輸出像素的中心會自動將它們映射到最近的輸入像素:

這將使每個輸入像素在輸出中具有近似相等的表示,直到舍入:
in_img = np.random.randint(150, size=(388, 388, 1), dtype=np.uint8) 1
in_height, in_width, *_ = in_img.shape
out_width, out_height = 4000, 5000
ratio_width = in_width / out_width
ratio_height = in_height / out_height
rows = np.round(np.linspace(0.5 * (ratio_height - 1), in_height - 0.5 * (ratio_height 1), num=out_height)).astype(int)[:, None]
cols = np.round(np.linspace(0.5 * (ratio_width - 1), in_width - 0.5 * (ratio_width 1), num=out_width)).astype(int)
out_img = in_img[rows, cols]
就是這樣。不需要復雜的函式,并且輸出保證保留輸入的型別,因為它只是一個花哨的索引操作。
您可以簡化代碼并將其包裝起來以備將來重用:
def nn_resample(img, shape):
def per_axis(in_sz, out_sz):
ratio = 0.5 * in_sz / out_sz
return np.round(np.linspace(ratio - 0.5, in_sz - ratio - 0.5, num=out_sz)).astype(int)
return img[per_axis(img.shape[0], shape[0])[:, None],
per_axis(img.shape[1], shape[1])]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341079.html
