将像素的强度值转换为整数
Convert the intensity value of a pixel to an integer
我目前正在编写一段代码,它采用中心像素 (x, y) 和半径 r,然后找到该圆形样本中每个像素的平均强度。
到目前为止,这是我的代码:
function [average] = immean(x, y, r, IMAGE)
%Initialise the variables, total and pixelcount, which will be used to
%collect the sum of the pixel intensities and the number of pixels used to
%create this total.
total = 0;
pixelcount = 0;
%Find the maximum width, nx, and maximum height, ny, of the image - so that
%it can be used to end the for-loop at the appropriate positions.
[nx ny] = size(IMAGE);
%Loop through all pixels and check whether each one falls within the range
%of the circle (specified by its x-and-y-coordinates and its radius, r).
%If a pixel does fall within that domain, its intensity is added to the
%total and the pixelcount increments.
for i = 1:nx
for j = 1:ny
if (x-i)^2 + (y-j)^2 <= r^2
total = total + IMAGE(i, j);
pixelcount = pixelcount + 1;
end
end
end
但是,问题是,当我打印出 total
时,我一直得到值 255。我想这是因为 MatLab 知道一个像素的最大强度是 255,所以它阻止了 total
从大于那个。那么我怎样才能将这个像素强度转换为普通整数,这样 MatLab 就不会将 total
限制为 255?
根据 Divakar 的评论,您选择 double
主要是为了提高位精度以及 MATLAB 以这种方式自然地处理数组。此外,当您取事物的平均值时,您还希望具有浮点精度,因为找到事物的平均值将不可避免地给您浮点值。
我有点困惑为什么你不想在平均值之后保留小数点,尤其是在准确性方面。但是,这不是关于意图的问题,而是问题中列出的您想做什么的问题。因此,如果您不需要小数点,只需将您的图像转换为高于 8 位的整数精度以避免裁剪。像 uint32
这样的东西,这样你就可以得到一个 32 位无符号整数,甚至 uint64
可以得到一个 64 位无符号整数。为尽量减少剪裁,转换为 uint64
。因此,只需执行:
IMAGE = uint64(IMAGE);
在任何处理之前在函数的开头执行此操作。
我目前正在编写一段代码,它采用中心像素 (x, y) 和半径 r,然后找到该圆形样本中每个像素的平均强度。
到目前为止,这是我的代码:
function [average] = immean(x, y, r, IMAGE)
%Initialise the variables, total and pixelcount, which will be used to
%collect the sum of the pixel intensities and the number of pixels used to
%create this total.
total = 0;
pixelcount = 0;
%Find the maximum width, nx, and maximum height, ny, of the image - so that
%it can be used to end the for-loop at the appropriate positions.
[nx ny] = size(IMAGE);
%Loop through all pixels and check whether each one falls within the range
%of the circle (specified by its x-and-y-coordinates and its radius, r).
%If a pixel does fall within that domain, its intensity is added to the
%total and the pixelcount increments.
for i = 1:nx
for j = 1:ny
if (x-i)^2 + (y-j)^2 <= r^2
total = total + IMAGE(i, j);
pixelcount = pixelcount + 1;
end
end
end
但是,问题是,当我打印出 total
时,我一直得到值 255。我想这是因为 MatLab 知道一个像素的最大强度是 255,所以它阻止了 total
从大于那个。那么我怎样才能将这个像素强度转换为普通整数,这样 MatLab 就不会将 total
限制为 255?
根据 Divakar 的评论,您选择 double
主要是为了提高位精度以及 MATLAB 以这种方式自然地处理数组。此外,当您取事物的平均值时,您还希望具有浮点精度,因为找到事物的平均值将不可避免地给您浮点值。
我有点困惑为什么你不想在平均值之后保留小数点,尤其是在准确性方面。但是,这不是关于意图的问题,而是问题中列出的您想做什么的问题。因此,如果您不需要小数点,只需将您的图像转换为高于 8 位的整数精度以避免裁剪。像 uint32
这样的东西,这样你就可以得到一个 32 位无符号整数,甚至 uint64
可以得到一个 64 位无符号整数。为尽量减少剪裁,转换为 uint64
。因此,只需执行:
IMAGE = uint64(IMAGE);
在任何处理之前在函数的开头执行此操作。