Python批量裁剪圖形外圍空白區(qū)域
一、基本描述
批量裁剪掉圖片的背景區(qū)域,一般是白色背景,從而減少背景值的干擾和減少存儲空間。
通過檢索所有圖片的最小裁剪區(qū)域坐標值,然后再對圖片進行裁剪。文中圖都是經過標準化處理的,核心圖片內容尺度都一致,所以采用該種辦法,如果有很多不同大小的圖片,即圖片中的內容區(qū)域大小形狀不一樣,則一張一張的檢索該圖的背景區(qū)域,然后進行裁剪。即一張一張的檢索裁剪區(qū)域并進行裁剪。
二、實現(xiàn)代碼
對原文中的代碼進行修改,一張一張的檢索每張圖的裁剪區(qū)域坐標,然后裁剪。
代碼如下:
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) ? ? # 先計算所有圖片的裁剪范圍,然后再統(tǒng)一裁剪并輸出圖片 ? ? 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批量裁剪圖形外圍空白區(qū)域的文章就介紹到這了,更多相關Python批量裁剪圖形內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用python讀寫txt和json(jsonl)大文件的方法步驟
在Python中讀取txt和json(jsonl)大文件并保存到字典是一項非常常見的操作,這篇文章主要給大家介紹了關于使用python讀寫txt和json(jsonl)大文件的方法步驟,需要的朋友可以參考下2023-12-12python使用clear方法清除字典內全部數(shù)據(jù)實例
這篇文章主要介紹了python使用clear方法清除字典內全部數(shù)據(jù),實例分析了Python中clear方法清空字典內數(shù)據(jù)的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07