Beispiel #1
0
def get_pixel_polygon_from_state(state):
    p = state.edge_pixels
    object_bonding_pixels = [
        Point(p['x_min'], p['y_min']),
        Point(p['x_min'], p['y_max']),
        Point(p['x_max'], p['y_max']),
        Point(p['x_max'], p['y_min'])
    ]
    return Polygon(object_bonding_pixels)
Beispiel #2
0
def get_locomotion_feature(step_output, object_occluded, object_in_scene,
                           obj_info):
    if step_output is None:
        obj = None
    else:
        obj = obj_info
    features = []
    if not object_in_scene:
        features.extend([0.0] * 27)  # position + bonding_box
        # features.extend([0.0]) # supported
        features.extend([0.0, 0.0])  # occluded, in_scene
    else:
        if object_occluded:
            features.extend([0.0] * 27)
            # features.extend([0.0])  # supported
            features.extend([0.0, 1.0])
        else:
            features.append(obj.position['x'])
            features.append(obj.position['y'])
            features.append(obj.position['z'])
            bonding_xy = []
            for bonding_vertex in obj.dimensions:
                features.append(bonding_vertex['x'])
                features.append(bonding_vertex['y'])
                bonding_xy.append(
                    Point(bonding_vertex['x'], bonding_vertex['y']))
                features.append(bonding_vertex['z'])
            # step_output.object_mask_list[-1].show()
            # features.extend(get_support_indicator(step_output, bonding_xy))
            features.extend([1.0, 1.0])

    assert len(features) == POSITION_FEATURE_DIM
    return torch.tensor(features)
Beispiel #3
0
def calc_weighted_centroid(P, Q, vertices):
    width, height = P.shape
    vertices = [ [i[0]-1, i[1]-1] for i in vertices] # adjust x values for vertices to compensate for zero padding in P/Q

    px = []
    polygon = Polygon(vertices)
    bounding_box = get_Bounding_Box(vertices)

    for y in range(int(bounding_box[2]), int(bounding_box[3])):
        row = []
        for x in range(int(bounding_box[0]), int(bounding_box[1])):
            if polygon.contains(Point(x, y)) or polygon.touches(Point(x, y)):
                row.append((x, y))
        if(row != []):
            px.append(row)


    denom = 0
    xNum = 0
    yNum = 0

    for row in px:
        first = row[0]
        last = row[-1]

        denom += P[last] - P[first]
        xNum += (last[0]*P[last]-first[0]*P[first]) - (Q[last]-Q[first])
        yNum += (width-last[1])*(P[last]-P[first])

    if(denom == 0 or xNum == 0 or yNum == 0): # todo denom, xNum, and yNum become zero when point density is higher
        print("trying to divide by zero")
        print("bounding box for cell: " + str(bounding_box))
        # print("pixels in cell: " + str(px))

    cx = xNum/denom
    cy = yNum/denom
    # print("denom = " + str(denom) + " xNum = " + str(xNum) + " yNum = " + str(yNum) + " centroid = (" + str(cx) + ", " + str(cy) + ")")

    return np.array([[cx, cy]])
Beispiel #4
0
def find_tile_at_point_slow(lon, lat):
    """Retrieve the tile where the point (lon, lat) sits.

    WARNING: this is an approximative algo. The tiles boundaries are
    curved.  A point inside a tile ain't necessarily inside the
    quadrilateral formed with the four corners...

    """
    point = Point(lon, lat)
    tile0 = -1
    for tile, p in polygon_tiles.items():
        if p.contains(point):
            tile0 = tile
            break
    return tile0
    def generate_random(self, number=100):
        """Generate shapely.geometry.Point n randon objects corresponding to the
    regions of a Generate shapely.geometry.Polygon area object, based on a 
    np.random.uniform distribution.

    """
        polygon = self._polygon

        list_of_points = []
        minx, miny, maxx, maxy = polygon.bounds
        counter = 0
        while counter < number:
            pnt = Point(np.random.uniform(minx, maxx),
                        np.random.uniform(miny, maxy))
            if polygon.contains(pnt):
                list_of_points.append(pnt)
                counter += 1
        self.list_of_points = list_of_points
        return self.list_of_points
