python实现灰度图像拉伸

2025-10-20 20:40:24

1、灰度拉伸是一种简单的线性运算。经过变换后使得灰度布满整个灰度等级范围。

为了把不同图像的灰度值映射到0-255范围内,常见的方法有:

python实现灰度图像拉伸

python实现灰度图像拉伸

2、处理过程如下:

import cv2 as cv

import numpy as np

from matplotlib import pyplot as plt

image = cv.imread('c:\\meiping1.png')

imgGray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)

cv.imshow('imgGray', imgGray)

python实现灰度图像拉伸

python实现灰度图像拉伸

3、rows, cols = imgGray.shape

reshapeGray = imgGray.reshape(rows * cols)

print(reshapeGray)

reshapeGrayList = reshapeGray.tolist()

通过.tolist() 转换成列表 方便后面求最大灰度 和最小灰度

python实现灰度图像拉伸

4、A = min(reshapeGrayList)

B = max(reshapeGrayList)

1)方法一

Gxy = (255 / (B - A)) * abs(imgGray - A)

print('A = %d,B = %d' % (A, B))

python实现灰度图像拉伸

5、2)另一种方法 

MAX = 255

MIN = 0

Gxy = (imgGray - A) / (B - A) * (MAX - MIN) + MIN

区别在gxy 其他不变!

python实现灰度图像拉伸

6、result = np.uint8(Gxy )

cv.imshow('imgGray', imgGray)

print(imgGray)

cv.imshow('result', result)

hist = cv.calcHist([imgGray],

    [0],    None,     [256],     [0.0,255.0]) 

hist1 = cv.calcHist([result],

    [0],     None,     [256],     [0.0,255.0]) 

plt.plot(hist)

plt.show()

plt.plot(hist1)

plt.show()

cv.waitKey()

cv.destroyAllWindows()

python实现灰度图像拉伸

python实现灰度图像拉伸

7、小结:

1)2种方法原始图和结果图对比基本亮度或者对比度提高了。图片更便于辨识度提高。

2)直方图也类似的。

3)灰度转一维列表 tolist()

python实现灰度图像拉伸

python实现灰度图像拉伸

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