前言
在用labelme标注遥感图像后会生成json文件,如果我们想要shp文件,下面给出了具体实现流程。
一、依赖配置
import json import geopandas as gpd from shapely.geometry import Polygon from osgeo import gdal import argparse import glob import os import shutil
配置环境中直接用以下命令进行安装。
python">pip install 包名
如果pip找不到包,就用conda,这里geopandas就是用conda安装。
python">conda install 包名
二、json_to_shp代码实现
python">import json
import geopandas as gpd
from shapely.geometry import Polygon
from osgeo import gdal
import argparse
import glob
import os
import shutildef labelme_json_to_shapefile(labelme_json_path, output_folder):with open(labelme_json_path, 'r') as f:data = json.load(f)# 读取跟json文件相关的影像信息image_width = data['imageWidth']image_height = data['imageHeight']geometries = []imagepath = os.path.join(os.path.dirname(labelme_json_path), os.path.basename(data['imagePath']))print(imagepath)image = gdal.Open(imagepath)geotrans = image.GetGeoTransform()x0 = geotrans[0]y0 = geotrans[3]x_resolution = geotrans[1]y_resolution = geotrans[5]# 创建新的文件夹以图片名称命名image_folder = os.path.join(output_folder, os.path.splitext(os.path.basename(imagepath))[0])os.makedirs(image_folder, exist_ok=True)shutil.copy(imagepath, image_folder)# 处理每个标注对象for shape in data['shapes']:label = shape['label']points = shape['points']# 将相对坐标转换为绝对坐标polygon_coords = [(x0 + point[0] * x_resolution, y0 + point[1] * y_resolution) for point in points]# 创建 shapely Polygon 对象polygon = Polygon(polygon_coords)# 添加到 geometries 列表中geometries.append({'label': label, 'geometry': polygon})# 创建 GeoDataFramegdf = gpd.GeoDataFrame(geometries, geometry='geometry')gdf.crs = 'EPSG:4326'# 构造输出 Shapefile 文件路径output_shapefile_path = os.path.join(image_folder, os.path.splitext(os.path.basename(labelme_json_path))[0] + '.shp')gdf.to_file(output_shapefile_path, driver='ESRI Shapefile')def main():input_folder = r'D:\wheat\工具包\json_shp\json5\json'output_folder = r'D:\wheat\工具包\json_shp\json5\shp'json_files = glob.glob(os.path.join(input_folder, '*.json'))for json_file in json_files:labelme_json_to_shapefile(json_file, output_folder)if __name__ == '__main__':main()
注意json文件和tif文件要放在同一个文件夹下面。
如:
生成的文件如下: