[英]Convert numpy array of colour images to a numpy array of gray scale images
How do I convert an array of two colour images to an array of two gray scale images using the to_grayscale
(from this site ) function below. 如何使用下面的to_grayscale
(来自此站点 )函数将两个彩色图像的数组转换为两个灰度图像的数组 。
Important: I don't want image files, I want the array image_g
defined below. 重要说明:我不需要图像文件,我想要下面定义的数组image_g
。
First create the function and sample images: 首先创建函数并采样图像:
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)
Have a look at the first image: 看一下第一张图片:
plt.imshow(images[1])
View as gray scale: 以灰度查看:
plt.imshow(to_grayscale(images[1]))
How do I convert images
to an array of gray scale images image_g
? 如何将images
转换为灰度图像image_g
的数组? I'd like to do something like this: 我想做这样的事情:
image_g = np.somefunction(to_grayscale, images)
images_g.shape
out> (2, 2, 2)
where somefunction
is a placeholder for the answer. 其中somefunction
是答案的占位符。
Use PIL
使用PIL
from PIL import Image
img = Image.open('image.png').convert('LA')
img.save('greyscale.png')
You can also use scikit-image 您也可以使用scikit-image
Example 例
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)
根据此答案 ,我不确定这是否通常是最快或最优雅的方式
images_g = np.array([to_grayscale(images[i]) for i in range(images.shape[0])])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.