Search code examples
pythonopencvcrop

Crop cellphone image with python


I'm trying to crop all the images contained in a folder. I want to keep the object in the picture and make the background black by coping the cropped image and paste it to another file in the same coordinates as obtained from the source.

I have all the coordinates stored in a csv file with this structure:

Filename xmax xmin ymax ymin
a.jpg 768 4 512 8
b.jpg 1200 3 899 10

I use this code for reach my goal:

import cv2
import numpy as np
save_path = '/content/drive/MyDrive/Colab Notebooks/object_cropped'
train_path = '/content/train'

with open('min_max.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
      xmax = int(row['xmax'])
      xmin= int(row['xmin'])
      ymax = int(row['ymax'])
      ymin = int(row['ymin'])
 
      image = cv2.imread(os.path.join(train_path , row['Filename'])) 
      
      object_ = image[ymin:xmax, xmin:ymax] 
 
      h, w, c = image.shape
 
      black_background = np.zeros([h, w, 3])
      for y in range(h):
          for x in range(w):
              black_background[y,x] = [0,0,0] 
 
      black_background[ymin:xmax, xmin:ymax] = object_  
      cv2.imwrite(os.path.join(save_path , 'cropped_' + row['Filename']), black_background)

It works very well for images taked from the web but when i try to apply this code with pictures taked with cellphone it doesn't work.

Both images (web images and cellphone images) are jpg with horizontal and vertical resolution :96dpi bit depth: 24, the only things that are not in common is the image size.

How can i solve this problem?

EDIT: Example:

Photo: enter image description here

I need to crop the object inside the boundaries box.

But when i apply the code, the result is:enter image description here

Values used:

xmax = 949
xmin= 489
ymax = 1829
ymin = 181

This happens only with pictures taked with cellphone or tablet.


Solution

  • The problem is object_ = image[ymin:xmax, xmin:ymax]. The solution is:

    import cv2
    import numpy as np
    save_path = '/content/drive/MyDrive/Colab Notebooks/object_cropped'
    train_path = '/content/train'
    
    with open('min_max.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
          xmax = int(row['xmax'])
          xmin= int(row['xmin'])
          ymax = int(row['ymax'])
          ymin = int(row['ymin'])
     
          image = cv2.imread(os.path.join(train_path , row['Filename'])) 
          
          object_ = image[ymin:ymax, xmin:xmax] ####the right solution
     
          h, w, c = image.shape
     
          black_background = np.zeros([h, w, 3])
          for y in range(h):
              for x in range(w):
                  black_background[y,x] = [0,0,0] 
     
          black_background[ymin:ymax, xmin:xmax] = object_ ####the right solution 
          cv2.imwrite(os.path.join(save_path , 'cropped_' + row['Filename']), black_background)