吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 544|回复: 13
收起左侧

[Python 原创] Python批量把白底图片比例转换成4:3

[复制链接]
linjian648 发表于 2024-4-18 15:23
做电商可能用得到,今天我就有这个需求,然后找gpt帮我写了代码。比较简单,所有我会把跟gpt的聊天记录发在帖子后面,有兴趣可以看看。
流程就是,先检测图片的白边,然后把白边都删掉,留10个像素的白边,全删完了太难看。
然后检测图片比例,用白色像素来填充不够的区域,原来的图片居中。
[Python] 纯文本查看 复制代码
import os
from PIL import Image
import numpy as np

def crop_image(image_path):
    img = Image.open(image_path)
    # Convert image to numpy array
    img_data = np.asarray(img)
    # Get the bounding box
    non_white_pixels = np.where(img_data != 255)
    min_y, max_y = np.min(non_white_pixels[0]), np.max(non_white_pixels[0])
    min_x, max_x = np.min(non_white_pixels[1]), np.max(non_white_pixels[1])
    
    # Adjust the bounding box to leave a 10 pixel border
    min_y = max(0, min_y - 10) # Ensure it's not less than 0
    min_x = max(0, min_x - 10) # Ensure it's not less than 0
    max_y = min(img_data.shape[0], max_y + 10) # Ensure it's not greater than the image height
    max_x = min(img_data.shape[1], max_x + 10) # Ensure it's not greater than the image width

    # Crop the image to this bounding box
    cropped_img = img.crop((min_x, min_y, max_x, max_y))
    # Save the cropped image
    cropped_img.save(image_path)

# original function to resize image to 4:3
def resize_image_to_43(image_path):
    img = Image.open(image_path)
    original_width, original_height = img.size
    target_aspect_ratio = 4 / 3

    # Calculate target size with same aspect ratio
    if original_width / original_height > target_aspect_ratio:
        # if image is wider than target aspect ratio, adjust height
        target_height = int(original_width / target_aspect_ratio)
        target_width = original_width
    else:
        # if image is taller than target aspect ratio, adjust width
        target_width = int(original_height * target_aspect_ratio)
        target_height = original_height

    # Create new image with white background
    new_img = Image.new("RGB", (target_width, target_height), "white")

    # calculate paste coordinates to center original image
    paste_x = (target_width - original_width) // 2
    paste_y = (target_height - original_height) // 2

    new_img.paste(img, (paste_x, paste_y))

    # Save new image overwriting the old one
    new_img.save(image_path)

# now we integrate them in process_images function
def process_images(folder):
    for filename in os.listdir(folder):
        if filename.endswith(".jpg") or filename.endswith(".png") or filename.endswith(".webp"):
            image_path = os.path.join(folder, filename)
            print(f"Processing image at {image_path}")
            crop_image(image_path)
            resize_image_to_43(image_path)
            
# replace this with your own directory
folder = "F:\Desktop\新建文件夹"

process_images(folder)


聊天记录:

  上午 10:47
Python 能不能给图片加上空白色块来增加图片比例

coze
应用  上午 10:48
当然可以,Python 的 pillow 库可以帮助你轻松实现这个需求。下面是一个简单的例子,增加图片的比例,并填充白色空白:
python
from PIL import Image

def add_white_block(image_path):
    # 打开原始图片
    img = Image.open(image_path)

    # 获取原始图片的宽度和高度
    width, height = img.size

    # 在图片的宽、高上加上需要的白色块的大小
    new_width = width + 100 # 这中间的 100 你可以改成你需要的尺寸
    new_height = height + 100 # 这中间的 100 你可以改成你需要的尺寸

    # 创建新图片,这个新图片是一个白色背景的图片
    new_img = Image.new("RGB", (new_width, new_height), "white")

    # 把原始的图片添加到新图片上,我这里的位置定的是左上角,你可以根据需要来改变位置
    new_img.paste(img, (0, 0))

    # 保存新图片
    new_img.save("new_img.jpg", "JPEG")

# 使用函数
add_white_block("test.jpg")
这个脚本读取原始图片,创建新的更大的图片,然后在新图片上贴上原始图片。新图片的额外空间会自动填充为白色,您可以根据需要调整新图片大小。



  上午 10:51
