赞
踩
# 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')
# 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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。