I have a program that classifies MRIs but the input images are photos taken of the MRIs, so before I use them I need to clean them by cropping them.
The idea is to have an input and output like this: Input photo and output example.
Using the image of the last example, here is the process of my code to determine the outline of the MRI. Where I use the contour to see the maximum values of the top, bottom, right and left to determine the hight and width of the image and crop it.
Now, one problem that I have is that the points not always are in the correct positions, sometimes the script fails to find the MRI when there are similar colors in the background. For example, in this image there is a white background that takes up a big area and the program ends up contouring it instead of the brain lines.
I don't know how to make the program ignore those big yellow areas. I have tried other thresholds and color spaces combinations but the gray color space is the one that works best for most of them. Can anyone suggest me another aproach on how to crop this type of images? or a way to make the program ignore big color areas?
This is my current code:
from keras.applications.inception_resnet_v2 import conv2d_bn
from google.colab.patches import cv2_imshow
img = cv2.imread(mri_photos[7])
og_img = img.copy()
# Gray color space
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
#Smoothing the image
gray = cv2.GaussianBlur(gray, (5, 5), 0)
ret , thresh = cv2.threshold(gray, 170, 255, cv2.THRESH_BINARY)
#Remove noise
thresh = cv2.erode(thresh, None, iterations=1)
thresh = cv2.dilate(thresh, None, iterations=5)
# find contours in thresholded image, then grab the largest one
cnts= cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
c = max(cnts, key=cv2.contourArea)
# find the extreme points
extLeft = tuple(c[c[:, :, 0].argmin()][0])
extRight = tuple(c[c[:, :, 0].argmax()][0])
extTop = tuple(c[c[:, :, 1].argmin()][0])
extBot = tuple(c[c[:, :, 1].argmax()][0])
img_cnt = cv2.drawContours(img, [c], -1, (0, 255, 255), 40)
# add extreme points
img_pnt = cv2.circle(img_cnt.copy(), extLeft, 50, (0, 0, 255), -1)
img_pnt = cv2.circle(img_pnt, extRight, 50, (160, 32, 240), -1)
img_pnt = cv2.circle(img_pnt, extTop, 50, (255, 0, 0), -1)
img_pnt = cv2.circle(img_pnt, extBot, 50, (255, 255, 0), -1)
ADD_PIXELS = 0
new_img = og_img[extTop[1]-ADD_PIXELS:extBot[1]+ADD_PIXELS, extLeft[0]-ADD_PIXELS:extRight[0]+ADD_PIXELS].copy()