python - 将 ndarray 转换为灰度

标签 python image machine-learning

所以我有这个形状的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/

相关文章:

python - 如何将元组传递给 python 函数

python - Django 在 vi​​rtualenv 下加载 RPy2 时找不到 R

image - 将纹理文件包含到 collada 文件中

java - 使用 Java 裁剪/修剪带有空白空间的 JPG 文件

machine-learning - SKlearn 中嵌套交叉验证的分类报告(平均值/个体值)

python - 我们如何使Python脚本在系统启动时(最好是linux)在安装它的每个系统上自动执行?

java - 实现拖放到图像查看器中

matlab - 如何将 tsne() 应用于 MATLAB 表格数据?

machine-learning - Octave 中 fminunc 的输出函数

python - 如何在类属性定义中使用类方法