参考《Python图像灰度变换及图像数组操作》实现以下几种灰度化
获取图片及显示图片的通用方法如下:
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
#获取图片
def getimg():
return Image.open("f:/pic/timg.jpg")
#显示图片
def showimg(img, isgray=False):
plt.axis("off")
if isgray == True:
plt.imshow(img, cmap='gray')
else:
plt.imshow(img)
plt.show()
PIL库自带方法实现灰度化
im = getimg()
im_gray = im.convert('L')
showimg(im_gray, True)
im = getimg()
im = np.array(im)
im[:,:,0] = im[:,:,0]*0.3
im[:,:,1] = im[:,:,1]*0.59
im[:,:,2] = im[:,:,2]*0.11
im = np.sum(im, axis=2)
showimg(Image.fromarray(im), True)
im1 = getimg()
#创建数组时指定数据类型,否则默认uint8乘法运算会溢出
im1 = np.array(im1, dtype=np.float32)
im1[...,0] = im1[...,0]*30.0
im1[...,1] = im1[...,1]*59.0
im1[...,2] = im1[...,2]*11.0
im1 = np.sum(im1, axis=2)
im1[...,:] = im1[...,:]/100.0
showimg(Image.fromarray(im1), True)
im2 = getimg()
im2 = np.array(im2, dtype=np.float32)
im2 = np.sum(im2, axis=2)
im2[...,:] = im2[...,:]/3.0
showimg(Image.fromarray(im2), True)
im3 = getimg()
im3 = np.array(im3, dtype=np.int32)
im3[...,0] = im3[...,0]*28.0
im3[...,1] = im3[...,1]*151.0
im3[...,2] = im3[...,2]*77.0
im3 = np.sum(im3, axis=2)
arr = [np.right_shift(y.item(), 8) for x in im3 for y in x]
arr = np.array(arr)
arr.resize(im3.shape)
showimg(Image.fromarray(arr), True)
im4 = getimg()
im4 = np.array(im4, dtype=np.int32)
im4[...,0] = 0
im4[...,2] = 0
im4 = np.sum(im4, axis=2)
showimg(Image.fromarray(im4), True)
im5 = getimg()
im5 = np.array(im5.convert('L'))
im5 = np.where(im5[...,:] < 127, 0, 255)
showimg(Image.fromarray(im5), True)
im = getimg()
im_gray1 = im.convert('L')
im_gray1 = np.array(im_gray1)
avg_gray = np.average(im_gray1)
im_gray1 = np.where(im_gray1[...,:] < avg_gray, 0, 255)
showimg(Image.fromarray(im_gray1), True)
im = getimg()
im_gray = im.convert('L')
im_arr = np.array(im_gray)
im1 = 255 - im_arr
showimg(Image.fromarray(im1))
im = getimg()
im_gray = im.convert('L')
im2 = (100.0/255)*im_gray +100
showimg(Image.fromarray(im2))
im = getimg()
im_gray = im.convert('L')
im3 = 255.0*(im_gray /255.0)**2
showimg(Image.fromarray(im3))
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.title('灰度变换函数图像')
plt.xlabel('像素值')
plt.ylabel('变换后像素值')
x1 = np.arange(0, 256)
y1 = np.arange(0, 256)
f1, = plt.plot(x1, y1, '--')
y2 = 255 - x1
f2, = plt.plot(x1, y2, 'y')
y3 = (100.0/255)*x1 + 100
f3, = plt.plot(x1, y3, 'r:')
y4 = 255.0*(x1/255.0)**2
f4, = plt.plot(x1, y4, 'm--')
plt.legend((f1, f2, f3, f4), ('y=x','y=255-x','y=(100.0/255)*x+100','y=255.0*(x/255.0)**2'),loc='upper center')
plt.show()