簡體   English   中英

如何從具有空白遮罩或多邊形內部的多邊形生成遮罩?

[英]How to generate mask from polygons with blank mask or polygon inside polygon?

我通過這種方式從蒙版生成多邊形(json):

def mask_to_json(mask, file_name, labelname = 'cranes'):
    annotation = {
                "lineColor": [0,255,0,128],
                "shapes": [],
                "imagePath": file_name,
                "imageData": None,
                "fillColor": [255,0,0,128]
        }
    contours = measure.find_contours(mask, 0.5)
    contours = sorted(contours, key=len, reverse=True) #[:1]
    shape_dict = {"points":[], "line_color": None, "fill_color": None, "label": labelname}
    for n, contour in enumerate(contours):
        coords = measure.approximate_polygon(contour, tolerance=3)[:-1]
        segmentation = np.flip(coords, axis=1).tolist()
        cur_shape = copy.deepcopy(shape_dict)
        cur_shape["points"] = segmentation
        annotation["shapes"].append(cur_shape)

    file = file_name.replace(".jpg", ".json")
    #return annotation
    with open(file, 'w') as outfile:
        json.dump(annotation, outfile, indent=2)

它工作得很好,但就我而言,我在多邊形內部得到了多邊形,我不知道該多邊形是否具有適當的可視化效果:

我有這樣的代碼,擺脫了這樣的多邊形:從PIL導入圖像,ImageDraw

def polygons_to_mask_array_labelme(polygons, width : int = 300, height : int = 300) -> np.ndarray:
    '''
    This function takes a list of lists that contains polygon masks for each building. Example;

    [[x11,y11,x12,y12,...],...,[xn1,yn1,xn2,yn2,...]]

    The return of this function is an array of size width x height which contains a binary mask
    as defined by the list of polygons

    Example usage:
    import json

    with open(json_names[0], encoding = 'utf-8') as f:
        data = json.load(f)
    plt.imshow(polygons_to_mask_array(data['shapes'], 898, 559))
    '''

    img = Image.new('L', (width, height), 0)    
    for polygon in polygons:
        nested_lst_of_tuples = [tuple(l) for l in polygon['points']]
        try:
            ImageDraw.Draw(img).polygon(nested_lst_of_tuples, outline=1, fill=1)
        except:
            print(nested_lst_of_tuples)
    mask = np.array(img)

    return mask

如何從此類多邊形中正確恢復蒙版?

UPD:如果我要調用其他多邊形內的每個多邊形,則可以將其ImageDraw ,此函數ImageDraw不能填充區域:

ImageDraw.Draw(img).polygon(nested_lst_of_tuples, outline=0, fill=0)

所以沒有問題如何找到其他多邊形內的多邊形

用這種方式解決了。 我只是檢查是否有任何多邊形包含其他多邊形:

from shapely.geometry.polygon import Polygon
def polygons_to_mask_array(polygons, width : int = 300, height : int = 300) -> np.ndarray:
    img = Image.new('L', (width, height), 0)   

    for polygon in polygons:
        nested_lst_of_tuples = [tuple(l) for l in polygon['points']]
        if len(nested_lst_of_tuples)<=2: continue
        ImageDraw.Draw(img).polygon(nested_lst_of_tuples, outline=1, fill=1)
    for  polygon in polygons:
        nested_lst_of_tuples = [tuple(l) for l in polygon['points']]
        if len(nested_lst_of_tuples)<=2: continue
        if is_polygons_contains_polygon(polygons, nested_lst_of_tuples):
            ImageDraw.Draw(img).polygon(nested_lst_of_tuples, outline=0, fill=0)            
    mask = np.array(img)    
    return mask

def is_polygons_contains_polygon(all_polygons, polygon):
    for possible_bigger_polyg in all_polygons:
        possible_bigger_polyg = [tuple(l) for l in possible_bigger_polyg['points']]
        if len(possible_bigger_polyg)<=2: continue
        if possible_bigger_polyg != polygon and Polygon(possible_bigger_polyg).contains(Polygon(polygon)):
            return True
    return False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM