[英]How to Crop Multiple Images
I'm working on a project to crop 3000 images.我正在做一个裁剪 3000 张图像的项目。 I have created 3000 images using an algorithm, and am trying to crop them.我已经使用算法创建了 3000 张图像,并正在尝试裁剪它们。 Currently, they are all sitting in a folder with names that follow the same format - "img1", "img2", "img3" etc. I have tried using online tools to crop all of these images but it isn't working.目前,它们都位于一个名称相同的文件夹中——“img1”、“img2”、“img3”等。我尝试使用在线工具裁剪所有这些图像,但它不起作用。 I'm looking for an approach, whether using a free software to crop all of them at once or using python to crop these images and store them in a separate folder.我正在寻找一种方法,无论是使用免费软件一次裁剪所有图像,还是使用 python 裁剪这些图像并将它们存储在单独的文件夹中。
I have written a small code to do that for you.我已经写了一个小代码来为你做这件事。
pip install opencv-python pip 安装 opencv-python
import cv2 as cv
import os
#First get the list of images in the folder
list_of_original_images = os.listdir("images") #Add the path to the folder
#Create a new directory to store the cropped images
os.mkdir("Cropped_Images")
#Iterate through the image_list
for image_path in list_of_original_images:
image_array = cv.imread(image_path) # Here we load image using opencv
height,width,channel = image_array.shape #Here we get the height,width and color channel
cropped_image = image_array[0:height//2,0:width//2] # Using array slicing we cut some part of the image and save in a new variable
# Write cropped image to Cropped Images folder
cv.write(f"Cropped_Images/{image_path}",cropped_image)
Using the Pillow library makes it quite easy:使用Pillow库非常容易:
from PIL import Image;
DirectoryPath = r"C:\Users\...\FolderWithImages";
Images = GetFiles(DirectoryPath);
for Img in Images:
BaseImg = Image.open(Img);
#The arguments to .crop is a rect (X,Y,Width,Height)
CroppedImg = im.crop((0,0,500,500))
CroppedImg.save("Path");
To get all files in a directory you can look here要获取目录中的所有文件,您可以查看此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.