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

enter image description here

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)


Solution 1:[1]

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

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fmw42
Solution 2 shiva