语义分割——json文件转shp

前言

        在用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

        配置环境中直接用以下命令进行安装。

pip install 包名

        如果pip找不到包,就用conda,这里geopandas就是用conda安装。

conda install  包名

二、json_to_shp代码实现

import json
import geopandas as gpd
from shapely.geometry import Polygon
from osgeo import gdal
import argparse
import glob
import os
import shutil

def 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})

    # 创建 GeoDataFrame
    gdf = 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文件要放在同一个文件夹下面。

        如:

生成的文件如下:

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是dream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值