Beispiel #6
0
def findTheFrontFarestCorner(probe, floorMeta, floorPoly, pd):
    MAXLEN = -1
    wallDiagIndex = -1
    for wallJndex in range(floorMeta.shape[0]):
        trobe = floorMeta[wallJndex][0:2]
        # check if the diagonal lies inside the edges of the polygon.
        line = LineString((probe, trobe))
        if sk.isLineIntersectsWithEdges(line, floorMeta):
            continue
        # check if some point on the diagonal is inside the polygon.
        mPoint = Point((probe + trobe) / 2)
        if not floorPoly.contains(mPoint):
            continue
        if np.dot(trobe - probe, pd) < 0:
            continue
        LEN = np.linalg.norm(probe - trobe, ord=2)
        if LEN > MAXLEN:
            MAXLEN = LEN
            wallDiagIndex = wallJndex
    return wallDiagIndex
Beispiel #7
0
def findTheLongestDiagonal(wallIndex, floorMeta, floorPoly):
    probe = floorMeta[wallIndex][0:2]
    MAXLEN = -1
    wallDiagIndex = -1
    for wallJndex in range(floorMeta.shape[0]):
        # a diagonal can not be formed using adjacent vertices or 'wallIndex' itself.
        if wallJndex == wallIndex or wallJndex == (
                wallIndex + 1) % floorMeta.shape[0] or wallIndex == (
                    wallJndex + 1) % floorMeta.shape[0]:
            continue
        trobe = floorMeta[wallJndex][0:2]
        # check if the diagonal lies inside the edges of the polygon.
        line = LineString((probe, trobe))
        if sk.isLineIntersectsWithEdges(line, floorMeta):
            continue
        # check if some point on the diagonal is inside the polygon.
        mPoint = Point((probe + trobe) / 2)
        if not floorPoly.contains(mPoint):
            continue
        LEN = np.linalg.norm(probe - trobe, ord=2)
        if LEN > MAXLEN:
            MAXLEN = LEN
            wallDiagIndex = wallJndex
    return wallDiagIndex
