简体   繁体   English

将多个 numpy 图像转换为灰度

[英]Converting multiple numpy images to gray scale

I currently have a numpy array 'images' containing 2000 photos.我目前有一个包含 2000 张照片的 numpy 数组“图像”。 I am looking for an improved way of converting all the photos in 'images' to gray scale.我正在寻找一种将“图像”中的所有照片转换为灰度的改进方法。 The shape of the images is (2000, 100, 100, 3).图像的形状是 (2000, 100, 100, 3)。 This is what I have so far:这是我到目前为止:

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

I wondered if anyone could suggest a more efficient way of doing this?我想知道是否有人可以提出一种更有效的方法来做到这一点? I need the output in an array format我需要数组格式的输出

With your mean over the last axis you do right now:用你现在做的最后一个轴的平均值:

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

But actually another conversion formula is more common (See this answer ):但实际上另一个转换公式更常见(请参阅此答案):

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

The code provided by @unutbu also works for arrays of images: @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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM