簡體   English   中英

使用numpy更好地進行圖像標准化

[英]Better image normalization with numpy

我已經實現了標題中描述的目標,但我想知道是否有更有效(或更普遍)的方法。 首先讓我介紹一下這個問題。

我有一組不同大小的圖像,但寬高比小於(或等於)2 (可以是任何東西,但現在要說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))            

關於此代碼有一條注釋:

  • 我將縮放比例取整,因為它使最終高度等於max_height,我敢肯定這不是最好的方法,但是它是可行的(這里有任何建議)。 我想做的是擴大圖像,保持比例直到其高度等於max_height。 這是我到目前為止找到的唯一解決方案,並且可以立即使用,插值效果很好。

所以我的最后一個問題是:

是否有更好的方法來實現上述解釋(圖像歸一化)? 您認為我本可以做不同的事情嗎? 我沒有遵循常見的良好做法嗎?

在此先感謝您的時間。

  • 取而代之的ndimage.zoom你可以使用scipy.misc.imresize 此功能允許您將目標大小指定為元組,而不是通過縮放系數。 因此,您np.resize稍后調用np.resize即可完全​​獲得所需的大小。

    請注意, scipy.misc.imresizescipy.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM