简体   繁体   中英

Cropping and storing bounding box image regions for a collection of images?

The current code aims to crop and store multiple bounding box image regions for a set of images in a folder. The cropped bounding box image regions are store to a different folder. There are a total of 100 images, each image has multiple bounding boxes. The CSV file contains multiple bounding box coordinates for every given image. The code is as shown:

import pandas as pd
import cv2
import numpy as np
import glob
import os

filenames = glob.glob("folder/abnormal/*.png")
filenames.sort()
images = [cv2.imread(img) for img in filenames]
print(images)
df = pd.read_csv('abnormal.csv')

for img in images:
    for i in range(len(df)):
        name = df.loc[i]['patientId']
        start_point = (df.loc[i]['x_dis'],df.loc[i]['y_dis'])  
        end_point = (df.loc[i]['x_dis']+df.loc[i]['width_dis'],df.loc[i]['y_dis']+df.loc[i]['height_dis'])  
        crop = img[df.loc[i]['y_dis']:df.loc[i]['y_dis']+df.loc[i]['height_dis'],
                     df.loc[i]['x_dis']:df.loc[i]['x_dis']+df.loc[i]['width_dis']]
        cv2.imwrite("abnormal/crop_{0}.png".format(i), crop)

On running the code above, the loop continues indefinitely. It happens so that all crops are with respect of the bounding box image regions for image1, and then all crops stored are converted with respect of the bounding box image regions for image2, and so on. What is needed is the multiple box regions for each image and cropped and stored once.The images start with name patient*.png (patient1.png) or patient*.*.png (patient1_1.png).

The following code snippet should do the job:

filenames = glob.glob("folder/abnormal/*.png")
filenames.sort()
df = pd.read_csv('abnormal.csv')
im_csv_np = df.loc[:,"patientId"].values

for f in filenames:
    img = cv2.imread(f)
    img_name = f.split(os.sep)[-1]
    idx = np.where(im_csv_np == img_name)
    if idx[0].shape[0]: # if there is a match shape[0] should 1, if not 0
        for i in idx:
            name = df.loc[i]['patientId']
            start_point = (df.loc[i]['x_dis'],df.loc[i]['y_dis'])  
            end_point = (df.loc[i]['x_dis']+df.loc[i]['width_dis'],df.loc[i]['y_dis']+df.loc[i]['height_dis'])  
            crop = img[df.loc[i]['y_dis']:df.loc[i]['y_dis']+df.loc[i]['height_dis'],
                        df.loc[i]['x_dis']:df.loc[i]['x_dis']+df.loc[i]['width_dis']]
            cv2.imwrite("abnormal/crop_{0}.png".format(i), crop)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM