日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Python批量裁剪圖形外圍空白區(qū)域_python

作者:空中旋轉(zhuǎn)籃球 ? 更新時(shí)間: 2022-06-12 編程語(yǔ)言

一、基本描述

批量裁剪掉圖片的背景區(qū)域,一般是白色背景,從而減少背景值的干擾和減少存儲(chǔ)空間。

通過(guò)檢索所有圖片的最小裁剪區(qū)域坐標(biāo)值,然后再對(duì)圖片進(jìn)行裁剪。文中圖都是經(jīng)過(guò)標(biāo)準(zhǔn)化處理的,核心圖片內(nèi)容尺度都一致,所以采用該種辦法,如果有很多不同大小的圖片,即圖片中的內(nèi)容區(qū)域大小形狀不一樣,則一張一張的檢索該圖的背景區(qū)域,然后進(jìn)行裁剪。即一張一張的檢索裁剪區(qū)域并進(jìn)行裁剪。

二、實(shí)現(xiàn)代碼

對(duì)原文中的代碼進(jìn)行修改,一張一張的檢索每張圖的裁剪區(qū)域坐標(biāo),然后裁剪。

代碼如下:

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) ?# 打開(kāi)tiff圖像
? ? ImageArray = np.array(image)
? ? row = ImageArray.shape[0]
? ? col = ImageArray.shape[1]
? ? print(row,col)
? ? # 先計(jì)算所有圖片的裁剪范圍,然后再統(tǒng)一裁剪并輸出圖片
? ? x_left = row
? ? x_top = col
? ? x_right = 0
? ? x_bottom = 0
? ? # 上下左右范圍
? ? """
? ? Image.crop(left, up, right, below)
? ? left:與左邊界的距離
? ? up:與上邊界的距離
? ? right:還是與左邊界的距離
? ? below:還是與上邊界的距離
? ? 簡(jiǎn)而言之就是,左上右下。
? ? """
? ? 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: #外框有個(gè)黑色邊框,增加條件判斷
? ? ? ? ? ? ? ? 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) ?# 打開(kāi)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!")

三、效果

原圖顯示:

?裁剪結(jié)果顯示:

?原文效果:

原文鏈接:https://soderayer.blog.csdn.net/article/details/123467979

欄目分類(lèi)
最近更新