Converting RGB to Grayscale manually tensorflow

2019-07-17 04:44发布

I wanted to convert an RGB image to grayscale manually without library usage in tensorflow. So I wrote the following...

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()

I extracted the first channel of the image for the conversion. But this generates error while using imread saying

TypeError: Invalid dimensions for image data

What should I do?

1条回答
欢心
2楼-- · 2019-07-17 05:13

From the doc of plt.imshow(X):

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

Here you have an input of shape [None, None, 1]. You just need to remove the last dimension like this:

result = np.squeeze(result, 2)
查看更多
登录 后发表回答