本文主要是介绍Python批量裁剪图形外围空白区域,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.描述
图形外围空白区域比较多,需要裁剪掉,这样的图形有很多,需要批量处理
2.代码
from PIL import Image
import numpy as np
import osimagesDirectory = r"D:\PycharmProjects\pythonProject\indias\IndiasSample1" # tiff图片所在文件夹路径
x_top=200;x_left=200;x_right=0;x_bottom=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]for row in range(row):for col in range(col):if ImageArray[row][col][0]<255:if x_top>row:x_top=row #获取最小x_topif x_left>col:x_left=col #获取最小x_leftif x_bottom<row:x_bottom=row #获取最大x_bottomif x_right<col:x_right=col #获取最大x_righti=0
for imageName in os.listdir(imagesDirectory):imagePath = os.path.join(imagesDirectory, imageName)image = Image.open(imagePath) # 打开tiff图像cropped = image.crop( (x_left ,x_top , x_right+10, x_bottom+10 )) # (left, upper, right, lower)i+=1;cropped.save("D:\PycharmProjects\pythonProject\indias\cutimages\{}.jpg".format(imageName,i))
3.效果
裁剪前:
裁剪后:
这篇关于Python批量裁剪图形外围空白区域的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!