简体   繁体   English

裁剪和存储图像集合的边界框图像区域?

[英]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.一共有100张图片,每张图片都有多个边界框。 The CSV file contains multiple bounding box coordinates for every given image. CSV 文件包含每个给定图像的多个边界框坐标。 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.碰巧所有裁剪都与 image1 的边界框图像区域有关,然后所有存储的裁剪都根据 image2 的边界框图像区域进行转换,依此类推。 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).需要的是每个图像的多个框区域并裁剪和存储一次。图像以名称 patient*.png (patient1.png) 或 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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