2017-04-21 163 views
1

所以我有一批彩色图像,我想让它们变成灰度。唯一的问题是,有时图像的形状是[batch_size, channels, height, width],有时它们是[batch_size, height, width, channels]。我需要一个需要一批彩色图像(不管它有两个形状中的哪一个)的函数,并且提供一批形状为[batch_size, height, width, channels](当然,通道为1)的灰度图像。在python中将图像从彩色批量转换为灰度

到目前为止,我有这个功能:

from scipy import misc 

def color_to_grayscale(image_batch, dim_order='NHWC'): 

    grayscale_batch = np.array() 

    if dim_order='NCHW': 
    image_batches = np.transpose(image_batch, [0, 2, 3, 1]) 
    else: 
    image_batches = image_batch 

    for idx in range(image_batches[0].shape): 
    image = image_batches[idx, :, :, :] 
    grayscale = np.zeros((image.shape[0], image.shape[1])) 

    for rownum in range(len(image)): 
     for colnum in range(len(image[rownum])): 
      grayscale[rownum][colnum] = np.average(image[rownum][colnum]) 

    grayscale = np.array(grayscale, dtype="float32") 
    grayscale = grayscale.reshape((grayscale.shape[0], grayscale.shape[1], 1)) 

    grayscale_batch = np.stack(grayscale, grayscale_batch) 

return grayscale_batch 

我想在的结束for循环重建一批做一个np.vstack的,但它看起来凌乱。此外,我不考虑上述两种情况(维度)。

任何想法?

编辑:更新的代码,我期望工作(但仍然没有)。

+0

你确定'范围内的idx(image_batches [0] .shape)'? –

+0

不,它给了我一个错误。 – Qubix

+0

我想你的意思是'image_batches.shape [0]' –

回答

0

你不需要做任何的循环,堆放或什么,只是用numpy.mean()在你的频道轴

# axis=-1 is channels, keepdims is optional 
greyscale_image_batch = numpy.mean(image_batch, axis=-1, keepdims=True) 
image_batch.shape    # [batch_size, height, width, channels] 
greyscale_image_batch.shape # [batch_size, height, width, 1] 

为了使您在正确的形状阵列可以使用transpose()

if image_batch.shape[1] == 3: 
    image_batch = image_batch.transpose([0, 2, 3, 1]) 
+0

不确定我用numpy.mean得到了答案的第一部分。我还将我的功能更新为尽可能完整的功能。 – Qubix

+0

您是否尝试过运行它? –

+0

和,它工作? –