那用这个思路帮我写一个脚本,把指定文件夹下面的所有图片的比例变成4:3,原来的图片内容要居中

coze
应用  上午 10:53
好的,以下是实现该功能的 Python 脚本。它将遍历指定的文件夹,将每个图片调整为 4:3 的比例,原始图片内容居中,并在需要的时候填充白色背景。
python
import os
from PIL import Image


def resize_images_to_43_aspect_ratio(directory):
    for filename in os.listdir(directory):
        if filename.endswith(".jpg") or filename.endswith(".png"):
            filepath = os.path.join(directory, filename)
            img = Image.open(filepath)

            original_width, original_height = img.size
            target_aspect_ratio = 4/3

            # Calculate target size with same aspect ratio
            if original_width / original_height > target_aspect_ratio:
                # if image is wider than target aspect ratio, adjust height
                target_height = int(original_width / target_aspect_ratio)
                target_width = original_width
            else:
                # if image is taller than target aspect ratio, adjust width
                target_width = int(original_height * target_aspect_ratio)
                target_height = original_height

            # Create new image with white background
            new_img = Image.new("RGB", (target_width, target_height), "white")

            # calculate paste coordinates to center original image
            paste_x = (target_width - original_width) // 2
            paste_y = (target_height - original_height) // 2

            new_img.paste(img, (paste_x, paste_y))

            # Save new image overwriting the old one
            new_img.save(filepath)


# Use function on a directory
resize_images_to_43_aspect_ratio("/path/to/your/directory")
请注意将 "/path/to/your/directory" 替换为你实际的文件夹路径。这个脚本默认会覆盖原来的图片,如果你希望保留原图,可以在 new_img.save(filepath) 这一行修改文件路径来保存为新的文件。例如 new_img.save(os.path.join(directory, "resized_" + filename)),这样会在原文件名前添加 "resized_" 并保存为新的文件。



  上午 10:54
批处理有这种功能么

coze
应用  上午 10:55
Batch 或批处理脚本主要用于自动执行简单的任务,如文件管理(删除、复制、重命名等),但它不擅长处理图像任务,如修改图片比例或添加填充。这类任务通常需要具备图像处理功能的语言或库的支持,例如 Python 的 PIL(Pillow)库。为了完成这个任务,你可能需要依赖一些第三方的命令行工具,比如 ImageMagick。然而,使用这些工具会使得过程变得更复杂,而且需要你单独安装和配置这些工具。
所以,对于复杂一些的图像处理任务,我仍建议使用像 Python 这样的编程语言,它的功能更强大,使用起来也更灵活。



  上午 10:58
pillow库要单独安装么

coze
应用  上午 10:59
是的,Pillow 是一个 Python 的第三方库,用于处理图像,它并不是 Python 的标准库。所以在使用 Pillow 之前,需要单独安装。
在安装 Pillow 前,你需要确保你的电脑上已经安装有 Python。安装 Python 后,你可以通过 Python 的包管理工具 pip 来安装 Pillow。
在命令行或者终端中,你可以使用下面的命令来安装 Pillow:
bash
pip install pillow
如果你使用的是 Python3,也可以尝试使用下面的命令:
bash
pip3 install pillow
安装成功之后,你就可以在你的 Python 脚本中引入并使用 Pillow 了。例如:
python
from PIL import Image

# 打开一个图片文件
img = Image.open('example.jpg')
# 显示该图片
img.show()
这些都是基础的使用方法,如果你想进行更复杂的操作,比如裁剪,旋转图片等等,你可以查阅 Pillow 的官方文档或者搜索相关教程。



  上午 11:17
那么能不能实现查找图片最外围不是白色色块的地方,来实现把多余的空白区域删掉来实现缩小图片尺寸

coze
应用  上午 11:18
当然可以,这个功能可以通过使用Pillow库中的 getbbox 函数实现。`getbbox`可以获取图像中非空白部分的边框。就是说,这个函数可以找到图像中包含实际内容(即非空白部分)的最小矩形。
以下是一个Python脚本示例,通过 getbbox 来裁剪掉图片的空白部分:
python
from PIL import Image

def remove_whitespace(image_path):
    img = Image.open(image_path)
   
    # getbbox获取非空白部分的矩形边界
    bbox = img.getbbox()
   
    # 对图片进行裁剪
    cropped_img = img.crop(bbox)
   
    # 覆盖保存原图片
    cropped_img.save(image_path)

