在MatLab中使用我自己构建的直方图很困难

时间:2013-09-11 15:07:04

标签: matlab histogram

我正在尝试实现一个简单的函数,它与MatLab的默认hist()相同。

我们有两个不同亮度的相同图像,我们必须将它们转换为灰度,然后使用MatLab hist()的默认函数来获得直方图(到目前为止一直很好!)。

然后我们必须实现函数hist my_hist(),当我试图计算强度的频率时,结果是不一样的。

似乎它总结了254&的频率。 255到254和255是零!我不知道问题是什么,任何帮助将不胜感激。

这是命令行的代码:

%Read the images and convert them from rgb to grayscale
i=imread('pic1.jpg');
j=rgb2gray(i);
x=imread('pic2.jpg');
y=rgb2gray(x);

%Display the two images
figure
imshow(j)
figure 
imshow(y)

%Display the histogram of the two images
[a,b] = hist(j(:),0:1:255);
figure 
plot(b,a)
[c,d]=hist(y(:),0:1:255);
figure 
plot(d,c)

%Call of the built-in function
my_hist('pic1.jpg','pic2.jpg')

这是自建功能的代码:

function  []= my_hist( x,y)

%Read the images and convert them from rgb to grayscale
pic1=imread(x);
i=rgb2gray(pic1);
pic2=imread(y);
j=rgb2gray(pic2);

%Initialize two vectors to be the axis for histogram
plotx=0:255;
ploty=zeros(1,256);

%Take the dimensions of the first image pic1
[m,n] = size(i);

%With 2 loops we go through the matrix of the image and count how many
%pixels have the same intensity

for k=1:m 
   for l=1:n
num=i(k,l)+1;
      ploty(num)=ploty(num)+1;
   end
 end

%Display the histogram for the first image pic1
figure
plot(plotx,ploty);

%Initialize two vectors to be the axis for histogram
plotx2=0:255;
ploty2=zeros(1,256);

%Take the dimensions of the second image pic2
[m2,n2] = size(j);

%With 2 loops we go through the matrix of the image and count how many
%pixels have the same intensity
for o=1:m2 
 for p=1:n2
num2=j(o,p)+1;
    ploty2(num2)=ploty2(num2)+1;
 end
end

%Display the histogram for the second image pic2
figure
plot(plotx2,ploty2);
end

以下是图片pic1pic2

1 个答案:

答案 0 :(得分:3)

这是一个问题,因为您的图片是整数类型uint8,其范围仅为0-255:

>> a= uint8(255)

a =

  255

>> a=a+1

a =

  255

使用

将数据转换为uint16类型
j = uint16(j);
y = uint16(y);

你的问题应该消失了:

>> a=uint16(a)

a =

    255

>> a=a+1

a =

    256