[英]Better image normalization with numpy
我已經實現了標題中描述的目標,但我想知道是否有更有效(或更普遍)的方法。 首先讓我介紹一下這個問題。
我有一組不同大小的圖像,但寬高比小於(或等於)2 (可以是任何東西,但現在要說2),我想對每個圖像進行標准化,這意味着我希望所有圖像都具有一樣的大小。 具體來說,我將這樣做:
請記住,圖像表示為灰度值[0,255]的Numpy矩陣。
這就是我現在在Python中執行的方式:
max_height = numpy.max([len(obs) for obs in data if len(obs[0])/len(obs) <= 2])
for obs in data:
if len(obs[0])/len(obs) <= 2:
new_img = ndimage.zoom(obs, round(max_height/len(obs), 2), order=3)
missing_cols = max_height * 2 - len(new_img[0])
norm_img = []
for row in new_img:
norm_img.append(np.pad(row, (0, missing_cols), mode='constant', constant_values=255))
norm_img = np.resize(norm_img, (max_height, max_height*2))
關於此代碼有一條注釋:
所以我的最后一個問題是:
是否有更好的方法來實現上述解釋(圖像歸一化)? 您認為我本可以做不同的事情嗎? 我沒有遵循常見的良好做法嗎?
在此先感謝您的時間。
取而代之的ndimage.zoom
你可以使用scipy.misc.imresize
。 此功能允許您將目標大小指定為元組,而不是通過縮放系數。 因此,您np.resize
稍后調用np.resize
即可完全獲得所需的大小。
請注意, scipy.misc.imresize
在scipy.misc.imresize
調用PIL.Image.resize
,因此PIL(或Pillow)是依賴項。
代替在for-loop
中使用np.pad
,您可以首先為所需的數組norm_arr
分配空間:
norm_arr = np.full((max_height, max_width), fill_value=255)
然后將調整大小的圖像new_arr
復制到norm_arr
:
nh, nw = new_arr.shape norm_arr[:nh, :nw] = new_arr
例如,
from __future__ import division
import numpy as np
from scipy import misc
data = [np.linspace(255, 0, i*10).reshape(i,10)
for i in range(5, 100, 11)]
max_height = np.max([len(obs) for obs in data if len(obs[0])/len(obs) <= 2])
max_width = 2*max_height
result = []
for obs in data:
norm_arr = obs
h, w = obs.shape
if float(w)/h <= 2:
scale_factor = max_height/float(h)
target_size = (max_height, int(round(w*scale_factor)))
new_arr = misc.imresize(obs, target_size, interp='bicubic')
norm_arr = np.full((max_height, max_width), fill_value=255)
# check the shapes
# print(obs.shape, new_arr.shape, norm_arr.shape)
nh, nw = new_arr.shape
norm_arr[:nh, :nw] = new_arr
result.append(norm_arr)
# visually check the result
# misc.toimage(norm_arr).show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.