Skip to main content
 首页 » 编程设计

python之手动将 RGB 转换为灰度

2024年10月17日7mq0036

我想在不使用 tensorflow 库的情况下手动将 RGB 图像转换为灰度图像。所以我写了以下...

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

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

TypeError: Invalid dimensions for image data 

我该怎么办?

请您参考如下方法:

来自doc plt.imshow(X) 的:

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

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

result = np.squeeze(result, 2)