t = img[row-1][col-1]+ img[row-1][col]+ img[row-1][col+1]+ img[row][col-1]+ img[row][col+1]+ img[row+1][col-1]+ img[row+1][col]+ img[row+1][col+1]if t >=2and t <=6:flag +=1
#條件2
t =0
lis =[img[row-1][col],img[row-1][col+1],img[row][col+1],img[row+1][col+1],img[row+1][col],img[row+1][col-1],img[row][col-1],img[row-1][col-1],img[row-1][col]]for i inrange(len(lis)-1):if lis[i]==0and lis[i+1]==1:t +=1if t ==1:flag +=1
對(duì)于條件三和四,就不需要贅述了。 下面是細(xì)化函數(shù)的完整形式:
defxihua(img):h,w = img.shapedst = img.copy()for row inrange(h-1):for col inrange(w-1):if img[row][col]==1:flag =0#條件1t = img[row-1][col-1]+ img[row-1][col]+ img[row-1][col+1]+ img[row][col-1]+ img[row][col+1]+ img[row+1][col-1]+ img[row+1][col]+ img[row+1][col+1]if t >=2and t <=6:flag +=1#條件2t =0lis =[img[row-1][col],img[row-1][col+1],img[row][col+1],img[row+1][col+1],img[row+1][col],img[row+1][col-1],img[row][col-1],img[row-1][col-1],img[row-1][col]]for i inrange(len(lis)-1):if lis[i]==0and lis[i+1]==1:t +=1if t ==1:flag +=1#條件3s = img[row-1][col]* img[row][col+1]* img[row+1][col]if s ==0:flag +=1#條件4s = img[row][col+1]* img[row+1][col]* img[row][col-1]if s ==0:flag +=1if flag ==4:dst[row][col]=0temp = dst.copy()for row inrange(h-1):for col inrange(w-1):if dst[row][col]==1:flag =0# 條件1t = dst[row -1][col -1]+ dst[row -1][col]+ dst[row -1][col +1]+ dst[row][col -1]+ dst[row][col +1]+ dst[row +1][col -1]+ dst[row +1][col]+ dst[row +1][col +1]if t >=2and t <=6:flag +=1# 條件2t =0lis =[dst[row -1][col], dst[row -1][col +1], dst[row][col +1], dst[row +1][col +1],dst[row +1][col], dst[row +1][col -1], dst[row][col -1], dst[row -1][col -1],dst[row -1][col]]for i inrange(len(lis)-1):if lis[i]==0and lis[i +1]==1:t +=1if t ==1:flag +=1# 條件3s = dst[row -1][col]* dst[row][col +1]* dst[row +1][col]if s ==0:flag +=1# 條件4s = dst[row][col +1]* dst[row +1][col]* dst[row][col -1]if s ==0:flag +=1if flag ==4:temp[row][col]=0return temp
在最后我對(duì)添加優(yōu)化和未優(yōu)化的時(shí)間做了一下對(duì)比:
t = time.time()
xihua_low(imgb)print('未優(yōu)化:',time.time()-t)t = time.time()
xihua(imgb)print('優(yōu)化后:',time.time()-t)