所以我有这个形状的ndarray
(39000, 64, 64, 3)
的
dtype=np.uint8
我正在尝试在 while 循环中将所有 39k 图像转换为灰度
while(image_index<num_images):
gray_dataset = np.dot(dataset[image_index,:,:], [0.299, 0.587, 0.114])
image_index +=1
这显然是在产生垃圾。你能指导我正确地做这件事吗?
最佳答案
如果您想将dataset
中的所有图像转换为浮点灰度格式,同时保留三个 channel ,您可以这样做:
# (39000, 64, 64, 1)
gray_dataset_1c = np.sum((dataset / 255.) * [0.299, 0.587, 0.114], axis=-1, keepdims=True)
# (39000, 64, 64, 3)
gray_dataset = np.tile(gray_dataset_1c, (1, 1, 1, 3))
或者使用np.dot
:
# (39000, 64, 64)
gray_dataset_1c = np.dot((dataset / 255.), [0.299, 0.587, 0.114])
# Since Python 3.5 this can be written like this:
gray_dataset_1c = (dataset / 255.) @ [0.299, 0.587, 0.114]
# (39000, 64, 64, 3)
gray_dataset = np.tile(gray_dataset_1c[..., np.newaxis], (1, 1, 1, 3))
经过快速基准测试后,似乎 np.dot
对于此用途实际上要快得多。
关于python - 将 ndarray 转换为灰度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49779430/