網站首頁 編程語言 正文
一、基本描述
批量裁剪掉圖片的背景區域,一般是白色背景,從而減少背景值的干擾和減少存儲空間。
通過檢索所有圖片的最小裁剪區域坐標值,然后再對圖片進行裁剪。文中圖都是經過標準化處理的,核心圖片內容尺度都一致,所以采用該種辦法,如果有很多不同大小的圖片,即圖片中的內容區域大小形狀不一樣,則一張一張的檢索該圖的背景區域,然后進行裁剪。即一張一張的檢索裁剪區域并進行裁剪。
二、實現代碼
對原文中的代碼進行修改,一張一張的檢索每張圖的裁剪區域坐標,然后裁剪。
代碼如下:
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!")
三、效果
原圖顯示:
?裁剪結果顯示:
?原文效果:
原文鏈接:https://soderayer.blog.csdn.net/article/details/123467979
相關推薦
- 2023-03-28 Pytorch實現將label變成one?hot編碼的兩種方式_python
- 2022-07-09 Python?對數字的千分位處理方式_python
- 2022-07-02 Pandas?如何處理DataFrame中的inf值_python
- 2024-01-11 String數組轉List的三種方式
- 2022-07-18 C語言簡明講解歸并排序的應用_C 語言
- 2022-12-26 使用python如何對圖片進行壓縮_python
- 2022-06-02 Python?推導式、生成器與切片問題解決思路_python
- 2022-12-25 Flutter開發通用頁面Loading組件示例詳解_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支