def get_grid_points_for_target_layer(file, target_layer, gap):
    '''
    get grid points inside infill on the target layer
    :param file: gcode file location
    :param target_layer: target layer number
    :param gap: gap between grid points (mm)
    :return: lists of x coordinates and y coordinates of a-structure and b-structure
    '''

    gcode = open(file)

    lines = gcode.readlines()

    is_target = 0
    is_inner_wall = 0

    target_lines = ""

    for l in lines:
        if is_target == 1 and is_inner_wall == 1 and ";TYPE:" in l:
            is_inner_wall = 0
        if ";LAYER:" + str(target_layer) + "\n" in l:  # target layer
            is_target = 1
            target_lines += l
        if ";LAYER:" + str(target_layer + 1) + "\n" in l:  # next layer
            break
        if is_target == 1 and ";TYPE:WALL-INNER" in l:
            is_inner_wall = 1
        if is_target == 1 and is_inner_wall == 1:
            target_lines += l

    x_values = []
    y_values = []
    #print(target_lines)

    for l in target_lines.split("\n"):
        if "G1" in l:
            elems = l.split(" ")

            for e in elems:
                if ";" not in e:
                    if "X" in e:
                        x_values.append(float(e.split("X")[1]))
                    if "Y" in e:
                        y_values.append(float(e.split("Y")[1]))

        elif "G0" in l:  # flag that indicates the next polygon
            x_values.append("G0")
            y_values.append("G0")

    # all polygons
    all_polygons_coords = get_all_polygons(x_values, y_values)

    set_a_x = []
    set_a_y = []
    set_b_x = []
    set_b_y = []

    #print(Polygon(all_polygons_coords.iloc[1]['polygon']).area)

    inner_polygons_index = []
    #print(all_polygons_coords)

    for index in range(len(all_polygons_coords)):
        if index in inner_polygons_index:
            #print("inner-polygon", index, all_polygons_coords.iloc[index]['area'])
            pass
        else:
            polygon = all_polygons_coords.iloc[index]['polygon']
            inner_polygons = []

            for a in range(index + 1, len(all_polygons_coords)):
                smaller_polygon = all_polygons_coords.iloc[a]['polygon']

                is_in = True
                for b in range(len(smaller_polygon)):
                    if not Polygon(polygon).contains(
                            Point([
                                smaller_polygon[b][0], smaller_polygon[b][1]
                            ])):
                        is_in = False
                        #print(smaller_polygon[b])

                if is_in:
                    inner_polygons.append(smaller_polygon)
                    inner_polygons_index.append(a)

            polygon.append(polygon[0])

            # print(polygon_coords)

            x_values = []
            y_values = []

            for i in range(len(polygon)):
                x_values.append(polygon[i][0])
                y_values.append(polygon[i][1])

            # print(polygon.area)

            x_min, x_max = get_min_max(x_values)
            y_min, y_max = get_min_max(y_values)

            grid_x = []
            grid_y = []

            current_x = x_min + gap / 2.2
            current_y = y_min + gap / 2.2
            # print(x_min)
            # print(y_min)

            grid_x.append(current_x)
            grid_y.append(current_y)

            while current_x <= x_max:
                current_x += gap
                grid_x.append(current_x)
            while current_y <= y_max:
                current_y += gap
                grid_y.append(current_y)

            # print(grid_x)
            # print(grid_y)

            # a structure
            a_x = []
            a_y = []

            no_x = []
            no_y = []

            polygon = Polygon(polygon)

            for i in range(len(grid_x)):
                for j in range(len(grid_y)):
                    current_point = Point(grid_x[i], grid_y[j])

                    if polygon.contains(current_point):

                        if is_far_from_inner_wall(current_point.x,
                                                  current_point.y,
                                                  x_values,
                                                  y_values,
                                                  threshold=1):
                            if len(inner_polygons) > 0:  # has inner polygons
                                include = True
                                for inner_poly in inner_polygons:
                                    if Polygon(inner_poly).contains(
                                            Point(current_point.x,
                                                  current_point.y)):
                                        #print(current_point)
                                        include = False

                                        #exclude.append((i, j))
                                    #else:
                                    #    no_x.append(current_point.x)
                                    #    no_y.append(current_point.y)
                                if include:
                                    a_x.append(current_point.x)
                                    a_y.append(current_point.y)

                            else:  # no inner polygon
                                a_x.append(current_point.x)
                                a_y.append(current_point.y)
            #print(len(exclude))
            #print(len(set(exclude)))
            #exclude = list(set(exclude))
            '''
            for i in range(len(grid_x)):
                for j in range(len(grid_y)):
                    if not (i, j) in exclude:
                        current_point = Point(grid_x[i], grid_y[j])
                        a_x.append(current_point.x)
                        a_y.append(current_point.y)
            '''
            a_coords = []  # coordinates of a structure

            for i in range(len(a_x)):
                a_coords.append([a_x[i], a_y[i]])

            # print(a_coords)

            # print(sorted(a_coords, key=lambda x: x[1]))

            # x and y values for b structure
            b_x = []
            b_y = []

            # check if the unit square is included in the polygon
            for i in range(len(a_coords)):
                if unit_square_is_included(a_coords[i], gap, a_coords):
                    b_x.append(a_coords[i][0] + gap / 2)
                    b_y.append(a_coords[i][1] + gap / 2)
            '''
            plt.plot(x_values, y_values, 'ro', markersize=3)

            plt.plot(a_x, a_y, 'bo', markersize=3)
            plt.plot(b_x, b_y, 'go', markersize=3)
            plt.autoscale()
            #plt.plot(no_x, no_y, 'bo', markersize=0.2)
            '''
            set_a_x.append(a_x)
            set_a_y.append(a_y)
            set_b_x.append(b_x)
            set_b_y.append(b_y)

        #return a_x, a_y, b_x, b_y

    #print(len(set_a_x), len(set_a_y), len(set_b_x), len(set_b_y))

    #plt.plot(set_a_x, set_a_y, 'bo', markersize=0.1)
    #plt.plot(set_b_x, set_b_y, 'go')
    #plt.show()

    #for i in range(len(set_a_x)):
    #    plt.plot(set_a_x[i], set_a_y[i], 'bo')
    #for i in range(len(set_b_x)):
    #    plt.plot(set_b_x[i], set_b_y[i], 'ro')

    #plt.show()

    #plt.show()
    #return

    return set_a_x, set_a_y, set_b_x, set_b_y
        inside5[j * 2] = po1.intersects(p2)
        inside5[(j * 2) + 1] = po1.intersects(p3)
    elif z % 2 == 0:
        po1 = Polygon(polygon1)
        p2 = Polygon(
            [combined[j], combined[j + 1], combined[j + 15], combined[j]])
        p3 = Polygon(
            [combined[j], combined[j + 14], combined[j + 15], combined[j]])
        inside5[j * 2] = po1.intersects(p3)
        inside5[(j * 2) + 1] = po1.intersects(p2)

final_coordinates = []

for i in range(0, 188):
    if inside2[i] == True:
        final_coordinates.append(Point(combined[i]))

for i in range(0, 188):
    poly = Polygon(polygon1)
    p1 = 0
    if inside5[i * 2] == True:
        #print(i)
        b1x = (combined[i][0] + combined[i + 1][0]) / 2
        b1y = (combined[i][1] + combined[i + 1][1]) / 2
        b2x = (combined[i + 1][0] + combined[i + 15][0]) / 2
        b2y = (combined[i + 1][1] + combined[i + 15][1]) / 2
        b3x = (combined[i][0] + combined[i + 15][0]) / 2
        b3y = (combined[i][1] + combined[i + 15][1]) / 2

        v1 = Polygon([[b1x, b1y], combined[i], [b3x, b3y], centroid[i * 2],
                      [b1x, b1y]])
