灰度变换,对数,伽马,反色
根据下列函数图像分析,可以得知各个变换的作用。
对数变换分析:对数变换使得输入的低级别的灰度,输出成了更高级别灰度。比如下图中的对数变换曲线,输入 L/4 时,对应输出就达到 3/4 L,也就是原本1/4亮的亮度变成了3/4亮度,所以图像会变明亮。其他变换可以照此分析。
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import cv2
"""
灰度转为2值图像,公式: 大于阈值置255,小于则置0
"""
def gray2binary(img):
im1 = np.array(img)
im1 = np.where(im1[...] <= 127, 0, 255)
im1 = Image.fromarray(im1)
return im1
"""
灰度反色变换,公式:256 - img
"""
def imageRev(img):
im1 = np.array(img)
im1 = 255 - im1;
im1 = Image.fromarray(im1)
return im1
"""
对数变换,公式:c * ln(1 + img) = [0,256]
"""
def imageLog(c, img):
im1 = np.array(img)
im1 = c * np.log(1 + im1)
im1 = np.uint8(im1)
im1 = Image.fromarray(im1)
return im1
"""
gama变换,又称幂指变换,公式:c * img **v = [0,256]
"""
def imageGama(c,img,v):
im1 = np.array(img)
lut = np.zeros(256, dtype=float)
for i in range(0,256):
lut[i] = c * i ** v
im1 = cv2.LUT(im1, lut)
im1 = np.uint8(im1 +0.5)
im1 = Image.fromarray(im1);
return im1;
"""这里输入图片"""
im = Image.open('bird.bmp')
img = im.convert('L') #转成灰度图
im1 = gray2binary(img);
im2 = imageRev(img);
im3 = imageLog(46, img);
im4 = imageGama(0.004, img, 2);
plt.figure()
plt.suptitle('Multi_Image')
plt.subplot(2,3,1), plt.title('binary')
plt.imshow(im1, cmap='gray'), plt.axis('off')
plt.subplot(2,3,2), plt.title('reverse')
plt.imshow(im2, cmap='gray'), plt.axis('off')
plt.subplot(2,3,3), plt.title('log')
plt.imshow(im3, cmap='gray'), plt.axis('off')
plt.subplot(2,3,4), plt.title('gama')
plt.imshow(im4, cmap='gray'), plt.axis('off')
plt.subplot(2,3,5), plt.title('source')
plt.imshow(im, cmap='gray'), plt.axis('off')
plt.subplot(2,3,6), plt.title('source gray')
plt.imshow(img, cmap='gray'), plt.axis('off')
plt.show()