How to cut specific part of image following reference mask in python?

Viewed 416

I want to cut the MRI by using the respective reference mask. I applied contour operation to crop the mask into 100*100. After that, I am trying to cut the MRI using the cropped mask in the same orientation and extract the mask location in the MRI. But it can't crop the same place as the MRI. Anyone can help, please. Thanks in advance. Here I attach the expected output. crop procedure output output mri and mask place

    ```
    #crop the mask into 100*100

    def crop_brain_contour(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # grayscale
    cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL,   cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]

    for c in cnts:
       x,y,w,h = cv2.boundingRect(c)
       ROI = image[y:y+h, x:x+w]
       return ROI
 
    cv_mask = cv2.imread('./input data/442_mask.bmp')
    desired_width, desired_height = (100, 100)
    final_crop_mask = np.zeros((desired_height, desired_width, 3), dtype="uint8")
    mask_crop = crop_brain_contour(cv_mask)
    h,w = mask_crop.shape[:2]
    x1 = int(desired_width/2 - w/2)
    y1 = int(desired_height/2 - h/2)
    x2 = x1 + w
    y2 = y1 + h
    final_crop_mask[y1:y2, x1:x2, :] = mask_crop
    cv2.imwrite("crop_mask.bmp",final_crop_mask)
    
    # crop the MRI using reference crop mask in the same orientation
    # read image
    img = cv2.imread('input_1.bmp')
    ht, wd, cc = img.shape
    # read mask as grayscale
    mask = cv2.imread('crop_mask.bmp', cv2.IMREAD_GRAYSCALE)
    # threshold mask and invert
    mask = cv2.threshold(mask,0,255,cv2.THRESH_BINARY)[1]
    mask = 255 - mask
    hh, ww = mask.shape

    # make mask 3 channel
    mask = cv2.merge([mask,mask,mask])
    x1 = int(512 / 2 - ww / 2)
    y1 = int(512 / 2 - hh / 2)
    x2 = x1 + ww
    y2 = y1 + hh

    # put mask into black background image
    mask2 = np.zeros_like(img)
    mask2[y1:y2, x1:x2] = mask
    # apply mask to image
    img_masked = cv2.bitwise_and(img, mask2)
    # crop region
    img_masked_cropped = img_masked[y1:y2, x1:x2]
    # ALTERNATE just crop input
    img_cropped = img[y1:y2, x1:x2]

    # save results
    cv2.imwrite('./output/mask_inserted.bmp', mask2)
    cv2.imwrite('./output/masked_image.bmp', img_masked)
    cv2.imwrite('./output/masked_cropped.bmp', img_masked_cropped)
    cv2.imwrite('./output/img_cropped.bmp', img_cropped)
    ```
    
0 Answers
Related