Click here to Skip to main content
15,917,618 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to extract 3 random areas from the image (lungs image) these areas are indicated in the soft tissues, each area will be a square of specific height and width e.g. 10mm for width and height, as shown in the image in the link.[^][^]

in the link below for more clarification I selected where the soft tissues located, they are the Homogeneous color[^]

as seen in the image also the area is Homogeneous which means it only includes the same color (soft tissues in the case)

How to do all the above without manually selecting the areas in red squares, and let the program find the areas and extract them, using python lib like skimage or cv2?

What I have tried:

what I have done for now is that I have to manually select the areas (red squares) before putting them in the program

import requests
from io import BytesIO

import numpy as np
import scipy.ndimage as ndimage
from PIL import Image

# replace with your image loading routines
img ='').content))
np_img = np.asarray(img)

red_parts = (np_img == (255, 0, 0, 255)).all(axis=-1)  # find red parts of RGBA image
filled_rects = ndimage.binary_fill_holes(red_parts)  # fill the rects to get a binary mask of ROI
rects_inner = filled_rects ^ red_parts  # remove the red border
labelled_rects, num_rects = ndimage.label(rects_inner)  # label/number each individual rect

ROIs = []
for i in range(1, num_rects + 1):  # 0 is background
    current_mask = labelled_rects == i
    x, y = np.where(current_mask)  # indices where current_mask is True (= area of interest)
    sub_image = np_img[x.min():x.max(), y.min():y.max()]  # extract image data inside rects
    sub_image = sub_image[1:-1, 1:-1]  # remove remaining red border (might be an image compression artefact, needs testing)
pil_imgs = [Image.fromarray(roi) for roi in ROIs]
Updated 12-Jun-22 1:39am

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900