将多个numpy图像转换为灰度图

3

我目前有一个包含2000张照片的numpy数组 'images'。我正在寻找一种改进的方法来将 'images' 中的所有照片转换为灰度。图片的形状为(2000, 100, 100, 3)。以下是我的代码:

# Function takes index value and convert images to gray scale 
def convert_gray(idx):
  gray_img = np.uint8(np.mean(images[idx], axis=-1))
  return gray_img

#create list
g = []
#loop though images 
for i in range(0, 2000):
  #call convert to gray function using index of image
  gray_img = convert_gray(i)
  
  #add grey image to list
  g.append(gray_img)

#transform list of grey images back to array
gray_arr = np.array(g)

我想知道是否有人能够建议一种更有效的方法来完成这个任务?我需要输出以数组格式呈现。


1
这个回答是否解决了你的问题?如何在Python中将RGB图像转换为灰度图像? - scleronomic
1个回答

4

通过对最后一个轴进行平均值计算,您现在所做的是:

Gray = 1/3 * Red + 1/3 * Green + 1/3 * Blue

但实际上,另一个转换公式更为常见(参见此答案):

Gray = 299/1000 * Red + 587/1000 * Green + 114/1000 * Blue

@unutbu提供的代码也适用于图像数组:
import numpy as np

def rgb2gray(rgb):
    return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])

rgb = np.random.random((100, 512, 512, 3))
gray = rgb2gray(rgb)
# shape: (100, 512, 512)

你不需要奇怪的索引。只需要 rgb.dot(weights) 就可以了。原始代码恰好使用了 np.ones(3) / 3,这可能没有被正确归一化。 - Mad Physicist
此外,鉴于您的函数是 https://dev59.com/EWct5IYBdhLWcg3wSbnY#12201744 的逐字复制,我强烈建议您给予适当的归属或投票关闭为重复。 - Mad Physicist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接