WebMonster
WebMonster

Reputation: 3031

MATLAB ind2sub is not the inverse of sub2ind

I implemented an image processing algorithm what needs to sweep the image with a line. I generate the valid points of the line into two vectors: lx_valid, and ly_valid. Then I generate the linear indices with sub2ind, and plot the results. As you can see, my line clearly intersects the object, but locmax == 0 after running the code. The coordinates are all valid (inside the image); but I've got one even stranger result: if I generate the coordinates as ind2sub(size(Im), c) I don't even get back my coordinates. I'm sure it's something small, but I can't get it.

valid = lx >= 1 & size(Im, 2) >= lx & ly >= 1 & size(Im, 1) >= ly;
lx_valid = lx(valid);
ly_valid = ly(valid);
c = sub2ind(size(Im), ly_valid, lx_valid);
locmax = max(Im(c));
imshow(Im);plot(lx_valid,ly_valid,'go');

imshow(Im);plot(lx_valid,ly_valid,'go'); works as expected

Upvotes: 3

Views: 1108

Answers (1)

WebMonster
WebMonster

Reputation: 3031

I solved the problem: the indices that were generated by sub2ind were staturated, and were returned as uint16 silently. If I convert the parameters to double, sub2ind returns a double value which is big enough for the indices.

valid = lx >= 1 & size(Im, 2) >= lx & ly >= 1 & size(Im, 1) >= ly; 
lx_valid = double(lx(valid)); 
ly_valid = double(ly(valid)); 
c = sub2ind(size(Im), ly_valid, lx_valid); 
locmax = max(Im(c)); 
imshow(Im);plot(lx_valid,ly_valid,'go');

Upvotes: 2

Related Questions