# 使用函数移除一张图片的空白部分
remove_whitespace('/path/to/your/image.jpg')
请将 '/path/to/your/image.jpg' 替换为你想要裁剪的图片的路径。
这段代码会将处理后的图片保存回原文件,如果你不想覆盖原文件,你可以将 cropped_img.save(image_path) 这一行修改为保存为新的文件,例如 cropped_img.save('/path/to/your/new_image.jpg') 这样会以新的文件名保存处理后的图片。
注意,这个函数只会移除像素完全是白色(RGB值为(255,255,255))的区域,如果图片周围有非完全的白色,例如灰色,这些区域是不会被移除的。



  上午 11:24
能不能改成指定文件夹下的所有图片

coze
应用  上午 11:25
当然可以,这只需要在之前的脚本基础上稍做添加就可以实现让这个脚本处理一个文件夹下的所有图片。需要用到 os 库来处理文件路径和文件名,以及 fnmatch 库来匹配图片文件。
以下是一个处理文件夹下所有特定类型图片的 Python 脚本示例:
python
from PIL import Image
import os
import fnmatch

def remove_whitespace(image_path):
    img = Image.open(image_path)
    bbox = img.getbbox()
    cropped_img = img.crop(bbox)
    cropped_img.save(image_path)

def process_directory(directory, file_ext):
    # 遍历目录下的所有文件和子目录
    for path, dirs, files in os.walk(directory):
        # 遍历所有的文件
        for filename in files:
            # 检查当前文件的扩展名,如果其为指定的图片格式,则进行处理
            if fnmatch.fnmatch(filename, f"*.{file_ext}"):
                # 将目录路径和文件名合并为完整的文件路径
                file_path = os.path.join(path, filename)
                # 对图片进行处理
                remove_whitespace(file_path)

# 使用函数处理一个目录下的所有 jpg 图片
process_directory("/path/to/your/directory", "jpg")
你只需要将 "/path/to/your/directory" 替换为你要处理的文件夹路径,然后将 "jpg" 替换为你要处理的图片文件类型(只需要填写文件扩展名,如 "png","jpeg"等)。这个脚本会遍历指定的目录以及所有子目录,并将其中的指定类型的图片进行处理。
注意,该程序会对文件夹内所有匹配的文件进行操作,所以建议先在几个图片上进行测试,确保它的效果符合预期再处理大量文件。



  上午 11:28
好没起作用
11:28
图片的多余的白色区域没有变小

coze
应用  上午 11:29
我很抱歉听到程序没有按照预期的方式工作。一个可能的原因是,如我提到的,这个函数只会裁剪完全是白色(RGB值为(255,255,255))的区域,如果图片周围有非完全白色的部分,例如有些图像可能周围是非完全白色的,那么这些区域是不会被裁剪的。
如果方便的话,你能否提供一些更具体的信息,例如你的原始图片以及你期望的结果?这样我可以更好地帮助你解决问题。
11:29
对不起给你带来了困扰。代码无法正常工作可能有很多原因,比如文件路径问题、文件权限问题、图片格式问题等等。
当遇到问题时,最有效的解决方法是检查错误提示。你在运行代码时遇到了什么错误提示吗?有的话,可以告诉我,我会尽我最大努力帮助你解决问题。
另外,你也可以检查一下以下几点:
- 确定你的文件路径填写正确,代码中的 "/path/to/your/directory" 需要替换为你的实际路径,如 "C:/Users/Username/Pictures" 等。
- 你的文件路径和图片格式填写正确。   文件格式 "jpg" 是否与你要处理的图片的实际格式相符。
- 检查你的 python 环境中已经安装了 PIL库 (或 Pillow库),并且是可以正常使用的。
- 检查你的处理图片的函数( remove_whitespace函数)是否有正确的返回值。
不过你不必为解决这个问题感到气馁,编程就是一直解决问题的过程,相信你可以解决它!



  中午 11:31
怎么检验remove_whitespace有返回正确的值

