Exemplo n.º 1
0
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')
Exemplo n.º 2
0
def x2jConvert_pascal(xmlpath, originImgPath, flag=True):
    # pass
    if not os.path.exists(xmlpath) or not os.path.exists(originImgPath):
        logger.error('file not exist')
        return

    base64Code = imgEncode(originImgPath)
    shapes = getPolygonPascal(xmlpath)

    (fatherPath, filename_ext) = os.path.split(originImgPath)
    (filename, _) = os.path.splitext(filename_ext)

    ob = dict()
    ob['imageData'] = base64Code
    ob['flags'] = {}
    ob['version'] = labelmeVersion
    ob['imagePath'] = filename_ext

    img = io.imread(originImgPath)
    imgShape = img.shape
    del img
    ob['imageHeight'] = imgShape[0]
    ob['imageWidth'] = imgShape[1]
    ob['shapes'] = shapes

    if flag:
        with open(fatherPath + os.sep + filename + '_p.json',
                  'w',
                  encoding='utf-8') as f:
            j = json.dumps(ob, sort_keys=True, indent=4)
            f.write(j)

        logger.info('save to path {}'.format(fatherPath + os.sep + filename +
                                             '_p.json'))
        return fatherPath + os.sep + filename + '_p.json'
    else:
        return json.dumps(ob, sort_keys=True, indent=4)
Exemplo n.º 3
0
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
Exemplo n.º 4
0
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')
Exemplo n.º 5
0
def imgNoise(oriImg: str, oriLabel: str, flag=True, labelFile=''):
    """
    see skimage.util.random_noise    
    """
    noise_type = ['gaussian', 'poisson', 's&p', 'speckle']

    l = np.random.randint(2, size=len(noise_type)).tolist()
    # print(l)
    p = list(zip(noise_type, l))

    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')
        return

    for i in p:
        if i[1] != 0:
            img = snoise.random_noise(img, mode=i[0])

    img = np.array(img * 255).astype(np.uint8)

    if flag:
        # parent_path = os.path.dirname(oriImg)
        (parent_path, file_path) = os.path.split(oriImg)
        if os.path.exists(parent_path + os.sep + 'jsons_'):
            pass
        else:
            os.makedirs(parent_path + os.sep + 'jsons_')
        # fileName = oriImg.split(os.sep)[-1].replace('.json', '')
        fileName = os.path.splitext(file_path)[0]

        io.imsave(
            parent_path + os.sep + 'jsons_' + os.sep + fileName + '_noise.jpg',
            img)

        try:
            if isinstance(oriLabel, str):
                shutil.copyfile(
                    oriLabel, parent_path + os.sep + 'jsons_' + os.sep +
                    fileName + '_noise.json')

                base64code = imgEncode(parent_path + os.sep + 'jsons_' +
                                       os.sep + fileName + '_noise.jpg')

                with open(
                        parent_path + os.sep + 'jsons_' + os.sep + fileName +
                        '_noise.json', 'r') as f:
                    load_dict = json.load(f)

                load_dict['imageData'] = base64code

                with open(
                        parent_path + os.sep + 'jsons_' + os.sep + fileName +
                        '_noise.json', 'w') as f:
                    # json.dump(load_dict,parent_path+os.sep+'jsons_'+os.sep+fileName+'_noise.json')
                    f.write(json.dumps(load_dict))

            elif isinstance(oriLabel, np.ndarray):
                """
                labeled file can be an Image
                """
                noisedMask_j = getMultiShapes(parent_path + os.sep + 'jsons_' +
                                              os.sep + fileName + '_noise.jpg',
                                              oriLabel,
                                              flag=True,
                                              labelYamlPath=labelFile)
                with open(
                        parent_path + os.sep + 'jsons_' + os.sep + fileName +
                        '_noise.json', 'w') as f:
                    f.write(json.dumps(noisedMask_j))

        except Exception:
            print(traceback.format_exc())

    else:
        d = dict()
        # mask = processor(oriLabel,flag=True)
        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".format(
                    type(oriLabel)))
        # print('======================')
        # print(np.max(mask))
        # print('======================')
        d['noise'] = Ori_Pro(img, mask)

        return d
Exemplo n.º 6
0
import os

from convertmask.utils.methods.img2base64 import imgEncode
from skimage import io

try:
    from labelme import __version__
except:
    __version__ = '4.2.9'

BASE_DIR = os.path.abspath(os.path.dirname(os.getcwd())) + os.sep + 'static'
imgPath = BASE_DIR + os.sep + 'multi_objs_test.jpg'

if __name__ == "__main__":
    image = io.imread(imgPath)
    base64Code = imgEncode(image).decode()

    # print(base64Code)
    (fatherPath, filename_ext) = os.path.split(imgPath)
    (filename, _) = os.path.splitext(filename_ext)

    ob = dict()
    ob['imageData'] = base64Code
    ob['flags'] = {}
    ob['version'] = __version__
    ob['imagePath'] = filename_ext
    ob['shapes'] = []

    ob['imageHeight'] = image.shape[0]
    ob['imageWidth'] = image.shape[1]
    # ob['shapes'] = shapes