Exemplo n.º 1
0
def inference(image, score, output_file):
    building_score = score[1]
    
    building_mask_pred = (np.argmax(score, axis=0) == 1)
    polygons = Mask(building_mask_pred).polygons()
    
    new_predictions = []
    
    for poly in polygons:
        if len(poly) >= 3:
            f = poly.reshape(-1, 2)
            simplified_vw = simplify_coords_vwp(f, .3)
            if len(simplified_vw) > 2:
                    mpoly = []
                    # Rebuilding the polygon in the way that PIL expects the values [(x1,y1),(x2,y2)]
                    for i in simplified_vw:
                        mpoly.append((i[0], i[1]))
                    # Adding the first point to the last to close the polygon
                    mpoly.append((simplified_vw[0][0], simplified_vw[0][1]))
                    new_predictions.append(mpoly)
            
    # Creating the json with the predicted and then adjusted polygons
    output_json = create_json(new_predictions)
    
    with open(output_file, 'w') as out_file:
        json.dump(output_json, out_file)
Exemplo n.º 2
0
def inference2(image, weights, mean):
    mean = np.load(mean)
    model = segmentation_cpu.SegmentationModel(weights, mean)

    image = np.array(Image.open(image))
    score = model.apply_segmentation(image)

    building_score = score[1]

    building_mask_pred = (np.argmax(score, axis=0) == 1)
    polygons = Mask(building_mask_pred).polygons()

    new_predictions = []

    for poly in polygons:
        if len(poly) >= 3:
            f = poly.reshape(-1, 2)
            simplified_vw = simplify_coords_vwp(f, .3)
            if len(simplified_vw) > 2:
                mpoly = []
                # Rebuilding the polygon in the way that PIL expects the values [(x1,y1),(x2,y2)]
                for i in simplified_vw:
                    mpoly.append((i[0], i[1]))
                # Adding the first point to the last to close the polygon
                mpoly.append((simplified_vw[0][0], simplified_vw[0][1]))
                new_predictions.append(mpoly)

    # Creating the json with the predicted and then adjusted polygons
    output_json = create_json(new_predictions)
    return output_json
Exemplo n.º 3
0
def predict_polygons(polygons):
    new_predictions = []
    for poly in polygons:
        if len(poly) >= 3:
            f = poly.reshape(-1, 2)
            simplified_vw = simplify_coords_vwp(f, .3)
            if len(simplified_vw) > 2:
                mpoly = []
                # Rebuilding the polygon in the way that PIL expects the values [(x1,y1),(x2,y2)]
                for i in simplified_vw:
                    mpoly.append((i[0], i[1]))
                # Adding the first point to the last to close the polygon
                mpoly.append((simplified_vw[0][0], simplified_vw[0][1]))
                new_predictions.append(mpoly)
    return new_predictions
Exemplo n.º 4
0
def mask_to_polygons(mask, use_convex_hull=False):
    """
    convert predicted mask to polygons
    """
    # for cv2 versions that do not support incontiguous array
    mask = np.ascontiguousarray(mask)
    mask = mask.astype(np.uint8)
    # cv2.RETER_CCOMP flag retrieves all the contours
    # the arranges them to a 2-level hierarchy.
    res = cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

    hierarchy = res[-1]
    # mask is empty
    if hierarchy is None:
        return [], False

    has_holes = (hierarchy.reshape(-1, 4)[:, 3] >= 0).sum() > 0

    res = res[-2]
    try:
        res_simp = simplify_coords_vwp(res[0].squeeze(), 30.0)
        res_simp = np.array(res_simp)
        res = [np.expand_dims(res_simp, axis=1)]
    except ValueError:
        print('Failed to simplify the points.')

    if use_convex_hull:
        hull = []
        for i in range(len(res)):
            hull.append(cv2.convexHull(res[i], False))
            res = [x.flatten() for x in hull]
    else:
        res = [x.flatten() for x in res]

    # convert OpenCV int coordinates [0, H -1 or W-1] to
    # real value coordinate spaces
    res = [x + 0.5 for x in res if len(x) >= 6]

    return res, has_holes
Exemplo n.º 5
0
def findContours(edges, min_arclength, contour_roughness):

    contour_points, h = cv.findContours(edges, cv.RETR_TREE,
                                        cv.CHAIN_APPROX_SIMPLE)
    print("inital amount of cnts", len(contour_points))

    #remove all contours with arclength less than 3 * edge length
    cnts = []
    for contour in contour_points:
        if cv.arcLength(contour, True) > min_arclength * 3:
            cnts.append(contour)
    print("removed", len(contour_points) - len(cnts), "short contours")
    contour_points = cnts

    #simplify polygons using a topology preserving variant of the Visvalingam-Whyatt Algorithm
    contour_points = [
        simplify_coords_vwp(np.squeeze(contour), contour_roughness)
        for contour in contour_points
    ]

    # delete contours with less than 3 points (not even forming a polygon)
    cnts = []
    for contour in contour_points:
        if len(contour) > 2:
            cnts.append(contour)
    print("removed",
          len(contour_points) - len(cnts), " contours with less than 3 points")
    contour_points = cnts

    #turn contours into polygon objects
    contour_points = [Polygon(contour) for contour in contour_points]

    #delete invalid contours (non-closing)
    cnts = []
    invalid_contours = []
    for polygon in contour_points:
        if polygon.is_valid:
            cnts.append(polygon)
        else:
            invalid_contours.append(polygon)
    print("removed",
          len(contour_points) - len(cnts), " contours that were invalid")
    contour_points = cnts

    #delete overlapping contours
    cnts = []
    overlap_cnts = []
    for i in range(len(contour_points)):
        a = contour_points[i]
        if a not in overlap_cnts:
            cnts.append(a)
        for j in range(i, len(contour_points)):
            b = contour_points[j]
            if a != b:
                if a.overlaps(b):
                    overlap_cnts.append(b)

    print("removed",
          len(contour_points) - len(cnts), " contours that were overlapping")
    contour_points = [cnt for cnt in cnts if cnt not in overlap_cnts]

    print("found", len(contour_points), "valid contours")

    return contour_points, invalid_contours