将RGB图像转为灰度图像,分别用PIL和实现。
gray = r0.299+g0.587+b*0.114
1.PIL实现
import numpy as np
from scipy import misc
from PIL import Image
import os
path = '../../data/Imgnet2015_64/'
output_path = '../../data/Imgnet2015_64_gray/'
if not os.path.exists(output_path):
os.makedirs(output_path)
def changesize(img):
img_name = img
oldimg = Image.open(path+img_name)
new_img = oldimg.resize(oldimg)
new_img.save(output_path+img_name)
def rgb2gray(img):
img_name = img
image = Image.open(path+img_name)
return image.convert('L')
for img in os.listdir(path):
gray = rgb2gray(img)
gray.save(output_path+img)
2.matplotlib实现
import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片
import numpy as np
lena = mpimg.imread('lena.png') # 读取和代码处于同一目录下的 lena.png
# 此时 lena 就已经是一个 np.array 了,可以对它进行任意处理
lena.shape #(512, 512, 3)
plt.imshow(lena) # 显示图片
plt.axis('off') # 不显示坐标轴
plt.show()
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
gray = rgb2gray(lena)
# 也可以用 plt.imshow(gray, cmap = plt.get_cmap('gray'))
# plt.imshow(gray, cmap='Greys_r')
# plt.axis('off')
# plt.show()
# plt.savefig('lena_new_sz.png')
from scipy import misc
misc.imsave('lena_new_sz.png', gray)