数字图像处理入门

[图像增强][灰度变换]2. 分段线性变换

2021-11-07  本文已影响0人  砥砺前行的人

1. 基本原理

分段线性变换,顾名思义,灰度变换在不同的像素值区间有不同的转换关系,实现如下形式:


\begin{equation} f(x)=\left\{ \begin{array}{rcl} \frac{f_3-f_2}{c-b}(x-b) + f_3 & & { b < x \leq c}\\ \frac{f_2-f_1}{b-a}(x-a) + f_2 & & { a < x \leq b}\\ \frac{f_1}{a}x & & {x \leq a}\end{array} \right. \end{equation}

上式为分段函数的表达式,此分段函数的实际作用是增加[a,b]的对比度,削弱 [0, a], [b, c] 对比度。

2. 使用场景

可用于增强图片某一像素值区域内的对比度,突出 ROI。

3. 代码示例

考虑如下灰度图像:


此图我做了特殊处理,将像素通过线性变换,使它的对比度相当的小,现在我们要通过增大对比度使它的图像变得更清晰

代码如下:

import cv2 as cv
import numpy as np
from math import *
import matplotlib.pyplot as plt


# 按灰度读取一张图片
img = cv.imread("cell2.png",cv.IMREAD_GRAYSCALE)
# plt_hist(img)

c = 255
b = 20
a = 10

f3 = 255
f2 = 40
f1 = 10

dst = np.zeros_like(img)

for row in range(len(img)):
    for column in range(len(img[row])):
        if img[row][column] < 10:
            dst[row][column] = f1 * img[row][column] / a
        elif 10 <= img[row][column] < 75:
            dst[row][column] = (f2 - f1) * (img[row][column] - a) / (b-a) + f1
        elif 75 <= img[row][column] < 255:
            dst[row][column] = (f3 - f2) * (img[row][column] - b) / (c-b) + f2         

plt.figure()
plt.subplot(2,2,1)
plt.imshow(img, cmap='gray')
plt.subplot(2,2,2)
plt.imshow(dst, cmap='gray')
plt.subplot(2,2,3)
plt.hist(img.ravel(), 256, [0, 256])
plt.subplot(2,2,4)
plt.hist(dst.ravel(), 256, [0, 256])
plt.show()

输出结果如下:


通过观察直方图我们发现,处理后的图像的像素值分布变宽,对比度变大,[10,20]像素值区域被线性扩展到[10,40],图像变得更加清晰。

上一篇 下一篇

猜你喜欢

热点阅读