coze
应用  中午 11:32
你可以在 remove_whitespace 函数中添加一些额外的代码,用于在每次处理图片之后输出一个消息。这样,你可以看到程序是否正常运行,并且可以查看每个被处理的图片的名称。这是一种非常常见的调试技术,叫做 "输出语句调试" 或 "printf调试"。
以下是一个示例,展示了如何修改函数以输出处理过程中的信息:
python
def remove_whitespace(image_path):
    try:
        img = Image.open(image_path)
        bbox = img.getbbox()
        cropped_img = img.crop(bbox)
        cropped_img.save(image_path)
        print(f"Successfully processed image at {image_path}!")  # 添加了输出语句
    except Exception as e:
        print(f"Failed to process image at {image_path} due to {e}.")
现在,每次处理一张图片时,程序都会输出一个消息。如果图片被成功处理,程序将输出 Successfully processed image at [图片路径]!。如果在处理图片时发生了错误,程序将输出 Failed to process image at [图片路径] due to [错误信息]。 这样,我们就可以看到每次运行 remove_whitespace(image_path) 时发生了什么。
需要注意的是,这个修改版本的 remove_whitespace 函数需要在你的主程序中调用才会执行,简单地将其在 Python 终端中运行是不会有任何输出的,你需要将你的主程序运行起来,观察运行的输出内容,这样就能知道函数是否正常工作了。



  中午 11:36
没有任何输出

coze
应用  中午 11:36
如果没有任何输出,可以尝试以下几个步骤:
1. 确保你已经成功运行了修改后的`remove_whitespace`函数。
2. 检查`image_path`变量,确保它链接到了有效的图片文件。你可以尝试打印`image_path`来看看它的实际值。
3. 检查你的图片文件是存在,且Python有正确的读写权限。
4. 对比输出的信息以确定是否有错误发生。如果有错误信息,但看起来不直观,你或许需要搜索错误信息来获取更多关于问题的信息。
如果以上步骤都不能解决问题,那可能你的`remove_whitespace`函数未正确被调用。你需要检查是否在正确的位置调用了这个函数,或者重新审视你的代码以确保所有的逻辑都是你想要的。



  中午 11:39
我现这样的路径对么:from PIL import Image
import os
import fnmatch
def remove_whitespace(image_path):
    try:
        img = Image.open(image_path)
        bbox = img.getbbox()
        cropped_img = img.crop(bbox)
        cropped_img.save(image_path)
        print(f"Successfully processed image at {image_path}!")  # 添加了输出语句
    except Exception as e:
        print(f"Failed to process image at {image_path} due to {e}.")
def process_directory(directory, file_ext):
    # 遍历目录下的所有文件和子目录
    for path, dirs, files in os.walk(directory):
        # 遍历所有的文件
        for filename in files:
            # 检查当前文件的扩展名,如果其为指定的图片格式,则进行处理
            if fnmatch.fnmatch(filename, f"*.{file_ext}"):
                # 将目录路径和文件名合并为完整的文件路径
                file_path = os.path.join(path, filename)
                # 对图片进行处理
                remove_whitespace(file_path)
# 使用函数处理一个目录下的所有 jpg 图片
process_directory("F:\Desktop\新建文件夹'", "jpg")

coze
应用  中午 11:39
你的代码看起来是正确的。但是,你的文件路径可能是不正确的。在你的函数 process_directory 调用中,你的文件路径为 "F:\Desktop\新建文件夹'",末尾可能多了一个单引号 '。除此之外,Python在处理文件路径时,你需要在每个反斜杠前添加一个反斜杠,使其变为 \\,以此来转义反斜杠。正确的文件路径应该是这样的形式:"F:\\Desktop\\新建文件夹"。
所以,你的函数调用应该修改为:`process_directory("F:\\Desktop\\新建文件夹", "jpg")`。试试看这个是否可以运行。



  中午 11:41
输出是提示正确处理了,但是图片没有变小

coze
应用  中午 11:42
是的,你的输出显示图片已成功经过 remove_whitespace 函数的处理。这个函数旨在裁减图片中的空白部分,但不一定会减小图片文件的大小。如果你的图片周围没有多余的空白部分,那么这个函数处理后的图片尺寸和原始图片可能会一样。如果你希望减小图像文件的大小,你可能需要使用其他方法,比如降低图片的分辨率、降低图片的质量或把图片转换成压缩率更高的格式等。如果你确实需要调整图片大小,以上方法或许可以帮忙。



  中午 11:45
