我编写了有色图像直方图均衡的代码。该代码适用于灰度图像,但它会导致彩色图像出错。我正在将rgb图像转换为hsv然后执行直方图均衡。有什么想法吗?
代码:
% GIm=imread('tire.tif'); this is grayscale image, which works fine
I=imread('D:\came.jpg');
GIm=rgb2hsv(I);% converting color image to hsv
numofpixels=size(GIm,1)*size(GIm,2);
figure,imshow(GIm);
title('Original Image');
HIm=uint8(zeros(size(GIm,1),size(GIm,2)));
freq=zeros(256,1);
probf=zeros(256,1);
probc=zeros(256,1);
cum=zeros(256,1);
output=zeros(256,1);
%freq counts the occurrence of each pixel value.
%The probability of each occurrence is calculated by probf.
for i=1:size(GIm,1)
for j=1:size(GIm,2)
value=GIm(i,j);
freq(value+1)=freq(value+1)+1; % giving error here
probf(value+1)=freq(value+1)/numofpixels;
end
end
sum=0;
no_bins=255;
%The cumulative distribution probability is calculated.
for i=1:size(probf)
sum=sum+freq(i);
cum(i)=sum;
probc(i)=cum(i)/numofpixels;
output(i)=round(probc(i)*no_bins);
end
for i=1:size(GIm,1)
for j=1:size(GIm,2)
HIm(i,j)=output(GIm(i,j)+1);
end
end
figure,imshow(HIm);
title('Histogram equalization');
subplot(2,2,2);
plot(GIm);
%bar(GIm);
title('Before Histogram equalization');
subplot(2,2,4);
plot(HIm)
%bar(HIm);
title('After Histogram equalization');
错误:
Attempted to access freq(1.61378); index must be a positive integer or logical.
Error in histogramequ (line 18)
freq(value+1)=freq(value+1)+1;
答案 0 :(得分:1)
你的代码的主要问题是在rgb2hsv()之后,每个像素的格式在[0,1]中是双倍的,而不是uint8。所以你需要转换回[0,255]所以它可以用作下标。
以下代码可以正常使用。
for i=1:size(GIm,1)
for j=1:size(GIm,2)
value=floor(GIm(i,j) * 255); % now value is in [0,255]
freq(value+1)=freq(value+1)+1;
probf(value+1)=freq(value+1)/numofpixels;
end
end