给我一个python代码用cv2的方法将一个文件夹中所有含有坐标信息的json文件,转化为可用于分割训练的标签二值化黑白png图片且命名方式不变
时间: 2023-04-01 14:04:17 浏览: 57
以下是我作为 CSDN 开发的 C 知道的回答:
可以使用以下 Python 代码实现:
```python
import cv2
import json
import os
# 定义函数将 json 文件转化为二值化黑白 png 图片
def json_to_png(json_file, png_file):
with open(json_file, 'r') as f:
data = json.load(f)
img = cv2.imread(data['imagePath'], )
for shape in data['shapes']:
pts = shape['points']
pts = pts.reshape((-1, 1, 2)).astype(int)
cv2.fillPoly(img, [pts], 255)
cv2.imwrite(png_file, img)
# 遍历文件夹中所有 json 文件并转化为 png 文件
folder_path = 'your_folder_path'
for file_name in os.listdir(folder_path):
if file_name.endswith('.json'):
json_file = os.path.join(folder_path, file_name)
png_file = os.path.join(folder_path, file_name.replace('.json', '.png'))
json_to_png(json_file, png_file)
```
这段代码可以将指定文件夹中所有含有坐标信息的 json 文件转化为二值化黑白 png 图片,并且命名方式不变。