利用python,opencv來去除圖像的黑邊(上下左右都有黑邊的)
"""author:youngkun;date:20180608;function:裁剪照片的黑邊""" import cv2 import os import datetime def change_size(read_file): image=cv2.imread(read_file,1) #讀取圖片 image_name應該是變量 img = cv2.medianBlur(image,5) #中值濾波,去除黑色邊際中可能含有的噪聲干擾 b=cv2.threshold(img,15,255,cv2.THRESH_BINARY) #調整裁剪效果 binary_image=b[1] #二值圖--具備三通道 binary_image=cv2.cvtColor(binary_image,cv2.COLOR_BGR2GRAY) print(binary_image.shape) #改成單通道 x=binary_image.shape[0] print("高度x=",x) y=binary_image.shape[1] print("寬度y=",y) edges_x=[] edges_y=[] for i in range(x): for j in range(y): if binary_image[i][j]==255: edges_x.append(i) edges_y.append(j) left=min(edges_x) #左邊界 right=max(edges_x) #右邊界 width=right-left #寬度 bottom=min(edges_y) #底部 top=max(edges_y) #頂部 height=top-bottom #高度 pre1_picture=image[left:left+width,bottom:bottom+height] #圖片截取 return pre1_picture #返回圖片數據 source_path="./training_data/1/" #圖片來源路徑 save_path="./out/" #圖片修改後的保存路徑 if not os.path.exists(save_path): os.mkdir(save_path) file_names=os.listdir(source_path) starttime=datetime.datetime.now() for i in range(len(file_names)): x=change_size(source_path + file_names[i]) #獲得文件名 cv2.imwrite(save_path+file_names[i],x) print("裁剪:",file_names[i]) print("裁剪數量:",i) while(i==2600): break print("裁剪完畢") endtime = datetime.datetime.now()#記錄結束時間 endtime = (endtime-starttime).seconds print("裁剪總用時",endtime)
這種方法只能裁剪出矩形的圖像,具備必定的侷限性,利用了opencv的二值化來分離出前景和背景html
完整代碼請見
https://github.com/younkun/image_image-processing.gitpython