如何使用边界框坐标裁剪图像中的感兴趣区域?

How to crop regions of interest in an image using bounding box coordinates?

我有几个灰度图像,每个图像都有多个兴趣区域,以矩形边界框的形式。这些图像的多个边界框坐标存储在 CSV 文件中。我希望将这些边界框与它们各自的图像相乘,以便只留下感兴趣的区域。这是代码:

import numpy as np
from skimage.measure import label, regionprops
from skimage import io
from scipy.ndimage.morphology import binary_fill_holes
import os
import glob
import pandas as pd
import cv2

#get mask coordinates
def get_mask(img_name, df, h, w):
    im_csv_np = df.loc[:,"patientId"].values
    idx = np.where(im_csv_np == img_name)
    if idx[0].shape[0]: 
        mask = np.zeros((len(idx[0]),h,w))
        for k,j in enumerate(idx[0]):
            i = j.item()
            mask[k,int(df.loc[i]['y_dis']):int(df.loc[i]['y_dis'])+int(df.loc[i]['height_dis']),
                        int(df.loc[i]['x_dis']):int(df.loc[i]['x_dis'])+int(df.loc[i]['width_dis'])] = 1.0
    else:
        mask = np.zeros((1,h,w))
    return mask

#read data
filenames = glob.glob("data/*.png")
filenames.sort()
df1 = pd.read_csv('bbox.csv')

for f in filenames:
    img = cv2.imread(f, cv2.IMREAD_GRAYSCALE)
    h,w = img.shape
    img_name = f.split(os.sep)[-1]
    print(img_name)
    mask1 = get_mask(img_name, df1, h, w)
    for i in range(len(mask1)):
        props = regionprops(mask1[i].astype(np.int8))[0]
        df_csv = {"patientId": img_name,
                  "x_dis": props.bbox[1],
                  "y_dis": props.bbox[0],
                  "width_dis": abs(props.bbox[3]-props.bbox[1]),
                  "height_dis": abs(props.bbox[2]-props.bbox[0])}
        contours, _ = cv2.findContours(mask1[i].astype(np.uint8), 
                                       cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        for contour in contours:
            cropped_image = 
            ......
            ......
    
    io.imsave(os.path.join("bbox",
                           f.split(os.sep)[-1][:-4]+'.png'), cropped_image) 

我在乘以图像和边界框以及保存 ROI 图像方面需要帮助。

您不需要寻找等高线。您已经有了 bbox 信息。 试试这个:

for f in filenames:
    img = cv2.imread(f, cv2.IMREAD_GRAYSCALE)
    h,w = img.shape
    img_name = f.split(os.sep)[-1]
    print(img_name)
    mask1 = get_mask(img_name, df1, h, w)
    for i in range(len(mask1)):
        props = regionprops(mask1[i].astype(np.int8))[0]
        
        cropped_image = img[props.bbox[0]:props.bbox[2],props.bbox[1]:props.bbox[3]]
    
        io.imsave(os.path.join("bbox",
                           f.split(os.sep)[-1][:-4]+'_'+str(i)+'.png'), cropped_image)