MATLAB Answers


How to crop specific portion of a grayscale image?

Asked by Warid Islam on 22 Aug 2019
Latest activity Commented on by Walter Roberson
on 23 Aug 2019
I have few OCT images which I want to crop. I have converted those images into grayscale images. Below are the resulting images. The part under the red box(brighter portion of the image) needs to be cropped. I tried using imcrop(). I want to create a GUI where the images could be cropped automatically by pressing a button. Using imcrop() won't allow me to automate the process as then I have to manually crop the images. I tried using the code below:
img = imread('gray4.jpg');
% % get red, green, blue channels
redC = img(:,:,1);
greenC = img(:,:,2);
blueC = img(:,:,3);
% % % mask where red channel is greater than blue channel and green channel greater than blue channel
mask = blueC > 120;
% % overlay mask into original image
finalimg = bsxfun(@times, img, cast(mask,class(img)));
% %plotting
The result is displayed in result.jpg. Please note that result.jpg corresponds to Picture4.jpg. It could be noticed that some information under the red box in Picture4.jpg is lost which is not desirable. I think it is probably related to mask = blueC > 120 in the code above. I was wondering if it is possbile to automate the process so that any image could be cropped as desired everytime a new file is opened. Any suggestions would be appreciated. Thank you.


Show 1 older comment
Hi Walter,
I have tried the code below:
img = imread('gray4.jpg');
a = sum(img,2);
mask = a >= 369310 & a <= 370770;
a(~mask) = 0;
I get the result below:
My low range values is from 193490- 22000 and the next range of values are from 369310-370770. So I put the latter range as high values. But I don't get the desired output.
Please attach grey4 (the ones you attached have the red border that would throw off computation)
Hi Walter,
Please find the gray4.jpg file in the above attachment. Thank you.

Sign in to comment.




1 Answer

Answer by Walter Roberson
on 22 Aug 2019
 Accepted Answer

img = imread('gray4.jpg');
im = imclearborder(255-imclearborder(255-rgb2gray(img)));imshow(im);
hc = sum(im,2);
mask = hc >= 10000;
fr = find(mask, 1, 'first');
lr = find(mask, 1, 'last');
cr = im(fr:lr, :);


Hi Walter,
This works perfectly for me. Thank you.
Note: the image is actually RGB in the file, but only contains gray images. It has a white border around a black border around the useful data. That two imclearborder() and the two "255-" there have to do with removing the white border and then the black border.

Sign in to comment.