The centers
output of imfindcircles
gives the coordinates of the centers in x/y coordinates and you need to index into your image using row/column coordinates so you need to be sure to reverse the two columns when indexing into the image
centers = imfindcircles(IM);
center1 = IM(centers(1,2), centers(1,1),:);
center2 = IM(centers(2,2), centers(2,1),:);
Presumably you are not doing this because you are instead sampling pixels from the background which obviously result in the same RGB values for the centroids.
Update
It appears that actual issue is that you are casting the location of the centroids to a uint8
to make it an integer value so you can then use it as an index. The maximum integer representable by uint8
is 255
and the number of rows and columns in your image is large than 255
(and so are the centroids) so they will get truncated to 255
resulting in the wrong pixel being sampled.
Rather than using uint8
, just use round
to round the centroids to their nearest integers
cX = round(centers(n_c,1));
cY = round(centers(n_c,2));