Segmenting an image from contours

I’m trying to segment ellipse-like objects from an image using the contours in its mask. however, I couldn’t figure out how to get the segmented image in PNG form (without background).
here is the function I’m using:

def segment(image_filepath,mask_filepath):
    
    mask=cv2.imread(mask_filepath)
    
    mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)


    ret, thresh = cv2.threshold(mask_gray, 0, 255, cv2.THRESH_BINARY)
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,
                                               cv2.CHAIN_APPROX_SIMPLE)
    l= list(contours)
    
  
    image=io.imread(image_filepath)
    
    
    image_name=os.path.basename(image_filepath)
    image_name=image_name.rsplit( ".", 1 )[ 0 ]
    
    os.mkdir(r"D:\unet\segmented_object\{}".format(image_name))
    
    for i in range(len(l)):
        x=[]
        y=[]
        for j in l[i]:
        
            y.append(j[0][1])
            x.append(j[0][0])


        y_max=np.amax(y)
        y_min=np.amin(y)
        x_max=np.amax(x)
        x_min=np.amin(x)

        im_crop = image[y_min:y_max,x_min:x_max]
        
        imageio.imwrite(r"D:\unet\segmented_object\{}\{}.tif".format(image_name,i+1), im_crop)