将彩色图像的numpy数组转换为灰度图像的numpy数组

时间:2018-10-13 04:50:45

标签: python numpy

如何使用下面的to_grayscale(来自此site)函数将两个彩色图像的阵列转换为两个灰度图像的阵列

重要:我不需要图像文件,但需要下面定义的数组image_g

首先创建函数并对图像进行采样:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['image.cmap'] = 'gray'
np.random.seed(0)

def to_grayscale(im):
    tile = np.tile(np.c_[0.333, 0.333, 0.333], reps=(im.shape[0],im.shape[1],1))
    return np.sum(tile * im, axis=2)

images = np.random.randint(0, 255, 24).reshape(2, 2, 2, 3)
images.shape

out> (2, 2, 2, 3)

看看第一张图片:

plt.imshow(images[1])

enter image description here

以灰度查看:

plt.imshow(to_grayscale(images[1]))

enter image description here

如何将images转换为灰度图像image_g的阵列?我想做这样的事情:

image_g = np.somefunction(to_grayscale, images)
images_g.shape

out> (2, 2, 2)

其中somefunction是答案的占位符。

3 个答案:

答案 0 :(得分:0)

使用PIL

from PIL import Image
img = Image.open('image.png').convert('LA')
img.save('greyscale.png')

答案 1 :(得分:0)

您也可以使用scikit-image

示例

from scipy import misc
import matplotlib.image as mpimg
from skimage import data
photo_data = misc.imread("./image.jpg")
x,y,z=photo_data.shape ## where z is the RGB dimension
photo_data[:] = photo_data.mean(axis=-1,keepdims=1) 
mpimg.imsave("greyscale.png", photo_data)

答案 2 :(得分:0)

基于此answer

,我不确定这是否通常是最快或最优雅的方法
images_g = np.array([to_grayscale(images[i]) for i in range(images.shape[0])])