-2

I have a an image directory I have loaded into a dataframe with annotations coordinates, I am trying to crop the images according to the coordinates (xmin, xmax, ymin, ymax) and save them into a new dataframe but keep getting an error.

This is the code I have so far:

Here is the df I have

File_Path xmin xmax ymin ymax filename
/MyDrive/Brand_Logos/img1.jpg 100 200 100 200 img1.jpg
/MyDrive/Brand_Logos/img2.jpg 200 300 200 300 img2.jpg
/MyDrive/Brand_Logos/img3.jpg 200 300 200 300 img3.jpg

here is the code I am trying to use to parse all the files and save them to a new directory

import pandas as pd
import os
import cv2

df = pd.read_csv('annotations.csv')

src_path = '/MyDrive/Brand_Logos/'

if not os.path.exists(os.path.join(src_path,'imageProcessDir')):
    os.mkdir(os.path.join(src_path,'imageProcessDir'))

dest_path = src_path+'imageProcessDir'

for index, row in df.iterrows():
 filename = row['filename']
    xmin = row['xmin']
    xmax = row['xmax']
    ymin = row['ymin']
    ymax = row['ymax']
    xmin = int(xmin)
    xmax = int(xmax)
    ymin = int(ymin)
    ymax = int(ymax)
    image = cv2.imread(src_path+row['filename'])
    crop = image((xmin, ymin), (xmax, ymax))
    cv2.imwrite(dest_path+"/"+filename+ "_" +'cropped'+".jpg", crop)

I have a feeling that the cv2 or the crop variable are not working properly, what am I missing?

2 Answers2

0

You don't use the correct way to crop the image, you should do like this:

crop = image[xmin:xmax, ymin:ymax]
César Debeunne
  • 407
  • 2
  • 10
0

You are calling the image array with image((xmin, ymin), (xmax, ymax)), instead of slicing image[ymin:ymax, xmin: xmax].

In your case, if I want to read and save the image with 3 channels, I would do the following:

image = cv2.imread(src_path+row['filename'])
crop = image[ymin:ymax, xmin:xmax]