def test(): img = "D:\\testALg\mask2json\mask2json\static\\1-2cvt.png" oriImg = "D:\\testALg\mask2json\mask2json\static\\1-2cvt.jpg" imgShape = cv2.imread(img).shape region = getShape.process(img) # print(type(region)) # print(region.shape) points = [] shapes = [] for i in range(0, region.shape[0]): print(region[i][0]) points.append(region[i][0].tolist()) obj = dict() obj['version'] = '4.2.9' obj['flags'] = {} shape = dict() shape['label'] = 'weld' #whatever other label shape['points'] = points shape['group_id'] = 'null' shape['shape_type'] = 'polygon' shape['flags'] = {} shapes.append(shape) obj['shapes'] = shapes obj['imagePath'] = oriImg.split(os.sep)[-1] obj['imageData'] = str(img2base64.imgEncode(oriImg)) obj['imageHeight'] = imgShape[0] obj['imageWidth'] = imgShape[1] j = json.dumps(obj, sort_keys=True, indent=4) print(j) with open('D:\\testALg\mask2json\mask2json\static\\1-2cvt.json', 'w') as f: f.write(j) rmQ.rm('D:\\testALg\mask2json\mask2json\static\\1-2cvt.json')
def getMultiShapes(oriImgPath, labelPath, savePath='', labelYamlPath='', flag=False, areaThresh=500): """ oriImgPath : for change img to base64 \n labelPath : after fcn/unet or other machine learning objects outlining , the generated label img or labelme labeled imgs(after json files converted to mask files) \n savePath : json file save path \n labelYamlPath : after json files converted to mask files. if doesn't have this file,should have a labeled img. but the classes should change by yourself(labelme 4.2.9 has a bug,when change the label there will be an error. ) \n """ # print('-==================') # print(oriImgPath) # print(labelPath) # print(savePath) # print(labelYamlPath) # print('-==================') if isinstance(labelPath, str): if os.path.exists(labelPath): label_img = io.imread(labelPath) else: raise FileNotFoundError('mask/labeled image not found') else: # img = oriImg label_img = labelPath # print(np.max(label_img)) if np.max(label_img) > 127: # print('too many classes! \n maybe binary?') label_img[label_img > 127] = 255 label_img[label_img != 255] = 0 label_img = label_img / 255 labelShape = label_img.shape labels = readYmal(labelYamlPath, label_img) # print(list(labels)) shapes = [] obj = dict() obj['version'] = labelme_version obj['flags'] = {} for la in list(labels): if la[1] > 0: # print(la[0]) img = copy.deepcopy(label_img) # img = label_img.copy() img = img.astype(np.uint8) img[img == la[1]] = 255 img[img != 255] = 0 region = process(img.astype(np.uint8)) if isinstance(region, np.ndarray): points = [] for i in range(0, region.shape[0]): # print(region[i][0]) points.append(region[i][0].tolist()) shape = dict() shape['label'] = la[0] shape['points'] = points shape['group_id'] = 'null' shape['shape_type'] = 'polygon' shape['flags'] = {} shapes.append(shape) elif isinstance(region, list): # print(len(region)) for subregion in region: points = [] for i in range(0, subregion.shape[0]): points.append(subregion[i][0].tolist()) shape = dict() shape['label'] = la[0] shape['points'] = points shape['group_id'] = 'null' shape['shape_type'] = 'polygon' shape['flags'] = {} shapes.append(shape) # print(len(shapes)) obj['shapes'] = shapes # print(shapes) (_, imgname) = os.path.split(oriImgPath) obj['imagePath'] = imgname # print(obj['imagePath']) obj['imageData'] = str(imgEncode(oriImgPath)) obj['imageHeight'] = labelShape[0] obj['imageWidth'] = labelShape[1] j = json.dumps(obj, sort_keys=True, indent=4) # print(j) if not flag: saveJsonPath = savePath + os.sep + obj['imagePath'][:-4] + '.json' # print(saveJsonPath) with open(saveJsonPath, 'w') as f: f.write(j) rmQ.rm(saveJsonPath) else: return j
def test(): # BASE_DIR = os.path.abspath(os.curdir) BASE_DIR = os.path.abspath(os.path.dirname(os.getcwd())) """ do not use cv2.imread to load the label img. there is a bug """ # oriImgPath = 'D:\\testALg\\mask2json\\mask2json\\static\\multi_objs_sameclass.jpg' # label_img = io.imread('D:\\testALg\\mask2json\\mask2json\\multi_objs_sameclass_json\\label.png') oriImgPath = BASE_DIR + '/static/multi_objs.jpg' label_img = io.imread(BASE_DIR + '/static/multi_objs_json/label.png') labelShape = label_img.shape labels = readYmal(BASE_DIR + '/static/multi_objs_json/info.yaml') shapes = [] obj = dict() obj['version'] = labelme_version obj['flags'] = {} for la in labels: if la[1] > 0: # img = label_img[label_img == i[1]] img = copy.deepcopy(label_img) img[img == la[1]] = 255 img[img != 255] = 0 region = process(img.astype(np.uint8)) """ this if...else... is unnecessary if using getShape.getMultiRegion """ if isinstance(region, np.ndarray): points = [] for i in range(0, region.shape[0]): # print(region[i][0]) points.append(region[i][0].tolist()) shape = dict() shape['label'] = la[0] shape['points'] = points shape['group_id'] = 'null' shape['shape_type'] = 'polygon' shape['flags'] = {} shapes.append(shape) elif isinstance(region, list): for subregion in region: points = [] for i in range(0, subregion.shape[0]): # print(region[i][0]) points.append(subregion[i][0].tolist()) shape = dict() shape['label'] = la[0] shape['points'] = points shape['group_id'] = 'null' shape['shape_type'] = 'polygon' shape['flags'] = {} shapes.append(shape) obj['shapes'] = shapes obj['imagePath'] = oriImgPath.split(os.sep)[-1] obj['imageData'] = str(imgEncode(oriImgPath)) obj['imageHeight'] = labelShape[0] obj['imageWidth'] = labelShape[1] j = json.dumps(obj, sort_keys=True, indent=4) with open(BASE_DIR + '/static/multi_objs.json', 'w') as f: f.write(j) rmQ.rm(BASE_DIR + '/static/multi_objs.json')
def imgFlip(oriImg: str, oriLabel: str, flip_list=[1, 0, -1], flag=True, labelFile=''): """ flipList: flip type. see cv2.flip : 1: 水平翻转 \n 0: 垂直翻转 \n -1: 同时翻转 \n >>> import cv2 >>> help(cv2.flip) """ if isinstance(oriImg, str): if os.path.exists(oriImg): img = io.imread(oriImg) else: raise FileNotFoundError('Original image not found') elif isinstance(oriImg, np.ndarray): img = oriImg else: logger.error('input {} type error'.format(imgFlip)) return try: if len(flip_list) > 1 and (1 in flip_list or 0 in flip_list or -1 in flip_list): if isinstance(oriLabel, str): if os.path.exists(labelFile): mask = processorWithLabel(oriLabel, labelFile, flag=True) else: mask = processor(oriLabel, flag=True) elif isinstance(oriLabel, np.ndarray): mask = oriLabel else: raise TypeError( "input parameter 'oriLabel' type is not supported") # print(type(mask)) h_ori = cv2.flip(img, 1) v_ori = cv2.flip(img, 0) h_v_ori = cv2.flip(img, -1) h_mask = cv2.flip(mask, 1) if 1 in flip_list else None v_mask = cv2.flip(mask, 0) if 0 in flip_list else None h_v_mask = cv2.flip(mask, -1) if -1 in flip_list else None """ maybe dict or zip is better :) """ if flag: parent_path = os.path.dirname(oriLabel) if os.path.exists(parent_path + os.sep + 'jsons_'): pass else: os.makedirs(parent_path + os.sep + 'jsons_') fileName = oriLabel.split(os.sep)[-1].replace('.json', '') io.imsave( parent_path + os.sep + 'jsons_' + os.sep + fileName + '_h.jpg', h_ori) if 1 in flip_list else do_nothing() io.imsave( parent_path + os.sep + 'jsons_' + os.sep + fileName + '_v.jpg', v_ori) if 0 in flip_list else do_nothing() io.imsave( parent_path + os.sep + 'jsons_' + os.sep + fileName + '_h_v.jpg', h_v_ori) if -1 in flip_list else do_nothing() h_j = getMultiShapes( parent_path + os.sep + 'jsons_' + os.sep + fileName + '_h.jpg', h_mask, flag=True, labelYamlPath='') if h_mask is not None else None # h_j = getMultiShapes(parent_path+os.sep+'jsons_'+os.sep+fileName+'_h.jpg',h_mask,flag=True,labelYamlPath='D:\\testALg\\mask2json\\mask2json\\multi_objs_json\\info.yaml') v_j = getMultiShapes( parent_path + os.sep + 'jsons_' + os.sep + fileName + '_v.jpg', v_mask, flag=True, labelYamlPath='') if v_mask is not None else None h_v_j = getMultiShapes( parent_path + os.sep + 'jsons_' + os.sep + fileName + '_h_v.jpg', h_v_mask, flag=True, labelYamlPath='') if h_v_mask is not None else None for saveJsonPath in [ parent_path + os.sep + 'jsons_' + os.sep + fileName + '_h.json', parent_path + os.sep + 'jsons_' + os.sep + fileName + '_v.json', parent_path + os.sep + 'jsons_' + os.sep + fileName + '_H_V.json' ]: # if saveJsonPath is not None: # print(saveJsonPath) if saveJsonPath.endswith('_h.json'): if h_j is not None: with open(saveJsonPath, 'w') as f: f.write(h_j) else: pass elif saveJsonPath.endswith('_v.json'): if v_j is not None: with open(saveJsonPath, 'w') as f: f.write(v_j) else: pass elif saveJsonPath.endswith('_H_V.json'): if h_v_j is not None: with open(saveJsonPath, 'w') as f: f.write(h_v_j) else: pass rmQ.rm(saveJsonPath) if os.path.exists( saveJsonPath) else do_nothing() return "" else: d = dict() d['h'] = Ori_Pro(h_ori, h_mask) d['v'] = Ori_Pro(v_ori, v_mask) d['h_v'] = Ori_Pro(h_v_ori, h_v_mask) return d else: logger.warning("<===== param:flip_list is not valid =====>") except Exception: # print(e) print(traceback.format_exc())