如何裁剪多张图像

问题描述 投票:0回答:3

我正在开发一个裁剪 3000 张图像的项目。我已经使用算法创建了 3000 张图像,并正在尝试裁剪它们。目前,它们都位于一个名称遵循相同格式的文件夹中 - “img1”、“img2”、“img3”等。我尝试使用在线工具裁剪所有这些图像,但它不起作用。我正在寻找一种方法,无论是使用免费软件一次裁剪所有图像,还是使用 python 裁剪这些图像并将它们存储在单独的文件夹中。

python image crop
3个回答
0
投票

我已经编写了一段小代码来为你做到这一点。

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)

0
投票

使用 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");

要获取目录中的所有文件,您可以查看此处


0
投票

BBonless 的示例有效,但对 im.crop 参数存在误解。它不是宽度和高度,而是右坐标和下坐标。仅当您想从左上角裁剪时才有效。

我下面的示例采用顶部、左侧、宽度和高度,并从中计算出右侧和下部位置。

它将提示用户输入源目录并将裁剪后的文件保存在 c: emp 中。使用另一个 fd.askdirectory() 调用,可以很容易地以与输入目录相同的方式提示输出目录。

import glob
import os
from tkinter import filedialog as fd

from PIL import Image

directory_path = fd.askdirectory()

Images = glob.glob(os.path.join(directory_path,"*.jpg"))

for image_file_and_path in Images:
    image_filename = os.path.basename(image_file_and_path)
    output_filename = os.path.join(r"c:\temp\cropped", image_filename)
    uncropped_image = Image.open(image_file_and_path)

    # The argument to crop is a box : a 4-tuple defining the left, upper, right, and lower pixel positions.
    left = 450
    top = 50
    width = 2595
    height = 3226

    CroppedImg = uncropped_image.crop((left, top, width + left, height + top))

    CroppedImg.save(output_filename)
© www.soinside.com 2019 - 2024. All rights reserved.