【问题标题】:Can't save a PIL image file after cropping out extra transparent pixels裁剪掉额外的透明像素后无法保存 PIL 图像文件
【发布时间】:2021-01-29 22:38:55
【问题描述】:

我有这个函数,它采用 svg 徽标,将它们转换为 png(第一个 for 循环),删除多余的透明像素并将其保存到目标文件夹(第二个 for 循环)。

def convert_to_png(source_path, destination_path, output_w, output_h):
    if not os.path.exists(destination_path):
        os.mkdir(destination_path)

    # Turns SVG images to to PNG
    for i in os.listdir(source_path):
        new_file_name = i.split('.')
        new_file_name = new_file_name[0]
        cairosvg.svg2png(url=source_path + str(i), write_to=destination_path + str(new_file_name) + '.png',
                         output_width=output_w, output_height=output_h)

    for j in os.listdir(destination_path):

        img = cv2.imread(destination_path + j, cv2.IMREAD_UNCHANGED)
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA)

        logo = Image.fromarray(np.uint8(img)).convert('RGBA').crop().getbbox()

        logo.save(destination_path + j, 'PNG')

这就是我调用函数的方式:

convert_to_png(current_dir + '/riot_sponsors/', current_dir + '/new_logos/', 2000, 1500)

由于某种原因,我收到此错误:

logo.save(destination_path + j, 'PNG')
AttributeError: 'tuple' object has no attribute 'save'

我的目标是将新裁剪的 png 文件保存到 destination_path

【问题讨论】:

    标签: python tuples python-imaging-library attributeerror cv2


    【解决方案1】:

    .getbbox() 返回左、右、上、下坐标的元组。这就是返回给 logo 变量的内容。

    如果要删除图像的透明部分,请使用以下代码:

    logo = Image.fromarray(np.uint8(img)).convert('RGBA')
    logo = logo.crop(logo.getbbox())
    

    【讨论】:

    • 是的,但我仍然需要删除额外的透明像素
    • 如果您只需要边界框,可以将其保存为单独的变量。像这样:logo_bbox = logo.getbbox()
    • 我想截取 png,裁剪掉多余的透明像素并保存
    • @oo92 哦,我明白了,你需要将 bbox 传递给crop,让我更新我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2018-10-09
    • 1970-01-01
    相关资源
    最近更新 更多