1. 程式人生 > >簡單圖像分割

簡單圖像分割

觀察 圖像處理 sha gray port 不同 ray 統計 根據

對於給定的一張圖像,可能邊緣或者無效信息較多,所以需要將圖像主要內容分離出來,這裏對於特定的圖片給出一個小例子。

技術分享 技術分享

對於此圖(左)來說,兩邊的無效信息較多,字母主要集中在中間部分。對於少量圖而言可以手動去掉兩邊的空白成為右圖。可是對於成千上萬張圖片需要一種特定的方法。觀察到數字主要集中在中間並且為大量黑色像素點,兩邊主要是白色像素點,所以考慮將圖片先轉為灰度,然後統計其水平的像素值分布,根據一定的閾值將中間部分區分出來。

import cv2
import os
import numpy as np
import matplotlib.pyplot as plt

imgs
= os.listdir(r"D:/ws_yzm/yzm/valid_data") imgNum = len(imgs) img =[[] for i in range(imgNum)] for i in range(0, imgNum): img[i] = cv2.imread(yzm/valid_data/+imgs[i]) img[i] = cv2.cvtColor(img[i], cv2.COLOR_BGR2GRAY) # 將讀入的圖像先轉為灰度 img_wrong = cv2.imread(D:/ws_yzm/yzm/valid_data/+‘00264.png) # 取其中的一張圖片進行操作顯示 img_wrong
= cv2.cvtColor(img_wrong, cv2.COLOR_BGR2GRAY) y_axis = np.mean(img_wrong, axis=0) # 對圖片的水平方向求象素均值 b = y_axis.shape[0] y_t = np.zeros(b) plt.subplot(221) plt.plot(y_axis) # 畫出水平像素分布 for i in range(0, b): if y_axis[i] <= 200: # 設定閾值為200,即水平像素均值<200則令y_t為1,否則為0 y_t[i] = 1 plt.subplot(222) plt.plot(y_t) # 將y_t畫出 y_diff
= np.diff(y_t) # 對y_t求差分 plt.subplot(223) plt.plot(y_diff) # 將y_diff畫出 q = np.where(y_diff != 0) # 將y_diff!=0的點坐標找出 q = list(q[0]) q.append(b) axis = [] # 存放找到的區間坐標 for l in range(1, q.__len__()): if (((q[l] - q[l - 1]) > 25) & (y_t[q[l] - 1] == 1)): axis.extend([q[l - 1], q[l]]) # 將區間寬度>25,並且屬於值為1的區間坐標找出 if axis and np.max(axis) >= 200: # 如果找出的坐標非空,且其最大值>200則在axis裏找出最大和最小坐標值 x_min = np.min(axis) x_max = np.max(axis) else: # 如果找出的坐標為空,則取圖像最右端0為左邊界,q的最小值為有邊界 x_min = 0 x_max = np.min(q)
plt.subplot(224) img_new = img_wrong[:, x_min:x_max] # 將處理後的圖像畫出 #cv2.imwrite(‘yzm/new_valid_data/‘ + imgs[j], img_new) plt.imshow(img_wrong[:, x_min:x_max], cmap=gray)

技術分享

由結果圖看到分割較好。條件設置主要是針對0-1二值化的結果,由於數字分布不均勻,不同的圖0-1化結果有很大出入,所以需要根據一定的判斷將x_min和x_max求出。上述代碼在幾千張的圖像處理中基本都能分割正確。

簡單圖像分割