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.
Important: I don't want image files, I want the array image_g
defined below.
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
? 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.
Use PIL
from PIL import Image
img = Image.open('image.png').convert('LA')
img.save('greyscale.png')
You can also use 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])])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.