繁体   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