Beispiel #10
0
def get_2d_bonding_box_point(dimensions):
    front_8_points = [dimensions[i] for i in range(8)]
    list_of_point_obj = []
    for p in front_8_points:
        list_of_point_obj.append(Point(p['x'], p['y']))
    return list_of_point_obj
Beispiel #11
0
    def error_update_out_view(self, new_occluder_state_dict,
                              locomotion_checker):
        if not self.out_of_scene:
            pred_occluded_by = None
            for id, occluder_state in new_occluder_state_dict.items():
                if occluder_state.bonding_box_poly.contains(
                        Point(self.next_step_position)):
                    pred_occluded_by = id
                    self.locomotion_cnt['near'] += 1
                    # print("Reasonable with error 0")

            if not pred_occluded_by:
                if self.occluded_by:
                    threshold = locomotion_checker.LOCOMOTION_MSE_ERROR_THRESHOLD_UNSEEN
                    poly = new_occluder_state_dict[
                        self.occluded_by].bonding_box_poly
                    error = np.square(
                        poly.distance(Point(self.next_step_position)))
                    if error > threshold:
                        self.locomotion_cnt['far'] += 1
                        # print("Unreasonable with error {:.4f}".format(error))
                    else:
                        self.locomotion_cnt['near'] += 1
                        # print("Reasonable with error {:.4f}".format(error))

                    if self.plot:
                        plt.plot(self.next_step_position[0],
                                 self.next_step_position[1],
                                 color='b',
                                 marker='x')
                        plt.pause(0.1)
                        x, y = poly.exterior.xy
                        plt.plot(x, y, 'k')
                        plt.pause(0.1)
                else:
                    min_error = float('inf')
                    min_error_poly = None
                    for id, occluder_state in new_occluder_state_dict.items():
                        poly = occluder_state.bonding_box_poly
                        error = np.square(
                            poly.distance(Point(self.next_step_position)))
                        if error < min_error:
                            self.occluded_by = id
                            min_error = error
                            min_error_poly = poly
                    if min_error > locomotion_checker.LOCOMOTION_MSE_ERROR_THRESHOLD:
                        self.locomotion_cnt['far'] += 1
                        # print("Unreasonable with error {:.4f}".format(error))
                    else:
                        self.locomotion_cnt['near'] += 1
                        # print("Reasonable with error {:.4f}".format(error))

                    if self.plot:
                        plt.plot(self.next_step_position[0],
                                 self.next_step_position[1],
                                 color='b',
                                 marker='x')
                        plt.pause(0.1)
                        x, y = min_error_poly.exterior.xy
                        plt.plot(x, y, 'k')
                        plt.pause(0.1)
            else:
                self.occluded_by = pred_occluded_by
                if self.plot:
                    plt.plot(self.next_step_position[0],
                             self.next_step_position[1],
                             color='b',
                             marker='x')
                    plt.pause(0.1)
                    x, y = new_occluder_state_dict[
                        self.occluded_by].bonding_box_poly.exterior.xy
                    plt.plot(x, y, 'k')
                    plt.pause(0.1)
