Python 去除图片纯色边框(qbit)

前言

Windows 10 2004
Python 3.8.3
Pillow 7.1.2
ImageMagick 7.0.10

Pillow

# 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)
    # diff = ImageChops.add(diff, diff, 2.0, -10) # 可选,会去的更干净,副作用是误伤
    bbox = diff.getbbox()   # 返回左上角和右下角的坐标 (left, upper, right, lower)
    if bbox:
        imgIn.crop(bbox).save(outImgPath, quality=95)
    else:
        shutil.copyfile(inImgPath, outImgPath)
if __name__ == "__main__":
    TrimImgEdge('csharp.jpg', 'csharp_pillow.jpg')
  • 调整尺寸
# LANCZOS 在 Pillow 2.7 以前叫 ANTIALIAS
img.resize((width, height), Image.LANCZOS) 
  • 输入图片样例(点击图片查看边框

csharp.jpg

  • 输出图片样例(点击图片查看边框

csharp_pillow.jpg

ImageMagick

magick convert csharp.jpg -fuzz 7% -trim csharp_magick.jpg
本文出自 qbit snap

你可能感兴趣的:(图像处理)