畢業設計的方向是變化檢測,但是在兩張圖片都分類進行對比以後,總會有一些小的誤差點,由於是編寫了一整套程序,需要把結果呈現在網頁上,所以爲了美觀,腐蝕掉一些小的分類誤差點。代碼是將小誤差塊的面積小於總面積的0.1,作爲測試。
import numpy as np
import cv2
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y
def getGrayDiff(img, currentPoint, tmpPoint):
return abs(int(img[currentPoint.x, currentPoint.y]) - int(img[tmpPoint.x, tmpPoint.y]))
def selectConnects(p):
if p != 0:
connects = [Point(-1, -1), Point(0, -1), Point(1, -1), Point(1, 0), Point(1, 1), \
Point(0, 1), Point(-1, 1), Point(-1, 0)]
else:
connects = [Point(0, -1), Point(1, 0), Point(0, 1), Point(-1, 0)]
return connects
def regionGrow(img, seeds, thresh, p=1):
area = 0
height = img.shape[0]
weight = img.shape[1]
seedMark = np.zeros(img.shape)
seedList = []
for seed in seeds:
seedList.append(seed)
label = 200
connects = selectConnects(p)
while (len(seedList) > 0):
area=area+1
currentPoint = seedList.pop(0)
seedMark[currentPoint.x, currentPoint.y] = label
#print(seedMark[currentPoint.x, currentPoint.y])
for i in range(8):
tmpX = currentPoint.x + connects[i].x
tmpY = currentPoint.y + connects[i].y
if tmpX < 0 or tmpY < 0 or tmpX >= height or tmpY >= weight:
continue
grayDiff = getGrayDiff(img, currentPoint, Point(tmpX, tmpY))
if grayDiff < thresh and seedMark[tmpX, tmpY] == 0:
seedMark[tmpX, tmpY] = label
seedList.append(Point(tmpX, tmpY))
print(area)
print(seedMark)
if area<(height*weight/10):
for i in range(0, height):
for j in range(0, weight):
if seedMark[i][j] == 200:
img[i][j] = 255
#print(1)
if area>(height*weight/10):
for i in range(0, height):
for j in range(0, weight):
if seedMark[i][j] == 200:
img[i][j] = 1
#print(1)
return img
#def convert():
img = cv2.imread('test.png', 0)
height = img.shape[0]
weight = img.shape[1]
for i in range(0, height):
for j in range(0, weight):
if(img[i][j]==0):
print(i,j)
seeds = [Point(i, j)]
binaryImg = regionGrow(img, seeds, 10)
cv2.imshow(' ', binaryImg)
cv2.waitKey(0)
處理後: