前言
Windows 10 2004
Python 3.8.3
Pillow 7.1.2
Python
# encoding: utf-8
# author: qbit
# date: 2020-06-15
# summary: 去除圖片純色邊框
import shutil
from PIL import Image, ImageChops
def TrimImgEdge(inImgPath, outImgPath):
r"""
去除圖片邊框
inImgPath: 輸入圖片路徑
outImgPath: 輸出圖片路徑
"""
print(f'TrimImgEdge {inImgPath} ...')
imgIn = Image.open(inImgPath)
# 建立一個邊框顏色圖片
bg = Image.new(imgIn.mode, imgIn.size, imgIn.getpixel((0, 0)))
diff = ImageChops.difference(imgIn, bg)
bbox = diff.getbbox()
if bbox:
imgIn.crop(bbox).save(outImgPath, quality=95)
else:
shutil.copyfile(inImgPath, outImgPath)
if __name__ == "__main__":
TrimImgEdge('csharp.jpg', 'csharp_pillow.jpg')
ImageMagick
magick convert csharp.jpg -fuzz 7% -trim csharp_magick.jpg
本文出自
qbit snap