您现在的位置是:网站首页> 编程资料编程资料

Python批量裁剪图形外围空白区域_python_

2023-05-26 321人已围观

简介 Python批量裁剪图形外围空白区域_python_

一、基本描述

批量裁剪掉图片的背景区域,一般是白色背景,从而减少背景值的干扰和减少存储空间。

通过检索所有图片的最小裁剪区域坐标值,然后再对图片进行裁剪。文中图都是经过标准化处理的,核心图片内容尺度都一致,所以采用该种办法,如果有很多不同大小的图片,即图片中的内容区域大小形状不一样,则一张一张的检索该图的背景区域,然后进行裁剪。即一张一张的检索裁剪区域并进行裁剪。

二、实现代码

对原文中的代码进行修改,一张一张的检索每张图的裁剪区域坐标,然后裁剪。

代码如下:

from PIL import Image import numpy as np import os   imagesDirectory = r"C:\Users\Administrator\Desktop\out"  # tiff图片所在文件夹路径   i = 0 for imageName in os.listdir(imagesDirectory):     imagePath = os.path.join(imagesDirectory, imageName)     image = Image.open(imagePath)  # 打开tiff图像     ImageArray = np.array(image)     row = ImageArray.shape[0]     col = ImageArray.shape[1]     print(row,col)     # 先计算所有图片的裁剪范围,然后再统一裁剪并输出图片     x_left = row     x_top = col     x_right = 0     x_bottom = 0     # 上下左右范围     """     Image.crop(left, up, right, below)     left:与左边界的距离     up:与上边界的距离     right:还是与左边界的距离     below:还是与上边界的距离     简而言之就是,左上右下。     """     i += 1     for r in range(row):         for c in range(col):             #if ImageArray[row][col][0] < 255 or ImageArray[row][col][0] ==0:             if ImageArray[r][c][0] < 255 and ImageArray[r][c][0] !=0: #外框有个黑色边框,增加条件判断                 if x_top > r:                     x_top = r  # 获取最小x_top                 if x_bottom < r:                     x_bottom = r  # 获取最大x_bottom                 if x_left > c:                     x_left = c  # 获取最小x_left                 if x_right < c:                     x_right = c  # 获取最大x_right     print(x_left, x_top, x_right, x_bottom)      # image = Image.open(imagePath)  # 打开tiff图像     cropped = image.crop((x_left-5, x_top-5, x_right+5, x_bottom+5))  # (left, upper, right, lower)     cropped.save(r"C:\Users\Administrator\Desktop\out_cut_bg\{}.png".format(imageName[:-4], i))     print("imageName completed!")

三、效果

原图显示:

 裁剪结果显示:

 原文效果:

到此这篇关于Python批量裁剪图形外围空白区域的文章就介绍到这了,更多相关Python批量裁剪图形内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网