對於這樣的圖片:
摳出其中的黑色區域,效果如下:
import cv2
import numpy as np
import matplotlib.pyplot as plt
import time
def findUnicomArea(img):
#先二值化
ret,threshold = cv2.threshold(img,128,255,cv2.THRESH_BINARY)
img_flag = np.zeros(threshold.shape,np.int8)
count = 0
findpoint = []
#首先遍歷圖像找到所有的聯通區
for x in range(threshold.shape[0]):
for y in range(threshold.shape[1]):
if(threshold[x][y] == 0 and img_flag[x][y] == 0):
#這裏表示已經找到了一個沒有標誌過的黑點,是一個新的聯通區
count += 1
img_flag[x][y] = count
findpoint.append((x,y))
while len(findpoint) > 0:
xx,yy = findpoint.pop()
if xx > 0 :#上面
if threshold[xx-1][yy] == 0 and img_flag[xx-1][yy] == 0:
findpoint.append((xx-1,yy))
img_flag[xx-1][yy] = count
if xx < img.shape[0]:#下面
if threshold[xx + 1][yy] == 0 and img_flag[xx + 1][yy] == 0:
findpoint.append((xx + 1, yy))
img_flag[xx+1][yy] = count
if yy > 0:#左面
if threshold[xx][yy-1] == 0 and img_flag[xx][yy-1] == 0:
findpoint.append((xx, yy-1))
img_flag[xx][yy-1] = count
if yy < img.shape[1]:#右面
if threshold[xx][yy+1] == 0 and img_flag[xx][yy+1] == 0:
findpoint.append((xx, yy+1))
img_flag[xx][yy+1] = count
#聯通區任然存在一張表中,需要將其分離
coutours = []
for num in range(1,count+1):
coutours.append([])
for x in range(img_flag.shape[0]):
for y in range(img_flag.shape[1]):
if img_flag[x][y] == num:
coutours[num-1].append([x,y,img_flag[x][y]])
desCoutous = np.empty(len(coutours),np.object)
for num in range(len(coutours)):
#將分離後的圖像提取出來。計算出聯通區所在的範圍
tmp = np.mat(coutours[num])
minX = np.min(tmp[:,0])
maxX = np.max(tmp[:,0])
minY = np.min(tmp[:,1])
maxY = np.max(tmp[:,1])
desCoutous[num] = img[minX:maxX,minY:maxY]
return desCoutous
#測試程序如下
img = cv2.imread("testpic/connected_test.png",0);
cost = time.time()
unicoms = findUnicomArea(img)
print("cost",time.time()-cost)
for i in range(len(unicoms)):
cv2.imshow("test"+str(i),unicoms[i])
cv2.waitKey(0)
目前只是實現了功能,效率還不高,還有很大的優化空間。
這個程序顯然有重複計算,第二次循環完全可以略去,可以合併到第一個循環中。另外,只需要遍歷1~shape[0]-1的空間就能找到所有的點,所以邊界的比較也可以省去,如此,程序如下:
def findUnicomArea(img):
#先二值化
ret,threshold = cv2.threshold(img,128,255,cv2.THRESH_BINARY)
img_flag = np.zeros(threshold.shape,np.int8)
count = 0
findpoint = []
coutours = []
#首先遍歷圖像找到所有的聯通區
for x in range(1,threshold.shape[0]-1):
for y in range(1,threshold.shape[1]-1):
if(threshold[x][y] == 0 and img_flag[x][y] == 0):
#這裏表示已經找到了一個沒有標誌過的黑點,是一個新的聯通區
count += 1
#新增一個聯通區存儲點
coutours.append([])
img_flag[x][y] = count
findpoint.append((x,y))
while len(findpoint) > 0:
xx,yy = findpoint.pop()
#上面
if threshold[xx-1][yy] == 0 and img_flag[xx-1][yy] == 0:
findpoint.append((xx-1,yy))
img_flag[xx-1][yy] = count
coutours[count - 1].append([xx, yy, img_flag[x][y]])
#下面
if threshold[xx + 1][yy] == 0 and img_flag[xx + 1][yy] == 0:
findpoint.append((xx + 1, yy))
img_flag[xx+1][yy] = count
coutours[count - 1].append([xx, yy, img_flag[x][y]])
#左面
if threshold[xx][yy-1] == 0 and img_flag[xx][yy-1] == 0:
findpoint.append((xx, yy-1))
img_flag[xx][yy-1] = count
coutours[count - 1].append([xx, yy, img_flag[x][y]])
#右面
if threshold[xx][yy+1] == 0 and img_flag[xx][yy+1] == 0:
findpoint.append((xx, yy+1))
img_flag[xx][yy+1] = count
coutours[count - 1].append([xx, yy, img_flag[x][y]])
desCoutous = np.empty(len(coutours),np.object)
for num in range(len(coutours)):
#將分離後的圖像提取出來。計算出聯通區所在的範圍
tmp = np.mat(coutours[num])
minX = np.min(tmp[:,0])
maxX = np.max(tmp[:,0])
minY = np.min(tmp[:,1])
maxY = np.max(tmp[:,1])
desCoutous[num] = img[minX:maxX,minY:maxY]
return desCoutous
這樣程序性能從1.3秒提升至0.8秒,程序有了顯著的提升。
如果我們只是摳出圖中的聯通區的話,只需要檢測邊界聯通區的外邊界就可以了,這樣效率能進一步提升。
def findUnicomBoundry(img):
#先二值化
ret,threshold = cv2.threshold(img,128,255,cv2.THRESH_BINARY)
img_flag = np.zeros(threshold.shape,np.int8)
count = 0
findpoint = []
coutours = []
desCoutous = []
existCoutous = []
#首先遍歷圖像找到所有的聯通區
for x in range(1,threshold.shape[0]-1):
for y in range(1,threshold.shape[1]-1):
if(threshold[x][y] == 0 and (threshold[x-1][y]==255 or threshold[x+1][y]==255 or threshold[x][y-1]==255 or threshold[x][y+1]==255) and img_flag[x][y] == 0):#是邊界的條件是中心點爲0,四周至少要有一個白點
#這裏表示已經找到了一個邊界點,並且是一個新的聯通區的邊界點
# 將分離後的圖像提取出來。計算出聯通區所在的範圍
if count > len(desCoutous):
desCoutous.append([])
tmp = np.mat(coutours[count - 1])
minX = np.min(tmp[:, 0])
maxX = np.max(tmp[:, 0])
minY = np.min(tmp[:, 1])
maxY = np.max(tmp[:, 1])
existCoutous.append([minX, maxX, minY, maxY])
desCoutous[count - 1] = img[minX:maxX, minY:maxY]
desCoutous[count-1] = np.mat(desCoutous[count-1])
isChildArea = False
for num in range(len(existCoutous)):
if x>existCoutous[num][0] and x < existCoutous[num][1] and y > existCoutous[num][2] and y < existCoutous[num][3] :
isChildArea = True
if not isChildArea:
count += 1
#新增一個聯通區的邊界存儲點
coutours.append([])
img_flag[x][y] = count
findpoint.append((x,y))
while len(findpoint) > 0:
#xx,yy肯定是一個邊界點了,現在尋找下一個邊界點
xx,yy = findpoint.pop()
#上面
if threshold[xx-1][yy] == 0 and (threshold[xx-2][yy]==255 or threshold[xx-1][yy-1]==255 or threshold[xx-1][yy+1]==255) and img_flag[xx-1][yy] == 0:
findpoint.append((xx-1,yy))
img_flag[xx-1][yy] = count
coutours[count - 1].append([xx-1, yy, img_flag[xx-1][yy]])
#下面
if threshold[xx + 1][yy] == 0 and (threshold[xx+1][yy]==255 or threshold[xx+1][yy-1]==255 or threshold[xx+1][yy+1]==255) and img_flag[xx + 1][yy] == 0:
findpoint.append((xx + 1, yy))
img_flag[xx+1][yy] = count
coutours[count - 1].append([xx+1, yy, img_flag[xx][yy]])
#左面
if threshold[xx][yy-1] == 0 and (threshold[xx][yy-2]==255 or threshold[xx-1][yy-1]==255 or threshold[xx+1][yy-1]==255) and img_flag[xx][yy-1] == 0:
findpoint.append((xx, yy-1))
img_flag[xx][yy-1] = count
coutours[count - 1].append([xx, yy-1, img_flag[xx][yy-1]])
#右面
if threshold[xx][yy+1] == 0 and (threshold[xx][yy+2]==255 or threshold[xx-1][yy+1]==255 or threshold[xx+1][yy+1]==255) and img_flag[xx][yy+1] == 0:
findpoint.append((xx, yy+1))
img_flag[xx][yy+1] = count
coutours[count - 1].append([xx, yy+1, img_flag[xx][yy+1]])
#左上
if threshold[xx-1][yy-1] == 0 and (threshold[xx-2][yy-1]==255 or threshold[xx][yy]==255 or threshold[xx-1][yy-2]==255 or threshold[xx-1][yy]==255) and img_flag[xx-1][yy-1] == 0:
findpoint.append((xx-1, yy-1))
img_flag[xx-1][yy-1] = count
coutours[count - 1].append([xx-1, yy-1, img_flag[xx-1][yy-1]])
#右上
if threshold[xx-1][yy+1] == 0 and (threshold[xx-2][yy+1]==255 or threshold[xx][yy+1]==255 or threshold[xx-1][yy]==255 or threshold[xx-1][yy+1]==255) and img_flag[xx-1][yy+1] == 0:
findpoint.append((xx-1, yy+1))
img_flag[xx-1][yy+1] = count
coutours[count - 1].append([xx-1, yy+1, img_flag[xx-1][yy+1]])
#左下
if threshold[xx+1][yy-1] == 0 and (threshold[xx][yy-1]==255 or threshold[xx+2][yy-1]==255 or threshold[xx+1][yy-2]==255 or threshold[xx+1][yy]==255) and img_flag[xx+1][yy-1] == 0:
findpoint.append((xx+1, yy-1))
img_flag[xx+1][yy-1] = count
coutours[count - 1].append([xx+1, yy-1, img_flag[xx+1][yy-1]])
#右下
if threshold[xx+1][yy+1] == 0 and (threshold[xx][yy+1]==255 or threshold[xx+2][yy+1]==255 or threshold[xx+1][yy]==255 or threshold[xx+1][yy+2]==255) and img_flag[xx+1][yy+1] == 0:
findpoint.append((xx+1, yy+1))
img_flag[xx+1][yy+1] = count
coutours[count - 1].append([xx+1, yy+1, img_flag[xx+1][yy+1]])
return desCoutous
程序的運行時間縮小到0.6秒
c++基於opencv的實現:
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
Mat findContinousArea(Mat& img)
{
int rows = img.rows;
int cols = img.cols;
Mat coutinous = Mat(img.rows,img.cols,img.type(),Scalar(0));
queue<Point> tmp;
int cCount = 0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(img.at<char>(i,j)==0 && coutinous.at<char>(i,j)==0){
cCount+=30;
tmp.push(Point(i,j));
coutinous.at<char>(i,j) = cCount;
while(!tmp.empty()){
Point p = tmp.front();
tmp.pop();
if(p.x>0 && img.at<char>(p.x-1,p.y)==0 && coutinous.at<char>(p.x-1,p.y)==0){
tmp.push(Point(p.x-1,p.y));
coutinous.at<char>(p.x-1,p.y) = cCount;
}
if(p.x<rows && img.at<char>(p.x+1,p.y)==0 && coutinous.at<char>(p.x+1,p.y)==0){
tmp.push(Point(p.x+1,p.y));
coutinous.at<char>(p.x+1,p.y) = cCount;
}
if(p.y>0 && img.at<char>(p.x,p.y-1)==0 && coutinous.at<char>(p.x,p.y-1)==0){
tmp.push(Point(p.x,p.y-1));
coutinous.at<char>(p.x,p.y-1) = cCount;
}
if(p.y<cols && img.at<char>(p.x,p.y+1)==0 && coutinous.at<char>(p.x,p.y+1)==0){
tmp.push(Point(p.x,p.y+1));
coutinous.at<char>(p.x,p.y+1) = cCount;
}
}
}
}
}
return coutinous;
}
int main() {
Mat frame = imread("/Users/jinweiliu/Pictures/coutinous.png",0);
int rows = frame.rows;
int cols = frame.cols;
//二值化
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if((frame.at<char>(i,j)&0xff)<128){
frame.at<char>(i,j) = 0;
}else{
frame.at<char>(i,j) = (char)255;
}
}
}
TickMeter tm;
tm.start();
Mat coutinous = findContinousArea(frame);
tm.stop();
cout<<tm.getTimeMilli()<<endl;
imshow("test",coutinous);
waitKey();
return 0;
}
原圖:
結果如下:
注意,結果是用不同的數字表示不同的聯通區的,比如,第一個聯通區全部標誌爲30,第二個全部標誌爲60,以此類推。之所以是30,60,90等而不是1,2,3等是因爲顯示出來看着比較明顯。這裏只是把不同的聯通區標示出來,並沒有做切割之類的,僅供參考。最後,c++的這段代碼耗時只有3ms,性能還是挺不錯的。