但是图片是我特意做的有很多白边的

coze
应用  中午 11:46
我明白了,你的图片有很多空白边缘,你使用这个函数的目的是希望裁剪掉这些空白边缘。我之前的解释可能没有很准确,让我澄清一下:
你的代码中使用的 getbbox 函数效果可能并不如你所期望的那样。 getbbox 函数计算的是图片内容的边界框,它的计算方式是:从左边开始,找到第一个非空白的像素;然后从顶部开始,找到第一个非空白的像素;然后从右边开始,找到第一个非空白的像素;最后,从底部开始,找到第一个非空白的像素。
所以,如果你的图片在四周有空白区域,但是图片中间部分的内容是紧凑的,那么 getbbox 可能仍然会识别出前景内容的全部区域,因为它在计算边界框时是从四个方向开始的。
对于你的情况,我建议你尝试使用其他方式来检测和裁剪空白区域。比如,你可以自定义一个函数,从四个方向开始扫描每一个像素,一旦遇到非空白的像素就停止。然后,根据这四个点的坐标来裁剪图片。这样做可能会有更好的效果。



  中午 11:47
帮我写这个代码

coze
应用  中午 11:48
当然,以下是一个实现的例子:
python
from PIL import Image
import numpy as np

def crop_image(image_path):
    img = Image.open(image_path)
    # Convert image to numpy array
    img_data = np.asarray(img)
    # Get the bounding box
    non_white_pixels = np.where(img_data!=255)
    min_y, max_y = np.min(non_white_pixels[0]), np.max(non_white_pixels[0])
    min_x, max_x = np.min(non_white_pixels[1]), np.max(non_white_pixels[1])
    # Crop the image to this bounding box
    cropped_img = img.crop((min_x, min_y, max_x, max_y))
    # Save the cropped image
    cropped_img.save(image_path)
在此函数中,通过将图片转换为 NumPy 数组,我们可以很方便地获取所有非白色像素的坐标,并据此来裁剪图像。
请注意,这份代码假定白色像素是空白区域。如果你的空白区域的颜色不是白色,或者图像背景中包含其他颜色的像素,那么你可能需要进行一些额外的颜色检查或预处理步骤。
还要注意,根据图片的颜色模式,可能需要对 img_data != 255 部分进行调整。这是因为对于 RGB 图像,需要比较的将是一个 (R, G, B) 元素的元组,而不仅仅是一个单一的像素值。



  下午 2:18
用这个替换掉上面的remove_whitespace

coze
应用  下午 2:19
好的,这里是使用新的 crop_image 函数替换掉 remove_whitespace 函数后的处理流程示例:
python
import os
from PIL import Image
import numpy as np

def crop_image(image_path):
    img = Image.open(image_path)
    # Convert image to numpy array
    img_data = np.asarray(img)
    # Get the bounding box
    non_white_pixels = np.where(img_data!=255)
    min_y, max_y = np.min(non_white_pixels[0]), np.max(non_white_pixels[0])
    min_x, max_x = np.min(non_white_pixels[1]), np.max(non_white_pixels[1])
    # Crop the image to this bounding box
    cropped_img = img.crop((min_x, min_y, max_x, max_y))
    # Save the cropped image
    cropped_img.save(image_path)
   
   
def process_images(folder):
    for filename in os.listdir(folder):
        if filename.endswith(".jpg"):
            image_path = os.path.join(folder, filename)
            print(f"Processing image at {image_path}")
            crop_image(image_path)

folder = "F:\\Desktop\\新建文件夹"
process_images(folder)
在上方代码中,我们首先定义了 crop_image 函数,该函数是按照我之前描述的方式工作的。然后,我们定义了一个新的 process_images 函数,该函数会遍历指定文件夹中的所有 .jpg 文件,并对每个图像应用 crop_image 函数。每次成功处理一个图片后,它都会打印一条消息。
为了应用这段代码,你只需要替换掉最后一行中的 folder 变量的值为你想要处理的图像所在的文件夹路径即可。
请记住,这段代码依赖于 PIL 和 NumPy,所以在使用前请确保你的 Python 环境中已经安装了这两个库。如果没有安装,你可以通过 pip install pillow numpy 来进行安装。
希望这段代码对你有所帮助!如果你有任何问题,或者需要进行任何改进,请随时告诉我。



  下午 2:35
