提取影象島嶼演算法
阿新 • • 發佈:2019-02-10
利用傳統影象演算法提取島嶼
1、建立掩模(B>R+G)
2、利用mask將其分割
3、閾值化(自己根據經驗)
4、填洞
5、膨脹
6、尋找最大面積輪廓
7、最終的mask和原圖邏輯與運算
效果圖如下:
# -*- coding: utf-8 -*-
import gdal
import numpy as np
import cv2
def maxminImg(im):
im=(im-np.min(im))/(np.max(im)-np.min(im))
return np.uint8(im*255)
def getBGRim():
gdal.AllRegister( )
dataset=gdal.Open(r"C:\Users\Y\Desktop\1.tif")
b=dataset.GetRasterBand(1)
b=b.ReadAsArray(0,0,dataset.RasterXSize,dataset.RasterYSize)
g=dataset.GetRasterBand(2)
g=g.ReadAsArray(0,0,dataset.RasterXSize,dataset.RasterYSize)
r=dataset.GetRasterBand(3)
r=r.ReadAsArray(0,0,dataset. RasterXSize,dataset.RasterYSize)
b,g,r=maxminImg(b),maxminImg(g),maxminImg(r)
return cv2.merge((b,g,r)),(b,g,r)
def fillhole(thresh):
h,w=thresh.shape
mask=np.zeros((h+2,w+2),np.uint8)
holes=cv2.floodFill(thresh.copy(),mask,(0,0),255)
s=~holes[1]
return s|thresh
if __name__== "__main__":
imout,t=getBGRim()
b,g,r=t
mask=b>(g+r)
mask=np.uint8(mask*255)
im2=imout&mask[:,:,np.newaxis]
im3=cv2.cvtColor(im2,cv2.COLOR_BGR2GRAY)
_,im4=cv2.threshold(im3,160,255,cv2.THRESH_BINARY)
kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
im5=cv2.dilate(im4,kernel,iterations=7)
fill=fillhole(im5)
_,cnts,_=cv2.findContours(fill,0,1)
cnt_max=sorted(cnts,key=lambda x:cv2.contourArea(x))[-1]
imout_temp=np.zeros((imout.shape[0],imout.shape[1]),np.uint8)
cv2.drawContours(imout_temp,[cnt_max],0,(255,255,255),2)
f2=fillhole(imout_temp)#skimage中的morphology.remove_small_holes用不了了,只能用笨辦法
result=imout & f2[:,:,np.newaxis]
cv2.imwrite("result.jpg",result)
# cv2.namedWindow("s",cv2.WINDOW_NORMAL),cv2.imshow("s",result),cv2.waitKey(0)