2017-04-21 160 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

和,它工作? –