import os
from PIL import Image
def resize_images_to_43_aspect_ratio(directory):
    for filename in os.listdir(directory):
        if filename.endswith(".jpg") or filename.endswith(".png"):
            filepath = os.path.join(directory, filename)
            img = Image.open(filepath)
            original_width, original_height = img.size
            target_aspect_ratio = 4/3
            # Calculate target size with same aspect ratio
            if original_width / original_height > target_aspect_ratio:
                # if image is wider than target aspect ratio, adjust height
                target_height = int(original_width / target_aspect_ratio)
                target_width = original_width
            else:
                # if image is taller than target aspect ratio, adjust width
                target_width = int(original_height * target_aspect_ratio)
                target_height = original_height
            # Create new image with white background
            new_img = Image.new("RGB", (target_width, target_height), "white")
            # calculate paste coordinates to center original image
            paste_x = (target_width - original_width) // 2
            paste_y = (target_height - original_height) // 2
            new_img.paste(img, (paste_x, paste_y))
            # Save new image overwriting the old one
            new_img.save(filepath)
# Use function on a directory
resize_images_to_43_aspect_ratio("/path/to/your/directory")    把这个把图片转换成4:3比例的代码加进去,处理图片的时候,先把多余的空白删掉,然后再转换成4:3

coze
应用  下午 2:36
当然,我可以帮你整合这两段代码,首先删除多余的空白,然后再将图像转换成4:3的比例。下面就是整合后的代码:
python
import os
from PIL import Image
import numpy as np

def crop_image(image_path):
    img = Image.open(image_path)
    # Convert image to numpy array
    img_data = np.asarray(img)
    # Get the bounding box
    non_white_pixels = np.where(img_data != 255)
    min_y, max_y = np.min(non_white_pixels[0]), np.max(non_white_pixels[0])
    min_x, max_x = np.min(non_white_pixels[1]), np.max(non_white_pixels[1])
    # Crop the image to this bounding box
    cropped_img = img.crop((min_x, min_y, max_x, max_y))
    # Save the cropped image
    cropped_img.save(image_path)

# original function to resize image to 4:3
def resize_image_to_43(image_path):
    img = Image.open(image_path)
    original_width, original_height = img.size
    target_aspect_ratio = 4 / 3

    # Calculate target size with same aspect ratio
    if original_width / original_height > target_aspect_ratio:
        # if image is wider than target aspect ratio, adjust height
        target_height = int(original_width / target_aspect_ratio)
        target_width = original_width
    else:
        # if image is taller than target aspect ratio, adjust width
        target_width = int(original_height * target_aspect_ratio)
        target_height = original_height

    # Create new image with white background
    new_img = Image.new("RGB", (target_width, target_height), "white")

    # calculate paste coordinates to center original image
    paste_x = (target_width - original_width) // 2
    paste_y = (target_height - original_height) // 2

    new_img.paste(img, (paste_x, paste_y))

    # Save new image overwriting the old one
    new_img.save(image_path)

# now we integrate them in process_images function
def process_images(folder):
    for filename in os.listdir(folder):
        if filename.endswith(".jpg") or filename.endswith(".png"):
            image_path = os.path.join(folder, filename)
            print(f"Processing image at {image_path}")
            crop_image(image_path)
            resize_image_to_43(image_path)
            
# replace this with your own directory
folder = "/path/to/your/directory"

process_images(folder)
这是一个将你所需所有功能集成到一个流程的脚本。当你运行 process_images 函数时,它会针对指定文件夹中的每一张图片进行处理 —— 首先调用 crop_image 函数来剪裁掉多余的白边,然后调用 resize_image_to_43 函数把图片变换到4:3的比例。
请在最后一行替换为你要处理的图片所在的文件夹路径即可。



  下午 2:41
能不能在剪裁白边的时候留下10个像素

