利用python将RGB图像转化为灰度图像

利用python将RGB图像转化为灰度图像

  • 灰度化公式:
    • 使用matplotlib

使用了mxnet来读取图片,也可以用其它的方式读取图片

灰度化公式:

gray = R * 0.299 + G * 0.587 + B * 0.114

from mxnet import image
import numpy as np
import matplotlib.pyplot as plt
from mxnet import nd

img = image.imread('autumn_oak.jpg')
R = img[:, :, 0].astype('float32')
G = img[:, :, 1].astype('float32')
B = img[:, :, 2].astype('float32')
Y = R * 0.299 + G * 0.587 + B * 0.114  #灰度化公式
gray = nd.zeros((Y.shape[0], Y.shape[1], 3)) #gray矩阵是三通道的(gray,gray,gray)
gray[:, :, 0] = Y
gray[:, :, 1] = Y
gray[:, :, 2] = Y
gray = gray.astype('int').asnumpy()  #变成int,使得图像能显示,支持[0,255]的int 和 [0,1]的float
plt.imshow(gray)
plt.imsave('2.png', gray)
plt.show()

使用matplotlib

from matplotlib import pyplot as plt
import numpy as np
path = 'autumn_oak.jpg'
x = plt.imread(path).astype('float32')
plt.imshow(x.astype('int'))
plt.show()
Y = x[:,:,0] * 0.299 + x[:,:,1] * 0.587 + x[:,:,2] * 0.114
gray = np.zeros((Y.shape[0],Y.shape[1],3))
gray[:,:,0] = gray[:,:,1] = gray[:,:,2] = Y
plt.imshow(gray.astype('int'))
plt.savefig('1.jpg', dpi = 300)
plt.show()

你可能感兴趣的:(图像处理,python,深度学习)