简体   繁体   English

在matlab中不使用for循环计算矩阵的直方图

[英]Calculating the histogram of a matrix without using a for loop in matlab

i have an image which i have read in and its pixel values are stored in a matrix. 我有一个我已读入的图像,其像素值存储在矩阵中。 I am trying to get a frequency table for the matrix of which i intend to plot a histogram. 我试图获得矩阵的频率表,我打算绘制直方图。 I am trying to do this using only matrix expressions(ie no for loops/ imhist function). 我试图只使用矩阵表达式(即没有for循环/ imhist函数)。 I looked at a function called histc() that can count the values in a matrix, but i don't know how to use it. 我查看了一个名为histc()的函数,它可以计算矩阵中的值,但我不知道如何使用它。 I would really appreciate it if someone could point me in the right direction. 如果有人能指出我正确的方向,我真的很感激。 Thanks 谢谢

try: 尝试:

hist(image(:),min(image(:)):max(image(:)));

this will plot a histogram of the pixel values including the entire range of values that the image has. 这将绘制像素值的直方图,包括图像具有的整个值范围。

Though this is an old post, we can also use accumarray : 虽然这是一个老帖子,但我们也可以使用accumarray

h = accumarray(double(im(:))+1, 1, [double(intmax(class(im)))+1 1]);

h will contain a histogram / frequency count of how many pixels are encountered per intensity level. h将包含每个强度级别遇到的像素数的直方图/频率计数。 We take all of the values in im and offset by 1 as MATLAB indexes arrays starting from 1 instead of 0 . 我们将im所有值和偏移量取1因为MATLAB索引数组从1开始而不是0 The intensities for an image will start at 0 . 图像的强度将从0开始。 We also want to specify the size of the histogram to go from 0 to as many intensities that we have that is supported by this class. 我们还想指定直方图的大小,从0到我们拥有的这个类所支持的强度。 We can figure out what the greatest intensity that is supported for an image by doing intmax(class(im)) . 我们可以通过intmax(class(im))图像支持的最大强度。 As such, the total number of possible intensities that we can support is intmax(class(im)) + 1 . 因此,我们可以支持的可能强度的总数是intmax(class(im)) + 1 The third parameter of accumarray specifies the output size of our histogram. accumarray的第三个参数指定了直方图的输出大小。

Take note that you need to cast the intmax call as well as the image im with double because what is returned is the maximum integer of that type and it is of that type . 请注意,您需要使用double intmax调用以及图像im ,因为返回的是该类型的最大整数, 并且它属于该类型 Therefore, adding 1 will simply saturate the value and not register. 因此,添加1将简单地使值饱和而不进行注册。 Therefore, you need to cast as double so that the addition can properly register. 因此,您需要转换为double以便添加可以正确注册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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