coze
应用  下午 2:42
当然,我们可以留下10个像素的边框,只需要修改裁剪范围即可,这是一段修改后的代码:
python
def crop_image(image_path):
    img = Image.open(image_path)
    # Convert image to numpy array
    img_data = np.asarray(img)
    # Get the bounding box
    non_white_pixels = np.where(img_data != 255)
    min_y, max_y = np.min(non_white_pixels[0]), np.max(non_white_pixels[0])
    min_x, max_x = np.min(non_white_pixels[1]), np.max(non_white_pixels[1])
   
    # Adjust the bounding box to leave a 10 pixel border
    min_y = max(0, min_y - 10) # Ensure it's not less than 0
    min_x = max(0, min_x - 10) # Ensure it's not less than 0
    max_y = min(img_data.shape[0], max_y + 10) # Ensure it's not greater than the image height
    max_x = min(img_data.shape[1], max_x + 10) # Ensure it's not greater than the image width

    # Crop the image to this bounding box
    cropped_img = img.crop((min_x, min_y, max_x, max_y))
    # Save the cropped image
    cropped_img.save(image_path)
这将确保我们在提取图像的非白色区域时,保留了至少10个像素的白色边框。我们使用 max 和 min 函数来确保裁剪区域始终在图像的边界内,防止出现尝试裁剪超出图像边界的情况。



  下午 2:44
这个代码能处理webp的图片么

coze
应用  下午 2:44
PIL库支持读取和保存webp格式的图片,所以这段代码可以处理webp格式的图片。只需要稍作修改,让代码也对后缀为 ".webp" 的文件进行处理即可。这是修改后的代码:
python
def process_images(folder):
    for filename in os.listdir(folder):
        if filename.endswith(".jpg") or filename.endswith(".png") or filename.endswith(".webp"): # 这里做了修改
            image_path = os.path.join(folder, filename)
            print(f"Processing image at {image_path}")
            crop_image(image_path)
            resize_image_to_43(image_path)
            
folder = "/path/to/your/directory"
process_images(folder)
这个修改的过程告诉 process_images 函数,当文件的后缀为 .webp 时也将进行处理。然后,`crop_image` 和 resize_image_to_43 函数将可以像处理 .jpg 和 .png 文件一样处理 .webp 文件。除非图像是动态webp(它包含多帧像gif一样),否则这应该可以正常工作,因为PIL不支持动态webp。
有了这个更新,你的脚本现在应该能够处理 .jpg, .png 和 .webp 格式的图像了。

免费评分

参与人数 2吾爱币 +8 热心值 +2 收起 理由
junjia215 + 1 + 1 用心讨论,共获提升!
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| linjian648 发表于 2024-4-19 08:59
zjg121 发表于 2024-4-19 06:43
学会去白边后,可以用去白边的方法去黑边。图片反相,去白边,再反相。不知道有没有直接去黑边的参数。

这个脚本的原理是识别像素点的值,所以只要把(img_data != [255, 255, 255], axis=-1))的值调整成黑色的就行。但是我这个脚本不能去不规则黑边。因为它在扫描四个方向的像素点时只要遇到一个非白色像素点就会停下来,如果是要扣不规则的黑边,gpt跟我说要用OpenCV。
 楼主| linjian648 发表于 2024-4-18 16:08
cropped_img.save(image_path, quality=99)
new_img.save(image_path, quality=99)
试了下,转出来的图片质量会下降,在两个保存的代码后面加上图片质量好很多
dsman 发表于 2024-4-18 18:57
wj21 发表于 2024-4-18 19:00
怎么觉得这个与GPT的交流过程也挺费事的呢
chm1988 发表于 2024-4-18 22:54
打包的有吗?
平淡最真 发表于 2024-4-18 23:52
dsman 发表于 2024-4-18 18:57
ModuleNotFoundError: No module named 'PIL'

怎么破?

https://www.baidu.com/s?wd=Modul ... PIL%27&ie=UTF-8

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
dsman + 1 + 1 热心回复!

查看全部评分

zjg121 发表于 2024-4-19 06:43
学会去白边后,可以用去白边的方法去黑边。图片反相,去白边,再反相。不知道有没有直接去黑边的参数。
caojian1624 发表于 2024-4-19 08:10
谢谢分享学习下
 楼主| linjian648 发表于 2024-4-19 08:37
wj21 发表于 2024-4-18 19:00
怎么觉得这个与GPT的交流过程也挺费事的呢

不懂代码是这样的,可能懂代码的人跟我的交流方式不一样
 楼主| linjian648 发表于 2024-4-19 08:38

没有打包
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-3 14:33

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表