所以我有一批彩色圖像,我想讓它們變成灰度。唯一的問題是,有時圖像的形狀是[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的,但它看起來凌亂。此外,我不考慮上述兩種情況(維度)。
任何想法?
編輯:更新的代碼,我期望工作(但仍然沒有)。
你確定'範圍內的idx(image_batches [0] .shape)'? –
不,它給了我一個錯誤。 – Qubix
我想你的意思是'image_batches.shape [0]' –