1. 程式人生 > 程式設計 >OpenCV Python實現影象指定區域裁剪

OpenCV Python實現影象指定區域裁剪

在工作中。在做資料集時,需要對圖片進行處理,照相的圖片我們只需要特定的部分,所以就想到裁剪一種所需的部分。當然若是圖片有規律可循則使用opencv對其進行膨脹腐蝕等操作。這樣更精準一些。

一、指定影象位置的裁剪處理

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      #獲取影象形狀:返回【行數值,列數值】列表
      sz1 = sp[0]         #影象的高度(行 範圍)
      sz2 = sp[1]         #影象的寬度(列 範圍)
      #sz3 = sp[2]        #畫素值由【RGB】三原色組成
      
      #你想對檔案的操作
      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)

二、批量處理—指定影象位置的裁剪

我這個是用來擷取發票的印章區域,用於影象分割(公司的資料集保密)
各位可以用自己的增值發票裁剪。適當的更改擷取區域

"""
處理資料集 和 標籤資料集的程式碼:(主要是對原始資料集裁剪)
  處理方式:分別處理
  注意修改 輸入 輸出目錄 和 生成的檔名
  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:             # 正常發票
      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:                    # 捲簾發票
      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)

三、多程序(加快處理)

#coding: utf-8
"""
採用多程序加快處理。添加了在讀取圖片時捕獲異常,OpenCV對大解析度或者tif格式圖片支援不好
處理資料集 和 標籤資料集的程式碼:(主要是對原始資料集裁剪)
  處理方式:分別處理
  注意修改 輸入 輸出目錄 和 生成的檔名
  output_dir = "./label_temp"
  input_dir = "./label"
"""
import multiprocessing
import cv2
import os
import time


def get_img(input_dir):
  img_paths = []
  for (path,output_dir):
  imread_failed = []
  try:
    img = cv2.imread(img_paths)
    height,weight = img.shape[:2]
    if (1.0 * height / weight) < 1.3:    # 正常發票
      cropImg = img[50:200,700:1500]   # 裁剪【y1,x2】
      cv2.imwrite(output_dir + '/' + img_paths.split('/')[-1],cropImg)
    else:                  # 捲簾發票
      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,b)) # 進度條(可用tqdm)
  pool.close()            # 呼叫join之前,先呼叫close函式,否則會出錯。
  pool.join()             # join函式等待所有子程序結束
  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)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。