rotate and crop image but get error (Subscript indices must either be real positive integers or logicals)

1 view (last 30 days)
I'm crop the picture using this code
v=~im2bw(img,0.7);
[rows, columns] = find(v);
row1 = min(rows);
row2 = max(rows);
col1 = min(columns);
col2 = max(columns);
cropped = img(row1:row2, col1:col2);
figure, imshow(cropped);title('crop Image');
[p3, p4] = size(cropped);
pp=p4/4; % finde quarter of image width
q1 = p4-pp; % size of the crop box
i3_start = floor((p3-q1)/2); % or round instead of floor; using neither gives warning
i3_stop = i3_start + q1;
i4_start = floor((p4-q1)/2);
i4_stop = i4_start + q1;
I1 = cropped(i3_start:i3_stop, i4_start:i4_stop, :);
figure ,imshow(I1);
and then I rotated the image and tried to crop it with the same code but I got this error
Subscript indices must either be real positive integers or logicals.
Error in Try (line 47)
I1 = croppedImage(i3_start:i3_stop, i4_start:i4_stop, :);

Accepted Answer

Geoff Hayes
Geoff Hayes on 17 Jul 2018
wisam - it could be that because you are using floor, then one of i3_start or i4_start are zero, since floor rounds toward negative infinity. As zero is not a positive integer, then the above error message makes sense. You may want to add a check to ensure that all four of your indices satisfy the real positive integers or logicals requirement before trying to use them.
  1 Comment
wisam kh
wisam kh on 17 Jul 2018
Edited: wisam kh on 17 Jul 2018
Thank you, the problem was solved by a small change in the code.
[p3, p4] = size(croppedImage);
pp=p3/4; % finde quarter of image width
q1 = p3-pp; % size of the crop box
i3_start = floor((p3-q1)/2); % or round instead of floor; using neither gives warning
i3_stop = i3_start + q1;
i4_start = floor((p3-q1)/2);
i4_stop = i4_start + q1;
I1 = croppedImage(i3_start:i3_stop, i4_start:i4_stop, :);
figure ,imshow(I1);

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!