当前位置:   article > 正文

python删除边框_python 删除图片外边框

python 删除图片外边框
# encoding: utf-8
# author: qbit
# date: 2020-06-15
# summary: 去除图片纯色边框
import shutil
from PIL import Image, ImageChops
Image.MAX_IMAGE_PIXELS = 10000000000
import numpy as np
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('IR_3000.png', 'IR_3000(new).png')
   

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
# encoding: utf-8
# author: qbit
# date: 2020-09-2
# summary: 给宽图片上下补白边,让其满足一定比例,然后缩放到指定尺寸

import math
from PIL import Image
Image.MAX_IMAGE_PIXELS = 10000000000
def add_white_edge(inImgPath, outImgPath, width, height):
    r"""
    给宽图片上下补白边,让其满足一定比例,然后缩放到指定尺寸
    inImgPath: 输入图片路径
    outImgPath: 输出图片路径
    width: 最终宽度
    height: 最终高度
    """
    print(f'{inImgPath}')
    inImg: Image.Image = Image.open(inImgPath)
    bgWidth = inImg.width
    bgHeight = inImg.height
    if bgWidth > bgHeight:
        bgHeight = math.ceil((bgWidth * height) / width)

    # 创建一个白色背景图片
    bgImg: Image.Image = Image.new("RGB", (bgWidth, bgHeight), (255, 255, 255))
    bgImg.paste(inImg, (0, round((bgHeight - inImg.height) / 2)))

    bgImg.resize((width, height), Image.LANCZOS).save(outImgPath)

if __name__ == "__main__":

    add_white_edge('IR_3000(new).png', 'IR_3000_4.png', 46170, 23085)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/604198
推荐阅读
相关标签
  

闽ICP备14008679号