手动将 RGB 转换为灰度

Converting RGB to Grayscale manually tensorflow

我想手动将 RGB 图像转换为灰度图像,而无需在 tensorflow 中使用库。所以我写了以下...

import tensorflow as tf
import matplotlib.image as mpimg
import matplotlib.pyplot as plt

# First, load the image again
filename = "MarshOrchid.jpg"
raw_image_data = mpimg.imread(filename)

image = tf.placeholder("float", [None, None, 3])
slice = tf.slice(image,[0,0,0],[-1,-1,1])

with tf.Session() as session:
    result = session.run(slice, feed_dict={image: raw_image_data})
    plt.imshow(result)
    plt.show()

我提取了图像的第一个通道进行转换。 但这会在使用 imread saying 时产生错误

TypeError: Invalid dimensions for image data

我该怎么办?

来自plt.imshow(X)的doc

X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)

这里有一个形状为 [None, None, 1] 的输入。您只需要像这样删除最后一个维度:

result = np.squeeze(result, 2)