How to save a drawn ROI (region of interest) (mask) as a png without a background (python)

47 Views Asked by At

I'm currently drawing ROI's in images for later image processing in Python I have found a way to draw the ROIs and everything works. I then coded a part for saving the roi as aimages. The problem is as follows: I create a roi_region with the same dimensions as the original image, wherein I store the ROI. This worked as a trial, but, I need the ROI itself only: without a background.

I've searched and searched on how this could be done, however I am fairly new to Python and I haven't figured out a way.

if index == 2:
    fig_all_roi, ax_all_roi = plt.subplots()
    ax_all_roi.set_title('Extracted ROIs')

    for i, (verts_list, color) in enumerate(zip(roi_verts_list, roi_colors)):
        for verts in verts_list:
            # Create a Path object from the vertices
            path = Path(verts)
            
            # Create a mask for the region inside the ROI
            x, y = np.meshgrid(np.arange(image.shape[1]), np.arange(image.shape[0]))
            points = np.column_stack((x.flatten(), y.flatten()))
            mask = path.contains_points(points).reshape(image.shape[:2])

            # Extract the region inside the ROI from the original image
            roi_region = np.zeros_like(image, dtype=np.uint8)
            for channel in range(image.shape[2]):
                roi_region[:, :, channel] = (image[:, :, channel] * mask).astype(np.uint8)
            roi_region[:,:, 3] = (mask*255).astype(np.uint8)

            # Save the extracted ROI as an image
            save_roi_image(roi_region, i)

            # Display the extracted region in the new figure
            ax_all_roi.imshow(roi_region, extent=[0, image.shape[1], 0, image.shape[0]])

I have tried adding an alpha channel (i read something about it on stackoverflow), i've tried switching to plt.figsave but that code failed and I ended up in misery.

1

There are 1 best solutions below

0
Tino D On

Search for cv2.imwrite and remember to use a filename with a .png extension. E.g.,

cv2.imwrite("filename.png", ROI)