def set_center(self, center_point: Point2D): self.__center = center_point half_width = self.width / 2 half_height = self.height / 2 self.bl = Point2D(center_point.x - half_width, center_point.y - half_height) self.tl = Point2D(center_point.x - half_width, center_point.y + half_height) self.tr = Point2D(center_point.x + half_width, center_point.y + half_height) self.br = Point2D(center_point.x + half_width, center_point.y - half_height) self.shape = Rectangle((self.bl.x, self.bl.y), self.width, self.height, fill=False)
def quick_hull(self): ''' time O(nlogn) :return: ''' l = Point2D(100, 0) r = Point2D(-100, 0) # find the most right and left point for point in self.point_list: l = point if point < l else l r = point if point > r else r self.hull.append(l) self.hull.append(r) self.left = l self.right = r rightside_l_r = [] # the points on the right side of (l -> r) rightside_r_l = [] # the points on the right side of (r -> l) for point in self.point_list: # seperate point_list to rightside_l_r and rightside_r_l cp = self.cross_product(l, r, point) if cp > 0: # on the right side of (r->l) rightside_r_l.append(point) elif cp < 0: # on the right side of (l->r) rightside_l_r.append(point) self.find_hull(rightside_l_r, l, r) length = len(self.hull) l_to_r = self.hull[2:] list.sort(l_to_r) self.find_hull(rightside_r_l, r, l) r_to_l = self.hull[length:] list.sort(r_to_l, reverse=True) self.sorted_hull = [self.left] + l_to_r + [self.right ] + r_to_l + [self.left] return self.hull
def __load_out(self, filepath): ''' Load the content of a .out file Attributes: filepath (string) : path to the .out file ''' # Get the content of the file reader = OutReader(filepath) cameras_json, points3D_json = reader.get_file_content() del reader # Create the cameras for cam_id, cam_data in enumerate(cameras_json): camera = Camera(cam_id) camera.set_focal(float(cam_data['cam_intr'][0])) # Set focal camera.set_radial_distortion_params(k1=float(cam_data['cam_intr'][1]), # Set radial distortion k2=float(cam_data['cam_intr'][2])) camera.set_rotation_matrix(R = np.matrix(cam_data['R'], dtype = np.float), # Set rotation matrix format = GeometrySettings.RotationMatrixType.BUNDLER_OUT) camera.set_translation_vector(t = np.matrix(cam_data['t'], dtype = np.float).reshape(-1,1), # Set the translation vector format = GeometrySettings.TranslationVectorType.BUNDLER_OUT) logger.debug('New {}'.format(camera)) self.__cameras[cam_id] = camera # Create points3D and points2D (observations) p2D_id = 0 for p3D_id, p3D_data in enumerate(points3D_json): p3D = Point3D(p3D_id) p3D.set_coordinates(np.matrix(p3D_data['xyz'], dtype = np.float).reshape(-1,1)) # Position (column vector) and color (row vector) p3D.set_color_rgb(np.array(p3D_data['rgb'], dtype = np.int)) observations = self.__parse_observation_string(p3D_data['obs'], 'out') # 2D observations: camera-id keypoint-index x y for observation in observations: p2D = Point2D(p2D_id) p2D.set_keypoint_index(int(observation['cam_id']), int(observation['kp_index'])) p2D.set_coordintes(np.matrix([float(observation['x']), float(observation['y'])]).reshape(-1,1)) p2D.set_point3D(int(p3D_id)) p3D.set_observation(self.__cameras[observation['cam_id']].get_id(), p2D_id) # Add 2D observation id to the point3D self.__cameras[observation['cam_id']].add_visible_point3D(p3D_id) # Add point3D to the visible points of the camera logger.debug('New {}'.format(p2D)) self.__points2D[p2D_id] = p2D p2D_id += 1 logger.debug('New {}'.format(p3D)) self.__points3D[p3D_id] = p3D
def __init__(self, **kwargs): self.point_list = [] self.point_x_list = [] self.point_y_list = [] if 'filepath' in kwargs.keys(): with open(kwargs['filepath'], newline='') as file: csvreader = csv.reader(file, delimiter=',') for entry in csvreader: point = Point2D(float(entry[0]), float(entry[1])) self.point_list.append(point) self.point_x_list.append(point.x) self.point_y_list.append(point.y) file.close() self.point_x_list = np.asarray(self.point_x_list) self.point_y_list = np.asarray(self.point_y_list) elif 'num' in kwargs.keys(): self.point_x_list = np.random.randn(kwargs['num']) self.point_y_list = np.random.randn(kwargs['num']) for _x, _y in zip(self.point_x_list, self.point_y_list): point = Point2D(_x, _y) self.point_list.append(point)
def draw_hull(self): x = [point.x for point in self.sorted_hull] y = [point.y for point in self.sorted_hull] _x = np.asarray(x) _y = np.asarray(y) point = Point2D(2, 3) print(self.is_in_hull(point)) p_x = np.asarray([point.x]) p_y = np.asarray([point.y]) plt.scatter(p_x, p_y, color='red', s=2, alpha=1) plt.title('Points and Convex Hull') plt.scatter(self.points.point_x_list, self.points.point_y_list, alpha=0.5, s=2, marker='o') plt.plot(_x, _y, color='g', linewidth=0.2) plt.show()
def place_photos_in_curve(photo_list, blp, trp, photo_space, point_unit, curve_coefficient): coordinate_generator = CoordinateGenerator(blp.x, trp.x, bl.y, tr.y, point_unit) photos_left = list(photo_list) pos = 0 coord = coordinate_generator.get_start() plan = {} while coord is not None: progressBar.print_progress_bar(pos, len(photo_list), prefix='Progress:', suffix='Complete', length=100) # Set the current coordinates x_curr = coord[0] y_curr = coord[1] if curve.is_point_in_curve(Point2D(x_curr, y_curr), curve_coefficient): for photo in photos_left: # Assign the corners of the photo photo.set_center(Point2D(x_curr, y_curr)) # Skip if all the corners are not in the curve if not photo.is_in_curve(curve_coefficient): # Clear the coordinates previously set to avoid corruption photo.clear_coords() continue """ At this point, the photo fits in the curve. """ # Get the coordinates the photo crosses including the external edge photo_coordinate_indexes_external = photo.get_indexes( external=True) error = False for photo_coordinate_index in photo_coordinate_indexes_external: # Add an empty list for a given key if it isn't in the plan yet if photo_coordinate_index not in plan.keys(): plan[photo_coordinate_index] = [] for neighbour in plan[photo_coordinate_index]: if photo.overlap_with(neighbour): error = True break if photo.too_close(neighbour, photo_space): error = True break # Create a list of neighbours photo.neighbours.add(neighbour) if error: break if error: photo.clear_coords() photo.neighbours.clear() continue """ At this point, the photo is not too close nor overlapping any of the photos around. """ left = set() right = set() top = set() for neighbour in photo.neighbours: if neighbour.on_the_left_of(photo) and \ photo.has_close_left_neighbour(neighbour, photo_space): left.add(neighbour) if neighbour.on_the_right_of(photo) and \ photo.has_close_right_neighbour(neighbour, photo_space): right.add(neighbour) if neighbour.on_the_top_of(photo) and \ photo.has_close_top_neighbour(neighbour, photo_space): top.add(neighbour) left = sorted(left, key=lambda photo_key: math.fabs(photo_key.br.x - photo.bl.x)) right = sorted(right, key=lambda photo_key: math.fabs(photo_key.bl.x - photo.br.x)) top = sorted(top, key=lambda photo_key: math.fabs(photo_key.bl.y - photo.tl.y)) side = coordinate_generator.get_curve_side(x_curr) if ((side == Side.LEFT and len(right) > 0) or (side == Side.RIGHT and len(left) > 0) or side == Side.MIDDLE): if side == Side.LEFT: x_temp = right[0].bl.x - photo_space - photo.width / 2 elif side == Side.RIGHT: x_temp = left[0].br.x + photo_space + photo.width / 2 else: x_temp = x_curr if len(top) > 0: y_temp = top[0].bl.y - photo_space - photo.height / 2 else: y_temp = y_curr photo.set_center(Point2D(x_temp, y_temp)) photo_fits = True if not photo.is_in_curve(curve_coefficient): photo_fits = False while photo_fits: for neighbour in photo.neighbours: if photo.overlap_with( neighbour) or photo.too_close( neighbour, photo_space): photo_fits = False break if photo_fits: x_curr = x_temp y_curr = y_temp else: photo.set_center(Point2D(x_curr, y_curr)) for photo_coordinate_index in photo.get_indexes( external=False): plan[photo_coordinate_index].append(photo) x_curr, y_curr = coordinate_generator.get_next_point_after_photo( x_curr, y_curr, photo) photo.position = pos pos += 1 plot_photo(photo) photos_left.remove(photo) break if len(photos_left) == 0: break coord = coordinate_generator.get_next_point(x_curr, y_curr) return [p for p in photo_list if p not in photos_left]
# axs.grid(True, which='both') axs.axis('equal') # this locator puts ticks at regular intervals # loc = plticker.MultipleLocator(base=1.0) # axs.xaxis.set_major_locator(loc) # axs.yaxis.set_major_locator(loc) # random.shuffle(photos) # set_photos_name(photos) ts = np.linspace(-np.pi, np.pi, num=100) xs = curve.curve_x_function(ts, CURVE_COEFFICIENT) ys = curve.curve_y_function(ts, CURVE_COEFFICIENT) bl = Point2D(min(xs), min(ys)) tr = Point2D(max(xs), max(ys)) list_of_photo_list = extract_binary() photo_list = list_of_photo_list[500] progressBar.print_progress_bar(0, len(photo_list), prefix='Progress:', suffix='Complete', length=100) external_heart = Rectangle((bl.x, bl.y), abs(tr.x - bl.x), abs(tr.y - bl.y),
if ((not self._continuedForFirst) and (((p - self._firstPoint)^(self._secondPoint - self._firstPoint)) < T(0))): #print('isOnSegment fail:', ((p - self._firstPoint)^(self._secondPoint - self._firstPoint))) return False #print('isOnSegment: test3') if ((not self._continuedForSecond) and (((p - self._secondPoint)^(self._firstPoint - self._secondPoint)) < T(0))): return False #print('isOnSegment: OK') return True def isOnSegmentFloat(self, p): assert False, 'Not implemented yet' def isOnSegmentRational(self, p): assert False, 'Not implemented yet' def splitByPoint(self, delim): assert False, 'Not implemented yet' if __name__ == '__main__': segment = GeneralizedSegment(Point2D(0, 1), Point2D(2, 1), False, True) print(segment.isOnSegment(Point2D(1, 1))) print(segment.isOnSegment(Point2D(-1, 1))) print(segment.isOnSegment(Point2D(3, 1))) print(segment.isOnSegment(Point2D(2, 1))) print(segment.isOnSegment(Point2D(1, 2)))
def draw_hull(self): x = [point.x for point in self.sorted_hull] y = [point.y for point in self.sorted_hull] _x = np.asarray(x) _y = np.asarray(y) point = Point2D(2, 3) print(self.is_in_hull(point)) p_x = np.asarray([point.x]) p_y = np.asarray([point.y]) plt.scatter(p_x, p_y, color='red', s=2, alpha=1) plt.title('Points and Convex Hull') plt.scatter(self.points.point_x_list, self.points.point_y_list, alpha=0.5, s=2, marker='o') plt.plot(_x, _y, color='g', linewidth=0.2) plt.show() if __name__ == '__main__': points = CreatePoints(num=1000) points.write_to_csv('points.csv') qh = QuickHull(points) qh.quick_hull() qh.is_in_hull(Point2D(2, 3)) qh.draw_hull()