MATLAB--拉伸直方图算法

问题描述 投票:0回答:1

我需要拉伸两张图片的直方图,但要使用我自己的算法。这是我目前的代码。

img_gray = imread('hist_gray.jpg');
img_couple = imread('hist_couple.bmp');

img_gray_mod = rozciaganie(img_gray);
img_couple_mod = rozciaganie(img_couple);

subplot(4,2,1);
imshow(img_gray);
title("Obraz oryginalny");

subplot(4,2,2);
imhist(img_gray);
title("Histogram");

subplot(4,2,3);
imshow(img_gray_mod);
title("Obraz po modyfikacji");

subplot(4,2,4);
imhist(img_gray_mod);
title("Histogram");

subplot(4,2,5);
imshow(img_couple);
title("Obraz oryginalny");

subplot(4,2,6);
imhist(img_couple);
title("Histogram");

subplot(4,2,7);
imshow(img_couple_mod);
title("Obraz po modyfikacji");

subplot(4,2,8);
imhist(img_couple_mod);
title("Histogram");

function r = rozciaganie(img);
mn = min(min(img));
mx = max(max(img));
r = 255*((img-mn)/(mx-mn));
end

这就是我得到的输出图像和它们的直方图. 有人能帮我解决这个问题吗?

result

matlab
1个回答
0
投票

你的问题是,你的图像类型为 uint8. 下面一行。

r = 255*((img-mn)/(mx-mn));

使用8位整数进行计算。img-mn 应该没问题,但你除以 mx-mn导致所有的像素都是0或1(任何非整数值都会向下舍入)。最后,乘以255,所有像素的值都是0或255。

最简单的解决方案是使用浮点运算来执行这些操作。

function r = rozciaganie(img);
img = double(img); % convert to double so all arithmetic is floating-point arithmetic
mn = min(img(:));  % better than min(min(img))
mx = max(img(:));
r = 255*((img-mn)/(mx-mn));
r = uint8(r); % convert back to uint8 so the display works as expected
end

简单地重新排列整数运算的顺序也不能达到预期的效果,比如说: (255*(img-mn))/(mx-mn) 在乘法中溢出值,大于255的结果全部变成255。之后的除法将不会恢复这些值。(img-mn)*(255/double(mx-mn)) 是最好的近似值,但可能会导致一些四舍五入的伪影。不过你可以试试,看看结果是否足够好。

© www.soinside.com 2019 - 2024. All rights reserved.