Reputation: 567
I'm currently working on a piece of code which takes a central pixel (x, y) and a radius, r, and then finds the average intensity of each pixel within that circular sample.
This is my code so far:
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
However, the problem is, when I print out total
, I keep getting the value 255. I figure this is because MatLab knows that the maximum intensity of a pixel is 255, so it prevents the total
from being greater than that. So how can I convert this pixel intensity to an ordinary integer, so that MatLab doesn't restrict the total
to 255?
Upvotes: 0
Views: 1367
Reputation: 104484
Going with Divakar's comment, you choose double
mainly for the increased bit precision as well as MATLAB naturally processing arrays this way. Also, when you take the average value of things, you also want to have floating point precision because finding the average of something will inevitably give you floating point values.
I am a bit confused as to why you don't want to maintain the decimal points after the average, especially when it comes to accuracy. However, this isn't a question about intention, but it is a question of what you want to do that is laid out in your question. As such, if you don't want the decimal points, simply cast your image to an integer precision higher than 8-bit in order to avoid clipping. Something like uint32
so that you get a 32-bit unsigned integer or even uint64
for a 64-bit unsigned integer. To minimize clipping, cast to uint64
. As such, simply do:
IMAGE = uint64(IMAGE);
Do this at the beginning of your function before any processing.
Upvotes: 3