Beispiel #12
0
def autoViewTwoWallPerspective(room, scene):
    fov = scene['PerspectiveCamera']['fov']
    # change the fov/2 to Radian.
    theta = (np.pi * fov / 180) / 2
    focal = 1 / np.tan(theta)
    tanPhi = ASPECT / focal
    floorMeta = p2d(
        '.', '/dataset/room/{}/{}f.obj'.format(room['origin'],
                                               room['modelId']))
    floorPoly = Polygon(floorMeta[:, 0:2])
    H = sk.getWallHeight(
        f"./dataset/room/{room['origin']}/{room['modelId']}w.obj")
    pcams = []
    for wallDiagIndex in range(floorMeta.shape[0]):
        pcam = {}
        iPre = (wallDiagIndex + floorMeta.shape[0] - 1) % floorMeta.shape[0]
        iNxt = (wallDiagIndex + 1) % floorMeta.shape[0]
        iPreP = floorMeta[iPre][0:2]
        iNxtP = floorMeta[iNxt][0:2]
        # extend two walls as far as possible:
        preList = []
        nxtList = []
        for i in range(floorMeta.shape[0]):
            if i == iPre or i == wallDiagIndex:
                continue
            p3 = floorMeta[i][0:2]
            p4 = floorMeta[(i + 1) % floorMeta.shape[0]][0:2]
            _p = twoInfLineIntersection(floorMeta[wallDiagIndex][0:2], iPreP,
                                        p3, p4)
            if _p is None:
                continue
            _p = np.array(_p)
            if np.dot(_p - floorMeta[wallDiagIndex][0:2],
                      floorMeta[wallDiagIndex][2:4]) < 0:
                continue
            preList.append(_p)
        for i in range(floorMeta.shape[0]):
            if i == iPre or i == wallDiagIndex:
                continue
            p3 = floorMeta[i][0:2]
            p4 = floorMeta[(i + 1) % floorMeta.shape[0]][0:2]
            _p = twoInfLineIntersection(floorMeta[wallDiagIndex][0:2], iNxtP,
                                        p3, p4)
            if _p is None:
                continue
            _p = np.array(_p)
            if np.dot(_p - floorMeta[wallDiagIndex][0:2],
                      floorMeta[iPre][2:4]) < 0:
                continue
            nxtList.append(_p)
        MAXdis = -1
        for pl in preList:
            for nl in nxtList:
                if checkPtoN(pl, nl, floorMeta):
                    dis = np.linalg.norm(pl - nl)
                    if MAXdis < dis:
                        MAXdis = dis
                        iPreP = pl
                        iNxtP = nl
        direction = iNxtP - iPreP
        direction = direction[[1, 0]]
        direction[1] = -direction[1]
        direction /= np.linalg.norm(direction, ord=2)
        probe = (iNxtP + iPreP) / 2
        if np.dot(direction, floorMeta[wallDiagIndex][0:2] - probe) < 0:
            direction = -direction
        dis = np.linalg.norm(probe - iNxtP, ord=2) / tanPhi
        probe = probe - direction * dis
        pcam['viewLength'] = np.linalg.norm(probe -
                                            floorMeta[wallDiagIndex][0:2],
                                            ord=2)
        if not floorPoly.contains(Point(probe[0], probe[1])):
            p1 = probe
            p2 = probe + direction * dis
            _plist = []
            for i in range(floorMeta.shape[0]):
                p3 = floorMeta[i][0:2]
                p4 = floorMeta[(i + 1) % floorMeta.shape[0]][0:2]
                _p = twoInfLineIntersection(p1, p2, p3, p4)
                if _p is None:
                    continue
                if np.dot(direction, np.array(_p) - p2) > 0:
                    continue
                _plist.append(_p)
            if len(_plist) > 0:
                _i = np.argmin(np.linalg.norm(np.array(_plist), axis=1))
                probe = _plist[_i]
        else:
            probe = probe.tolist()
        if not floorPoly.contains(Point(probe[0], probe[1])):
            continue
        probe.insert(1, H / 2)
        probe = np.array(probe)
        direction = direction.tolist()
        direction.insert(1, 0)
        direction = groundShifting(probe, floorMeta, floorPoly,
                                   np.array(direction), theta, H)
        pcam['probe'] = probe
        pcam['direction'] = direction
        pcam['theta'] = theta
        pcam['roomId'] = room['roomId']
        pcam['wallDiagIndex'] = wallDiagIndex
        pcam['type'] = 'twoWallPerspective'
        pcam['floorMeta'] = floorMeta
        pcams.append(pcam)
    return pcams
Beispiel #13
0
				elif d["geometry"]["type"] == "Polygon":
					mean = get_mean(d["geometry"]["coordinates"][0])

				d.pop("geometry")
				d["GeoCoordinate"] = {"longitude" : mean[0], "latitude" : mean[1]}

				listOfStations.append(d)
		for d_i, d in enumerate(data):
			if "railway" in d and not "station" in d["railway"]:
				if "geometry" in d:
					poly = np.array(d["geometry"]["coordinates"])
					poly = LineString(poly if len(poly.shape) == 2 else poly[0])
					geom = ops.transform(tr.transform, poly)

					for r in listOfStations:
						circle = Point([r["GeoCoordinate"]["longitude"],r["GeoCoordinate"]["latitude"]])
						circle = ops.transform(tr.transform, circle)
						circle = Point(circle).buffer(100).boundary
						i = circle.intersection(geom)
						if not i.is_empty:
							if "stations" in d:
								d["stations"].append(r["@id"])
							else:
								d["stations"] = [r["@id"]]

					if "stations" in d:
						print(len(d["stations"]))
				
		for d_i, d in enumerate(data):
			if "geometry" in d:
				multicoordAllineation(d)