Python图像灰度化处理

import imageio
import numpy as np
from PIL import Image #用于基本的图像处理
import matplotlib.pyplot as plt # plt 用于显示图片

#定义一个显示函数showing
def showimg(img, isgray=False):
    plt.axis("off")
    if isgray == True:
        plt.imshow(img, cmap='gray')
    else:
        plt.imshow(img)


lena = imageio.imread("lena.jpg")# 用于读取图片

#彩色图像的灰度转换(只抽取G,绿色面)
gray_lena = lena
gray_lena = np.array(gray_lena, dtype=np.int32)
gray_lena[...,0] = 0
gray_lena[...,2] = 0
gray_lena = np.sum(gray_lena, axis=2)

#灰度变换函数图像
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()

#图像的灰度变换
g1 = 255 - gray_lena

g2 = (100.0/255)*gray_lena +100

#显示效果图
plt.subplot(221)
showimg(lena,True)
#plt.imshow(lena)
plt.title("Source Image")

plt.subplot(222)
showimg(gray_lena,True)
#plt.imshow(gray_lena,cmap='gray')
plt.title("Gray Image")

plt.subplot(223)
showimg(g1,True)
plt.title("g1 Image")

plt.subplot(224)
showimg(g2,True)
plt.title("g2 Image")

plt.show()
#灰度化的一些方法
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np


# 获取图片
def getimg():
    return Image.open("D:\Pycharm\example\lena.jpg")


# 显示图片
def showimg(img, isgray=False):
    plt.axis("off")
    if isgray == True:
        plt.imshow(img, cmap='gray')
    else:
        plt.imshow(img)
    plt.show()

showimg(getimg())   #原图显示

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)

im4 = getimg()
im4 = np.array(im4, dtype=np.int32)
im4[...,1] = 0
im4[...,2] = 0
im4 = np.sum(im4, axis=2)
showimg(Image.fromarray(im4), True)

你可能感兴趣的:(python,pycharm,opencv)