Grayscale linear transformation of image enhancement (python implementation)


Spatial enhancement refers to the method of directly enhancing pixels in the space composed of pixels, which can be expressed as
g ( x , y ) = T [ f ( x , y ) ] g(x,y)=T[f(x, y)]g(x,y)=T[f(x,y ) ]
where: f(x,y) is the image before enhancement; g(x,y) is the image after enhancement; T is the enhancement operation on f, which can be used as a single A pixel can also be the neighborhood of the pixel, or it can be a set of pixels in a series of images there. Commonly used grayscale transformation methods include grayscale linear transformation, piecewise linear transformation, and nonlinear transformation.

1.1 Gray scale linear transformation

Assuming that the grayscale range of the original image f(x,y) is [a,b], and it is hoped that the grayscale range of the transformed image g(x,y) will be extended to [c,d], then the grayscale linear transformation can be expressed as
g ( x , y ) = d − cb − a [ f ( x , y ) − a + c ] g(x,y)=\frac{dc}{ba}[f(x,y)-a+c ]g(x,y)=badc[f(x,y)a+c]

1.2 Specific implementation

The linear transformations that stretch the grayscale range (10.100) to (0,150) and (10,200), compress to (50,100) and (10,125), and translate to (110,225) are respectively given.

'''灰度线性变换
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])

1.3 Achievement results

Gray scale linear transformation

Guess you like

Origin blog.csdn.net/m0_53192838/article/details/127409172