0

Using my code below I have successfully been able to import an image, define a list of coordinates, and then crop the image to those coordinates. However, I have two problems with my current code:

  1. Because the coordinates are in pairs, it is cropping the image and then cropping THAT image, rather than saving two separate crops as new images, separate from the parent image.

  2. When I define my coordinates in the code, it works fine. But when I uncomment the first boxcrop (line 11) to get the coordinates from my csv, it doesn't work.

Eventually, I would like the code to be able to import an image, get the coordinates of the desired crops (there could be more than 2, up to 8!) from a csv file, and then save each crop as a new image, with the same filename as the original image. for example, flowers.png would become flowers_crop1, flowers_crop2, etc etc. Any and all advice is appreciated, I have looked at other posts and not seen this same issue with saving copies so I hope I am not re-asking a question.

from PIL import Image
import numpy as np
import pandas as pd

#Open image
im = Image.open(r'C:/Users/Testing/Capture.png')

#Open excel file
df = pd.read_csv(r'C:/Users/Testing/crops.csv', header=0)
#Get coordinates of box
#boxcrop = df.values.T[2].tolist()
boxcrop = ['(212,233,226,247)','(196,217,210,231)']  

for i in boxcrop:
    left, upper, right, lower = np.array([i.replace('(', '').replace(')','').split(',')], dtype=int).T
    dims = np.concatenate([left, upper, right, lower])
    im_crop = im.crop((dims))
    im_crop.save(r'C:\Users\Testing\crops\cropped.png', quality=95)
pbthehuman
  • 123
  • 3
  • 12
  • There are two questions here. If you divide your question into two, you can have a better chance of finding the answers. For example, cropping an image can be found in https://stackoverflow.com/questions/15589517/how-to-crop-an-image-in-opencv-using-python. Then you need to search for cv2.imwrite or similar way to write your image into disk. – smttsp Apr 21 '20 at 20:19
  • @smttsp thank you for the advice! another user has quickly solved my copying problem, so now the csv input is the only issue. thank you! – pbthehuman Apr 21 '20 at 20:28

1 Answers1

2

Use:

im_crop = im.copy().crop((dims))

to crop a copy.

Use an f-string to make your filename to save:

im_crop.save(f'blahblah{i}.png')
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432