简体   繁体   中英

Histogram Equalization error in freq(255) freq(256) values

my initial code for histogram equalization computes freq(1) to freq(254) perfectly and computes freq(255) and freq(256) wrongly. Wrongly as in the result at freq(255) is the summation of the actual result at freq(255) and freq(256). And freq(256) always remains 0.

    freq=zeros(256,1);
    probf=zeros(256,1);
    probc=zeros(256,1);
    cum=zeros(256,1);
    output=zeros(256,1);
    numofpixels = 1080*1920;
    value = 500;
    %calculating the frequency
    for i=1:1080
        for j=1:1920
            value=mdata(i,j,1);
            freq(value+1)=freq(value+1)+1;                
            probf(value+1)=freq(value+1)/numofpixels;

        end
    end

So what I modified the initial code to the following code, where I individually check if the value at any pixel is 254 and 255. This works perfectly. What could be the reason behind it?

freq=zeros(256,1);
probf=zeros(256,1);
probc=zeros(256,1);
cum=zeros(256,1);
output=zeros(256,1);
numofpixels = 1080*1920;
maximum254 = 0;
maximum255 = 0;
value = 500;
%calculating the frequency
for i=1:1080
    for j=1:1920
        value=mdata(i,j,1);
        if value < 254
        freq(value+1)=freq(value+1)+1;
        end

        if value==254
        freq(255)=freq(255)+1;
        maximum254 = maximum254 +1;
        end

        if value==255
        freq(256)=freq(256)+1;
        maximum255 = maximum255 +1;
        end

        probf(value+1)=freq(value+1)/numofpixels;

    end
end

The most likely culprit is the fact that your image is uint8 and that the data type is saturating. You noticed that you need to add the intensity by 1 to bin the results because MATLAB starts indexing at index 1. However, when you get to intensity 255, adding 1 should give you 256, but it actually saturates to 255. This is why the bin at 256 is always 0 because you are never generating any values beyond 255.

What's actually happening is that those values that are being binned at 254 are being merged with 255 because uint8(254+1) = uint8(255+1) = 255 . This is why the count at index 254 and 255 are wrong, while bin 256 is 0.

Therefore, to ensure that your data doesn't saturate, you'll need to cast your data to a type that doesn't saturate for 8-bit data. double is a good type to use. As such, simply take your mdata and cast it to double before performing histogram equalization, and so:

mdata = double(mdata);

Once you do this, when you run your code, it should now work and you shouldn't have to check for those values at the higher end of the intensity range manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM