简体   繁体   中英

How to crop and store bounding box image regions in Python?

在此处输入图像描述

My idea is to use the multiple bounding box coordinates of the abnormal regions for a given image and crop these regions to save to a separate folder. I have written the code as shown below, to crop these multiple bounding box coordinates for a single image, however,I also get the bounding box which I have to get rid of.

import pandas as pd
import cv2
import numpy as np

df = pd.read_csv('excel1.csv')
image = cv2.imread('image2.png')
im_name = 'image2.png'

for i in range(len(df)):
    name = df.loc[i]['filename']
    if name == im_name:
        start_point = (df.loc[i]['x'],df.loc[i]['y'])  
        end_point = (df.loc[i]['x']+df.loc[i]['width'],df.loc[i]['y']+df.loc[i]['height'])  
        color = (128, 0, 0)  
        thickness = 2  
        image = cv2.rectangle(image, start_point, end_point, color, thickness) 
        crop = image[df.loc[i]['y']:df.loc[i]['y']+df.loc[i]['height'],
                     df.loc[i]['x']:df.loc[i]['x']+df.loc[i]['width']]
        cv2.imwrite("cropped/crop_{0}.png".format(i), crop)  
cv2.imwrite('bb.png', image)

Use numpy slicing in the loop and then Python/OpenCV imwrite() that crop also inside the loop with a different name for each iteration of the loop

crop = image[ystart:ystop, xstart:xstop]
cv2.imwrite("crop_{0}.png".format(i), crop)


You can also add a different path for each image you want to write if you want them to go to different folders.

For numpy slicing, see https://www.w3schools.com/python/numpy_array_slicing.asp

I found a solution. I removed cv2.rectangle just because I anted to store only the bounding box regions so that the bounding boxes do not appear.

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