简体   繁体   English

Python PIL 裁剪图像并将裁剪保存为新图像/副本

[英]Python PIL to crop image and save crop as a new image/copy

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.但是当我取消注释第一个 boxcrop(第 11 行)以从我的 csv 获取坐标时,它不起作用。

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.最终,我希望代码能够导入图像,从 csv 文件中获取所需作物的坐标(可能超过 2 个,最多 8 个),然后将每个作物保存为新图像。 with the same filename as the original image, for example.例如,具有与原始图像相同的文件名。 flowers,png would become flowers_crop1, flowers_crop2. flowers,png 将变为 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)

Use:利用:

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

to crop a copy.裁剪副本。

Use an f-string to make your filename to save:使用 f-string 使您的文件名保存:

im_crop.save(f'blahblah{i}.png')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM