所以我有一批彩色图像,我想让它们变成灰度。唯一的问题是,有时图像的形状是[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]' –