Reputation:
I would like to get the pixel values of the region marked as red rectangle.I want to crop the image after that
Upvotes: 0
Views: 180
Reputation: 1270
The following code will solve your problem. But there can be several better solutions. Next time please don't just ask the question, instead show what you've tried.
% 20151116
% crop image by area
clc; clear all;
img = imread('xgOFu.png');
subplot(1,5,1);
imshow(img);
xl1 = xlim;
title('Original');
imgr = img(:,:,1);
subplot(1,5,2);
imshow(imgr);
xlim(xl1);
title('Red channel');
imgb = im2bw(imgr,.9);
subplot(1,5,3);
imshow(imgb);
xlim(xl1);
title('Binary');
s = regionprops(imgb);
c1 = s.BoundingBox(1);
c2 = s.BoundingBox(1)+s.BoundingBox(3)-1;
r1 = s.BoundingBox(2);
r2 = s.BoundingBox(2)+s.BoundingBox(4)-1;
subplot(1,5,4);
imgc = imgb(r1:r2,c1:c2,:);
imshow(imgc);
xlim(xl1);
title('Crop with border');
s2 = regionprops(imcomplement(imgc));
c3 = s2.BoundingBox(1)+c1;
c4 = s2.BoundingBox(1)+s2.BoundingBox(3)-1+c1;
r3 = s2.BoundingBox(2)+r1;
r4 = s2.BoundingBox(2)+s2.BoundingBox(4)-1+r1;
imgc2 = img(r3:r4,c3:c4,:);
subplot(1,5,5);
imshow(imgc2);
xlim(xl1);
title('Crop without border');
Output:
Updated answer for older version without regionprops
.
% 20151116
% filter image by area 2
clc; clear all;
img = imread('xgOFu.png');
imgr = img(:,:,1);
imgb = im2bw(imgr,.9);
[r, c] = find(imgb(:,:,1)==1);
r1 = min(r);
r2 = max(r);
c1 = min(c);
c2 = max(c);
img2 = img(r1:r2,c1:c2,:);
img2r = img2(:,:,1);
img2b = im2bw(img2r,.9);
[r, c] = find(img2b(:,:)==0);
r1 = min(r);
r2 = max(r);
c1 = min(c);
c2 = max(c);
img3 = img2(r1:r2,c1:c2,:);
imshow(img3);
Upvotes: 2