前言:今天是團隊的集訓日,自己選了HAAR特徵的課題來研究,參考了很多博文,都沒給出代碼實現,遂貢獻下自己的代碼吧。關於HAAR特徵網上已經有很多博文解釋的很好了,我肯定是沒他們寫得好啦,所以我會在下面給出我看到最好的文章。而且最近在看機器學習的內容,博客更新的有點慢。
推薦參考博客連接:http://blog.csdn.net/jing_xin/article/details/17383161
關於積分圖:圖一是參考博客裏的,圖二是自己畫的,可以幫助你們理解下我的代碼
圖一
圖二
關於代碼:我只實現了橫向的比較,就是下圖兩矩形類右邊的那個,其他情況類似
import cv2 as cv
#積分圖
def intergralMat(input = [],weigth = 0 ,height = 0):
output = []
output.clear()
columnSum = [0 for i in range(weigth)]
for i in range(height):
output.append([0 for x in range(weigth)])
for j in range(weigth):
if j == 0:
columnSum[j] = int(input[i][j])
else:
columnSum[j] = columnSum[j-1] + int(input[i][j])
if i == 0:
output[i][j] = columnSum[j]
else:
output[i][j] = output[i-1][j] + columnSum[j]
return output
#哈爾圖,默認size=1,deep=2
def myHaar(interM = [],weigth = 0,height = 0,size = 1,deep = 2):
dst = []
for i in range(height - deep + 1):
dst.append([0 for x in range(weigth - size)])
for j in range(weigth - 2*size +1):
whithe,black = (0,0)
if j == 0 and i==0:
whithe = int(interM[i+deep-1][j+size-1])
elif i!=0 and j==0:
whithe = int(interM[i + deep - 1][j + size - 1]) - int(interM[i - 1][j + size -1])
elif i == 0 and j != 0:
whithe = int(interM[i+deep-1][j+size-1]) - int(interM[i+1][j-1])
else:
whithe = int(interM[i+deep-1][j+size-1]) + int(interM[i-1][j-1]) - int(interM[i+1][j-1]) - int(interM[i -1][j+ size -1])
_i = i
_j = j + size
if _i == 0:
black = int(interM[_i+deep-1][_j+size-1]) - int(interM[_i+1][_j-1])
else:
black = int(interM[_i+deep-1][_j+size-1]) + int(interM[_i-1][_j-1]) - int(interM[_i+1][_j-1]) - int(interM[_i - 1][_j+ size -1])
dst[i][j] = black - whithe
return dst
def main():
src = cv.imread('1.jpg')
tmp = src.copy()
# 分裂出三通道。這裏只取b通道來進行分析,實際應該是分析三個通道,再合併
b, g, r = cv.split(src)
# 用於得到圖像的寬高
_w = len(b[0])
_h = len(b)
in_b = intergralMat(b, _w, _h)
Haar_b = myHaar(in_b, _w, _h)
dst = []
for x in range(len(Haar_b)):
dst.append([])
for y in range(len(Haar_b[0])):
if Haar_b[x][y] > 0:
dst[x].append(255)
else:
dst[x].append(0)
for x in range(len(dst)):
for y in range(len(dst[0])):
f = dst[x][y]
tmp[x, y] = [f, f, f]
cv.imshow('src', src)
cv.imshow('test', tmp)
cv.waitKey()
main()
效果圖:由於只實現了橫向的比較,所以只有豎直的線可以提取特徵