nparray转成shapefile文件
前言
一、数组转成shapefile文件函数
第一步:使用cv2.findContours把图片轮廓
这些轮廓contours是一个list,list里面是array。array格式是(x,y)类似坐标
第二步:把数组转成gdal用的数据
把contours的(x,y)点,保存起来,按照如下格式,保存在binary_value.txt中
x0 y0
x1 y1
x2 y2
第三步:从txt中取数据使用gdal生成shapefile文件
def nparray2shp(file_path_jpg, folder_2_shpimg, DATASET, Imarray):
Image.fromarray(np.uint8(Imarray)).save(file_path_jpg)
#.jpg trans to .shp
np.set_printoptions(threshold=np.inf)
img = cv2.imread(file_path_jpg)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 1)
cv2.imwrite(folder_2_shpimg+DATASET+'_contour.jpg', img)
# (binary) is the binary image; contours's class is List
file = open('binary_value.txt', 'w')
for i in range(len(contours)):
for j in range(len(contours[i])):
temstr = str(contours[i][j])+'\n'
temstr=temstr.replace('[','')
temstr=temstr.replace(']','')
temstr = temstr.split()
file.write(str(temstr[0]+ ' '+str(temstr[1]))+'\n')
file.close()
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","NO")
gdal.SetConfigOption("SHAPE_ENCODING","GB2312")
ogr.RegisterAll()
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
driver = ogr.GetDriverByName("ESRI Shapefile")
dataSource = driver.CreateDataSource(folder_2_shpimg+DATASET+".shp")
layer = dataSource.CreateLayer(DATASET, srs,ogr.wkbPoint)
field_list = []
f_name= ['x_long','y_lat']
for i in range(len(f_name)):
field_name = f_name[i]
field_list.append(field_name)
field = ogr.FieldDefn(field_name, ogr.OFTString)
field.SetWidth(100)
layer.CreateField(field)
# row and col
file2 = open('binary_value.txt', 'r')
for line in file2:
feature = ogr.Feature(layer.GetLayerDefn())
geom = ogr.Geometry(ogr.wkbPoint)
geom.AddPoint(float(line.split(' ')[0]), -float(line.split(' ')[1]))
feature.SetGeometry(geom)
for j in range(2):
feature.SetField(field_list[j], line.split(' ')[j])
layer.CreateFeature(feature)
os.remove('./binary_value.txt')
os.remove(file_path_jpg)