cellpose格式标注数据转labelme格式标注数据
点击查看代码
import numpy as np
import json
import os
from skimage.measure import label, regionprops
import cv2
import glob
folder_path = 'D:/pic/zhongwei/2_team/cp_labeled/'
def contours_to_labelme_shapes(contours):
shapes = []
for contour in contours:
shape = {
"label": "SQ", # 可以根据需要更改标签名
"points": contour, # 轮廓坐标列表
"group_id": None, # 如果有多个形状组,可以设置组ID
"shape_type": "polygon", # 因为我们处理的是轮廓,所以使用多边形
"flags": {} # 可以添加其他标志或属性
}
shapes.append(shape)
return shapes
def masks_to_mask(masks):
'''
16位mask转8位二值mask
'''
x = cv2.Sobel(masks, cv2.CV_16S, 1, 0)
y = cv2.Sobel(masks, cv2.CV_16S, 0, 1)
absX = cv2.convertScaleAbs(x) # 转回uint8
absY = cv2.convertScaleAbs(y)
edge = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
ret, edge = cv2.threshold(edge, 0, 255, cv2.THRESH_BINARY)
cv2.bitwise_not(edge, edge)
mask = np.where(masks > 0, 255, 0)
mask = mask.astype(np.uint8)
cv2.bitwise_and(edge, mask, mask)
return mask
npy_files = glob.glob(os.path.join(folder_path, '*.npy'))
for npy_file in npy_files:
file_name_before_underscore = npy_file.split('.')[0]
file_name_before_underscore=file_name_before_underscore[:-4]
jpg_filename = file_name_before_underscore.split('\\')[-1] + '.jpg'
json_filename = file_name_before_underscore + '.json'
cellpose_output = np.load(npy_file, allow_pickle=True).item()
outlines = cellpose_output['masks']
mask = masks_to_mask(outlines)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours_coordinates = []
for contour in contours:
cnt = contour.tolist()
flat_list = []
for sublist in cnt:
flat_list.append(sublist[0])
#rint(flat_list)
contours_coordinates.append(flat_list)
# for i in len(contours_coordinates):
# if len(contours_coordinates[i]) < 3:
# del contours_coordinates[i]
fin_list = [sublist for sublist in contours_coordinates if len(sublist) > 2]
contours_labelme = contours_to_labelme_shapes(fin_list)
# 创建LabelMe JSON对象
labelme_json = {
"version": "5.1.1", # LabelMe的版本号,可以根据需要更改
"flags": {}, # 其他可能的标志或设置
"shapes": contours_labelme, # 轮廓坐标的形状列表
"imagePath": jpg_filename, # 图像文件的路径
"imageData": None # 图像数据(可以为None,如果图像文件存在)
}
# 将JSON对象写入文件
#json_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),json_filename)
#json_file_path = os.path.join(folder_path, json_filename)
with open(json_filename, 'w') as json_file:
json.dump(labelme_json, json_file, ensure_ascii=False, indent=2)
print(f"轮廓坐标已写入 {json_filename}")
来源链接:https://www.cnblogs.com/SunshineWeather/p/18807675
没有回复内容