Python OpenCV圖像指定區(qū)域裁剪的實(shí)現(xiàn)
在工作中。在做數(shù)據(jù)集時(shí),需要對(duì)圖片進(jìn)行處理,照相的圖片我們只需要特定的部分,所以就想到裁剪一種所需的部分。當(dāng)然若是圖片有規(guī)律可循則使用opencv對(duì)其進(jìn)行膨脹腐蝕等操作。這樣更精準(zhǔn)一些。
一、指定圖像位置的裁剪處理
import os import cv2 # 遍歷指定目錄,顯示目錄下的所有文件名 def CropImage4File(filepath,destpath): pathDir = os.listdir(filepath) # 列出文件路徑中的所有路徑或文件 for allDir in pathDir: child = os.path.join(filepath, allDir) dest = os.path.join(destpath,allDir) if os.path.isfile(child): image = cv2.imread(child) sp = image.shape #獲取圖像形狀:返回【行數(shù)值,列數(shù)值】列表 sz1 = sp[0] #圖像的高度(行 范圍) sz2 = sp[1] #圖像的寬度(列 范圍) #sz3 = sp[2] #像素值由【RGB】三原色組成 #你想對(duì)文件的操作 a=int(sz1/2-64) # x start b=int(sz1/2+64) # x end c=int(sz2/2-64) # y start d=int(sz2/2+64) # y end cropImg = image[a:b,c:d] #裁剪圖像 cv2.imwrite(dest,cropImg) #寫入圖像路徑 if __name__ == '__main__': filepath ='F:\\\maomi' #源圖像 destpath='F:\\maomi_resize' # resized images saved here CropImage4File(filepath,destpath)
二、批量處理—指定圖像位置的裁剪
我這個(gè)是用來截取發(fā)票的印章區(qū)域,用于圖像分割(公司的數(shù)據(jù)集保密)
各位可以用自己的增值發(fā)票裁剪。適當(dāng)?shù)母慕厝^(qū)域
""" 處理數(shù)據(jù)集 和 標(biāo)簽數(shù)據(jù)集的代碼:(主要是對(duì)原始數(shù)據(jù)集裁剪) 處理方式:分別處理 注意修改 輸入 輸出目錄 和 生成的文件名 output_dir = "./label_temp" input_dir = "./label" """ import cv2 import os import sys import time def get_img(input_dir): img_paths = [] for (path,dirname,filenames) in os.walk(input_dir): for filename in filenames: img_paths.append(path+'/'+filename) print("img_paths:",img_paths) return img_paths def cut_img(img_paths,output_dir): scale = len(img_paths) for i,img_path in enumerate(img_paths): a = "#"* int(i/1000) b = "."*(int(scale/1000)-int(i/1000)) c = (i/scale)*100 time.sleep(0.2) print('正在處理圖像: %s' % img_path.split('/')[-1]) img = cv2.imread(img_path) weight = img.shape[1] if weight>1600: # 正常發(fā)票 cropImg = img[50:200, 700:1500] # 裁剪【y1,y2:x1,x2】 #cropImg = cv2.resize(cropImg, None, fx=0.5, fy=0.5, #interpolation=cv2.INTER_CUBIC) #縮小圖像 cv2.imwrite(output_dir + '/' + img_path.split('/')[-1], cropImg) else: # 卷簾發(fā)票 cropImg_01 = img[30:150, 50:600] cv2.imwrite(output_dir + '/'+img_path.split('/')[-1], cropImg_01) print('{:^3.3f}%[{}>>{}]'.format(c,a,b)) if __name__ == '__main__': output_dir = "../img_cut" # 保存截取的圖像目錄 input_dir = "../img" # 讀取圖片目錄表 img_paths = get_img(input_dir) print('圖片獲取完成 。。。!') cut_img(img_paths,output_dir)
三、多進(jìn)程(加快處理)
#coding: utf-8 """ 采用多進(jìn)程加快處理。添加了在讀取圖片時(shí)捕獲異常,OpenCV對(duì)大分辨率或者tif格式圖片支持不好 處理數(shù)據(jù)集 和 標(biāo)簽數(shù)據(jù)集的代碼:(主要是對(duì)原始數(shù)據(jù)集裁剪) 處理方式:分別處理 注意修改 輸入 輸出目錄 和 生成的文件名 output_dir = "./label_temp" input_dir = "./label" """ import multiprocessing import cv2 import os import time def get_img(input_dir): img_paths = [] for (path,dirname,filenames) in os.walk(input_dir): for filename in filenames: img_paths.append(path+'/'+filename) print("img_paths:",img_paths) return img_paths def cut_img(img_paths,output_dir): imread_failed = [] try: img = cv2.imread(img_paths) height, weight = img.shape[:2] if (1.0 * height / weight) < 1.3: # 正常發(fā)票 cropImg = img[50:200, 700:1500] # 裁剪【y1,y2:x1,x2】 cv2.imwrite(output_dir + '/' + img_paths.split('/')[-1], cropImg) else: # 卷簾發(fā)票 cropImg_01 = img[30:150, 50:600] cv2.imwrite(output_dir + '/' + img_paths.split('/')[-1], cropImg_01) except: imread_failed.append(img_paths) return imread_failed def main(input_dir,output_dir): img_paths = get_img(input_dir) scale = len(img_paths) results = [] pool = multiprocessing.Pool(processes = 4) for i,img_path in enumerate(img_paths): a = "#"* int(i/10) b = "."*(int(scale/10)-int(i/10)) c = (i/scale)*100 results.append(pool.apply_async(cut_img, (img_path,output_dir ))) print('{:^3.3f}%[{}>>{}]'.format(c, a, b)) # 進(jìn)度條(可用tqdm) pool.close() # 調(diào)用join之前,先調(diào)用close函數(shù),否則會(huì)出錯(cuò)。 pool.join() # join函數(shù)等待所有子進(jìn)程結(jié)束 for result in results: print('image read failed!:', result.get()) print ("All done.") if __name__ == "__main__": input_dir = "D:/image_person" # 讀取圖片目錄表 output_dir = "D:/image_person_02" # 保存截取的圖像目錄 main(input_dir, output_dir)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python pyautogui手動(dòng)活動(dòng)(模擬鼠標(biāo)鍵盤)自動(dòng)化庫(kù)使用
這篇文章主要為大家介紹了python pyautogui手動(dòng)活動(dòng)(模擬鼠標(biāo)鍵盤)自動(dòng)化庫(kù)使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01pytest官方文檔解讀Fixture?errors拋錯(cuò)解決
這篇文章主要為大家介紹了pytest官方文檔解讀Fixture?errors拋錯(cuò)后的解決方案,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06Python實(shí)現(xiàn)自動(dòng)清理電腦垃圾文件詳解
經(jīng)常存在在我們的電腦中的垃圾文件主要是指系統(tǒng)在運(yùn)行過程中產(chǎn)生的tmp臨時(shí)文件、日志文件、臨時(shí)備份文件等。本文將利用Python實(shí)現(xiàn)自動(dòng)清理這些垃圾文件,需要的可以參考一下2022-03-03解決python3 Pycharm上連接數(shù)據(jù)庫(kù)時(shí)報(bào)錯(cuò)的問題
今天小編就為大家分享一篇解決python3 Pycharm上連接數(shù)據(jù)庫(kù)時(shí)報(bào)錯(cuò)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12Python使用matplotlib繪圖無法顯示中文問題的解決方法
這篇文章主要介紹了Python使用matplotlib繪圖無法顯示中文問題的解決方法,結(jié)合具體實(shí)例形式分析了Python使用matplotlib繪圖時(shí)出現(xiàn)中文亂碼的原因與相關(guān)解決方法,需要的朋友可以參考下2018-03-03PyCharm2019.3永久激活破解詳細(xì)圖文教程,親測(cè)可用(不定期更新)
這篇文章主要介紹了PyCharm2019.3最新激活碼(注冊(cè)碼)破解永久版詳細(xì)圖文教程的相關(guān)資料,親測(cè)可用,需要的朋友可以參考下2020-10-10Python異常處理機(jī)制結(jié)構(gòu)實(shí)例解析
這篇文章主要介紹了Python異常處理機(jī)制結(jié)構(gòu)實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07