繁体   English   中英

在python中,如何使用np数组有效地处理多维?

[英]In python, how to use np array to manipulate multi-dimension efficiently?

我的数据集中有成千上万的32 X 32 RGB图像。 例如。

X_train,形状(123123、32、32、3)

我想将rgb变灰,并将形状更改为(123123,32,32,1)

我这里的代码非常不够,我想知道什么是最好的方法。 我在AWS G2或P2主机上,所以我有GPU。

谢谢。

def grayedOut(x) :
    out = []

    for n in range(len(x)) :
        nv = []
        for i in range(len(x[n])) :
            iv = []
            for j in range(len(x[n,i])) :
                r,g,b = x[n,i,j,0], x[n,i,j,1], x[n, i,j,2]
                gray = np.uint8(0.2989 * r + 0.5870 * g + 0.1140 * b)

                iv.append(np.asarray([gray]))
            nv.append(iv)
        out.append(nv)
    return np.asarray(out)

你可以简单地写

def grayedOut(x):
    return x.dot([0.2989, 0.5870, 0.1140])[..., np.newaxis].astype(np.uint8) 
  • x.dot([0.2989, 0.5870, 0.1140]) :计算每个像素的灰度分量。 结果形状将为(123123, 32, 32)
  • [..., np.newaxis] :为结果创建一个新轴,并给出所需的形状(123123, 32, 32, 1)
  • .astype(np.uint8) :将数据类型转换为uint8。

假设images所有 RGB图像的数组。 然后,以下代码生成灰度图像数组:

coeffs = np.array([0.2989, 0.5870, 0.1140])
gray = np.apply_along_axis(coeffs.dot, 3, images).astype(np.uint8)

我希望这段代码比您的三重循环更快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM