灰度变换函数 s = T(r) 其中 r 为输入图像在 (x, y) 点处的灰度值, s 为输出图像在 (x, y) 点处的灰度值
灰度变换的作用
上图所示的两幅 T(s)函数的图像曲线, 第一幅图可以增强图像对比度, 第二幅图可以对图像进行二值化处理
灰度变换函数
反转函数
- void reverse(short** in_array, short** out_array, long height, long width)
- {
- for (int i = 0; i <height; i++){
- for (int j = 0; j <width; j++)
- out_array[i][j] = GRAY_LEVELS - in_array[i][j];
- }
- }
最简单的灰度变换函数, 将图像中的每个像素点处的颜色值反转, 对于 8 位灰度图片, 用 255 减去原灰度值
原图
反转图
对数变换
s = clog(1 + r) c 为常数, 本次测试中 c 取 10
- void logarithm(short** in_array, short** out_array, long height, long width)
- {
- for (int i = 0; i < height; i++){
- for (int j = 0; j <width; j++)
- out_array[i][j] = (short)(10 * log((1 + in_array[i][j])));
- }
- }
可以看出, 对数变换降低了图像的对比度
幂律 (伽马) 变换
s = crγ 其中 c 和 γ 为正常数
其中γ<1 时, 降低对比度,γ>1 时, 提高对比度
γ = 1.2
- void gamma(short** in_array, short** out_array, long height, long width)
- {
- for (int i = 0; i < height; i++){
- for (int j = 0; j <width; j++)
- out_array[i][j] = (short)pow(in_array[i][j], 1.2);
- }
- }
直方图均衡化
直方图为离散函数 h(rk) = nk, 其中 rk 是第 k 级灰度值, nk 是图像中 h 灰度为 rk 的像素个数
现在给出上面几幅图像的直方图
可以明显看出, 对比度越高的图像, 直方图的分布越均衡, 因此直方图均衡化算法可以显著提高图像对比度
直方图均衡化算法推导(需一定高等数学及概率论知识)
算法实现
- void calculate_histogram(long height, long width, short **image, unsigned long histogram[])
- {
- short k;
- for(int i=0; i < height; i++){
- for(int j=0; j < width; j++){
- k = image[i][j];
- histogram[k] = histogram[k] + 1;
- }
- }
- }
- void histogram_equalization(short** in_array, short** out_array, long height, long width)
- {
- unsigned long sum, sum_of_h[GRAY_LEVELS];
- double constant;
- unsigned long histogram[GRAY_LEVELS] = {};
- calculate_histogram(height, width, in_array, histogram);
- sum = 0;
- for(int i=0; i < GRAY_LEVELS; i++){
- sum = sum + histogram[i];
- sum_of_h[i] = sum;
- }
- constant = (double)(GRAY_LEVELS)/(double)(height*width);
- for(int i = 0, k = 0; i < height; i++){
- for(int j = 0; j < width; j++){
- k = in_array[i][j];
- out_array[i][j] = sum_of_h[k] * constant;
- }
- }
- }
来源: https://www.cnblogs.com/GoldBeetle/p/9733220.html