Python で画像からテキストを消去する方法

画像から文字を消去するには、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` として保存します。

文字のみを消去する方法ですので、複雑な背景やテキストの装飾は対応できませんこと、ご了承ください。

bannerAds