Image piecewise linear transformation

  Image piecewise linear transformation (Piecewise Linear Transformation) is an image processing technology that adjusts the contrast and brightness of the image by applying different linear transformations to pixel values ​​in different areas. This is often used to enhance detail in specific areas of an image or to adjust the overall appearance of the image. Mathematically, the piecewise linear transformation can be expressed in the following form: for each pixel point (x, y) (x, y)
  in the input image(x,y ) , its output valuef ′ ( x , y ) f'(x, y)f(x,y) 可以通过以下分段线性函数来计算:
f ′ ( x , y ) = { a 1 ⋅ f ( x , y ) + b 1 , if  f ( x , y ) < x 1 a 2 ⋅ f ( x , y ) + b 2 , if  x 1 ≤ f ( x , y ) < x 2 ⋮ a n ⋅ f ( x , y ) + b n , if  x n − 1 ≤ f ( x , y ) < x n f'(x, y) = \begin{cases} a_1 \cdot f(x, y) + b_1, & \text{if } f(x, y) < x_1 \\ a_2 \cdot f(x, y) + b_2, & \text{if } x_1 \leq f(x, y) < x_2 \\ \vdots \\ a_n \cdot f(x, y) + b_n, & \text{if } x_{n-1} \leq f(x, y) < x_n \\ \end{cases} f(x,y)= a1f(x,y)+b1,a2f(x,y)+b2,anf(x,y)+bn,if f(x,y)<x1if x1f(x,y)<x2if xn1f(x,y)<xn
  Among them, f ( x , y ) f(x, y)f(x,y ) is the pixel point(x, y) (x, y)(x,y ) gray value,( x 1 , x 2 , … , xn ) (x_1, x_2, \ldots, x_n)(x1,x2,,xn) is the segmentation point,( a 1 , a 2 , … , an ) (a_1, a_2, \ldots, a_n)(a1,a2,,an) is the slope,( b 1 , b 2 , … , bn ) (b_1, b_2, \ldots, b_n)(b1,b2,,bn) is the intercept.
  Here is an example of Python code using the OpenCV library for piecewise linear transformation of an image:

import cv2
import numpy as np

def piecewise_linear_transform(image, breakpoints, slopes, intercepts):
    # 创建一个空白图像,用于存储变换后的结果
    transformed_image = np.zeros_like(image)

    for i in range(len(breakpoints) + 1):
        lower_bound = breakpoints[i - 1] if i > 0 else 0
        upper_bound = breakpoints[i] if i < len(breakpoints) else 255

        # 对当前分段内的像素应用线性变换
        mask = (image >= lower_bound) & (image < upper_bound)
        transformed_image[mask] = slopes[i] * image[mask] + intercepts[i]

    return transformed_image

# 读取图像
input_image = cv2.imread('input.jpg', cv2.IMREAD_GRAYSCALE)

# 定义分段点、斜率和截距
breakpoints = [100, 150]
slopes = [1.5, 0.7, 1.2]
intercepts = [-100, 50, 0]

# 应用分段线性变换
output_image = piecewise_linear_transform(input_image, breakpoints, slopes, intercepts)

# 显示原始图像和变换后的图像
cv2.imshow('Original Image', input_image)
cv2.imshow('Transformed Image', output_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Guess you like

Origin blog.csdn.net/qq_50993557/article/details/132153227