温馨提示×

怎么用python擦除图片中的文字

小亿
178
2023-10-25 17:35:20
栏目: 编程语言

要擦除图片中的文字,可以使用Python的图像处理库PIL(Pillow)来实现。以下是一个简单的示例代码:

from PIL import Image, ImageDraw

def erase_text(image_path, text_coordinates):
    # 打开图片
    img = Image.open(image_path)
    draw = ImageDraw.Draw(img)

    # 在要擦除的文字区域上绘制与背景颜色相同的矩形
    for coordinates in text_coordinates:
        x1, y1, x2, y2 = coordinates
        draw.rectangle((x1, y1, x2, y2), fill="white")

    # 保存修改后的图片
    img.save("erased_image.png")

# 示例用法
text_coordinates = [(100, 100, 200, 150)]  # 要擦除的文字区域的坐标
erase_text("example_image.png", text_coordinates)

在上述代码中,需要指定要擦除的文字区域的坐标text_coordinates,示例中使用一个矩形坐标作为示例。然后,使用PIL库中的ImageDraw模块在指定的区域上绘制与背景颜色相同的矩形,从而实现擦除文字的效果。最后,保存修改后的图片为erased_image.png

请注意,此方法只能擦除文字,对于复杂的背景或文本样式可能无法产生理想的效果。

0