假定原图像f(x,y)的灰度范围为[a,b],希望变换后图像g(x,y)的灰度范围扩展至[c,d],则灰度线性变换可表示为
g ( x , y ) = d − c b − a [ f ( x , y ) − a + c ] g(x,y)=\frac{d-c}{b-a}[f(x,y)-a+c] g(x,y)=b−ad−c[f(x,y)−a+c]
分别给出将灰度范围(10.100)拉伸到(0,150)和(10,200)、压缩到(50,100)和(10,125)、平移到(110,225)的线性变换。
'''灰度线性变换
g(x,y)=(d-c)/(b-a)(f(x,y)-a)+c
'''
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
#灰度线性变换
def linear_trans(img,x):
a,b,c,d,=x
w,h=img.shape[:2]
new_img=np.zeros((w,h),dtype=np.uint8)
k=(d-c)/(b-a)
for i in range(w):
for j in range(h):
new_img[i,j]=k*(img[i,j]-a)+c
if new_img[i,j]>255:
new_img[i,j]=255
if new_img[i,j]<0:
new_img[i,j]=0
return new_img
if __name__=="__main__":
path="D:\\code\\python\\opencv\\lena.jpg"
img=cv.imread(path,0)
x1=np.array([10,100,0,150])
x2=np.array([10,100,10,200])
x3=np.array([10,100,50,100])
x4=np.array([10,100,110,125])
new_img1=linear_trans(img,x1)
new_img2=linear_trans(img,x2)
new_img3=linear_trans(img,x3)
new_img4=linear_trans(img,x4)
titles=["(10,100)","(0,150)","(10,200)","(50,100)","(110,125)"]
new_img=[img,new_img1,new_img2,new_img3,new_img4]
plt.figure(figsize=(8,6))
for i in range(5):
plt.subplot(2,3,i+1)
plt.rcParams['font.sans-serif']=['SimHei']
plt.imshow(new_img[i],cmap='gray')
plt.title(titles[i])