[英]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.