def get_intersection_points2D_with_img(intersection_points: list, plane_range: np.ndarray) -> tuple: x, y = intersection_points p1 = Point(x[0], y[0]) p2 = Point(x[1], y[1]) intersection_line = Line(p1, p2) points1 = Point(plane_range[0, 1], plane_range[0, 0]), Point(plane_range[0, 1], plane_range[1, 0]) points2 = Point(plane_range[0, 1], plane_range[1, 0]), Point(plane_range[1, 1], plane_range[1, 0]) points3 = Point(plane_range[1, 1], plane_range[1, 0]), Point(plane_range[1, 1], plane_range[0, 0]) points4 = Point(plane_range[1, 1], plane_range[0, 0]), Point(plane_range[0, 1], plane_range[0, 0]) line1 = Segment(*points1) line2 = Segment(*points2) line3 = Segment(*points3) line4 = Segment(*points4) result = tuple( filter( lambda x: x != [], intersection_line.intersection(line1) + intersection_line.intersection(line2) + intersection_line.intersection(line3) + intersection_line.intersection(line4))) return (float(result[0].x), float(result[0].y)), (float(result[1].x), float(result[1].y))
def find_valid_corners(mat_size, corners): popped = False top_edge_line = Line(Point(0, 0), Point(100, 0)) while corners and corners[0][1] < 0: pt = corners.popleft() left_line = Line(pt, corners[0]) temp_pt = left_line.intersection(top_edge_line) popped = True if popped: first_pt = corners[0] if first_pt[1] != temp_pt[0].y: new_point = (int(temp_pt[0].x), int(temp_pt[0].y)) if new_point[0] != corners[0][0] and new_point[1] != corners[0[1]]: corners.appendleft(new_point) popped = False bottom_edge_line = Line(Point(0, mat_size[1] - 1), Point(100, mat_size[1] - 1)) while corners[-1][1] >= mat_size[1] and len(corners) > 0: pt = corners.pop() left_line = Line(pt, corners[-1]) temp_pt = left_line.intersection(bottom_edge_line) popped = True if popped: first_pt = corners[0] if first_pt[1] != temp_pt[0].y: new_point = (int(temp_pt[0].x), int(temp_pt[0].y)) if new_point[0] != corners[-1][0] and new_point[1] != corners[-1][1]: corners.append(new_point) return corners
def get_polygon(left, right, top, bottom): # convert rays to lines left = Line(left.p1, left.p2) right = Line(right.p1, right.p2) top = Line(top.p1, top.p2) bottom = Line(bottom.p1, bottom.p2) top_left = left.intersection(top)[0] top_right = right.intersection(top)[0] bottom_left = left.intersection(bottom)[0] bottom_right = right.intersection(bottom)[0] return Polygon(top_left, top_right, bottom_right, bottom_left)
def test(f, col=30, n=200): for i in range(0, n): points = [] while True: points = generate_test(col) if points[0] is points[1] or points[0][0] is points[0][ 1] or points[1][0] is points[1][1]: continue l = Line(P(points[0][0], points[0][1]), P(points[1][0], points[1][1])) if len(l.intersection(P(points[2][0], points[2][1]))) != 0: continue break if i % 50 == 0 and i != 0: print('passed {} tests'.format(i)) for j in range(0, 2 * len(points)): point = np.random.randint(0, 25, size=(2)) answer = check(points, point) for k in range(0, len(points) - 1): points.insert(len(points), points[0]) points.remove(points[0]) result = f(points, point) if result is answer: continue print("Test №{} failed".format(i + 1)) print("Expected {}, result {}".format(answer, result)) print("points={}".format(points)) print("point={}".format(point)) draw(points, point) return print("All tests passed")
def locate_puzzle(img, debug=False): # Blurr image to reduce noise in edges thresh = cv.GaussianBlur(img, (3,3), cv.BORDER_REFLECT) param1, param2 = 15, 20 while True: # Canny edge detection edges = cv.Canny(thresh, param1, param2, None, 3) # Dilate and erode edges (from https://stackoverflow.com/questions/48954246/find-sudoku-grid-using-opencv-and-python) edges = cv.dilate(edges, np.ones((3,3),np.uint8), iterations=1) edges = cv.erode(edges, np.ones((5,5),np.uint8), iterations=1) lines = cv.HoughLines(edges, 1, np.pi / 180, 150, None, 0, 0) param1, param2 = param1+5, param2+30 if lines is None: continue if len(lines) <= 35: break # Copy edges to the images that will display the results in BGR cdst = cv.cvtColor(edges, cv.COLOR_GRAY2BGR) # Find four corners of sudoku board poss_corners = [] for i in range(len(lines)): rho = lines[i][0][0] theta = lines[i][0][1] pt1, pt2 = polar_to_points(rho, theta) cv.line(cdst, pt1, pt2, (0,0,255), 3, cv.LINE_AA) p1, p2 = Point(pt1), Point(pt2) l1 = Line(p1, p2) for j in range(len(lines)): if i == j: continue rho = lines[j][0][0] theta = lines[j][0][1] p3, p4 = polar_to_points(rho, theta, return_class=True) l2 = Line(p3, p4) p = l1.intersection(l2) if len(p) == 0: continue p = np.array([int(p[0][1]), int(p[0][0])]) if 0 <= p[0] < len(img) and 0 <= p[1] < len(img[1]): poss_corners.append(p) tl = poss_corners[np.argmin(np.array(list(map(euclidean, poss_corners, [[0,0]]*len(poss_corners)))))] tr = poss_corners[np.argmin(np.array(list(map(euclidean, poss_corners, [[0,len(img[0])]]*len(poss_corners)))))] bl = poss_corners[np.argmin(np.array(list(map(euclidean, poss_corners, [[len(img),0]]*len(poss_corners)))))] br = poss_corners[np.argmin(np.array(list(map(euclidean, poss_corners, [[len(img),len(img[0])]]*len(poss_corners)))))] # Idea for warping using imutils: https://www.pyimagesearch.com/2020/08/10/opencv-sudoku-solver-and-ocr/ img = four_point_transform(img, np.array([ [tl[1],tl[0]], [tr[1],tr[0]], [bl[1],bl[0]], [br[1],br[0]]])) if debug: cv.imshow("Lines", cdst) cv.imshow("Cropped", img) cv.waitKey() return img
def extendExWall(P0, P1, l1, msp): l0 = Line(p0, p1) intersectedPoint = l0.intersection(l1) xE, yE = intersectedPoint xS, yS = p1 msp.add_line(((xS, yS, 0), (xE, yE, 0))) l0 = Line(p1, intersectedPoint) return l0
def crossing(p1: Point, p2: Point, p3: Point, p4: Point): line1, seg1 = Line(p1, p2), Segment(p1, p2) line2, seg2 = Line(p3, p4), Segment(p3, p4) intersect = line1.intersection(line2) if intersect: seg1 = Segment(p1, p2) seg2 = Segment(p3, p4) pi = intersect[0] return seg1.contains(pi) and seg2.contains(pi)
def calibrate(self, width, height, top_left, top_right, bottom_left, bottom_right): top_left = self.estimate_average(top_left) top_right = self.estimate_average(top_right) bottom_left = self.estimate_average(bottom_left) bottom_right = self.estimate_average(bottom_right) vertical_left = Line(bottom_left, top_left) vertical_right = Line(bottom_right, top_right) horizontal_top = Line(top_left, top_right) horizontal_bottom = Line(bottom_left, bottom_right) self.abscissa_hinge, = vertical_left.intersection(vertical_right) self.ordinate_hinge, = horizontal_top.intersection(horizontal_bottom) abscissa_low, = vertical_left.intersection(abscissa) abscissa_high, = vertical_right.intersection(abscissa) ordinate_low, = horizontal_bottom.intersection(ordinate) ordinate_high, = horizontal_top.intersection(ordinate) self.to_width = lambda x: width / 4 + width / 2 * ( x - abscissa_low.x) / (abscissa_high.x - abscissa_low.x) self.to_height = lambda y: height / 4 + height / 2 * ( y - ordinate_low.y) / (ordinate_high.y - ordinate_low.y)
def demonstrate_circle_power(circle): """Demonstrate power-of-a-point theorem.""" A, B, C, D = (circle.random_point() for i in range(4)) P = Line.intersection(Line(A, B), Line(C, D)) assert len(P) == 1 P = P[0] PAPB = P.distance(A) * P.distance(B) PCPD = P.distance(C) * P.distance(D) print("PA * PB =", PAPB.evalf()) print("PC * PD =", PCPD.evalf())
def build_graph(self, obstacles: List[Obstacle]): graph = nx.Graph() polygons = [] visited_lines = [] for obst_coords in obstacles: poly = Polygon(*obst_coords) polygons.append(poly) coors_len = len(obst_coords) i = 0 while i < coors_len: c1 = obst_coords[i] try: c2 = obst_coords[i + 1] except IndexError: c2 = obst_coords[-1] if c1 != c2: visited_lines.append(Line(c1, c2)) graph.add_edge(c1, c2) i += 1 coordinates = [] # brute force the rest for obst_coords in obstacles: coordinates.extend(obst_coords) for coord1 in coordinates: for coord2 in coordinates: if coord1 == coord2: continue l = Line(coord1, coord2) if l in visited_lines: continue for poly in polygons: intersect = l.intersection(poly) if len(intersect) > 1: graph.add_edge()
def findPathOld(roada, lanea, roadb, laneb, width, maxRadius=10., midPoint=5): dxa, dya = getRoadUnitVector(roada) dxb, dyb = getRoadUnitVector(roadb) pxa, pya = getOutPoint(roada, width, lanea) pxb, pyb = getInPoint(roadb, width, laneb) pa = Point(pxa, pya) pb = Point(pxb, pyb) da = Point(dxa, dya) db = Point(dxb, dyb) la = Line(pa, pa + da) lb = Line(pb, pb + db) inter = la.intersection(lb) # print(roada, roadb) disa = inter.disntance(pa) disb = inter.disntance(pb) distance = np.min([disa, disb, maxRadius]) ca = pa + da * (disa - distance) cb = pb - db * (disb - distance) o = (ca, ca + da.rotate(pi / 2)).intersection(cb, cb + db.rotate(pi / 2)) oa = ca - o ob = cb - o angle = oa.dot(ob) dangle = angle / midPoint path = [pa] for i in range(midPoint + 1): path.append(o + oa.rotate(dangle * i)) path.append(pb) # ix, iy = computeIntersection(pxa, pya, dxa, dya, pxb, pyb, dxb, dyb) # _width = (dxa * (pxb - pxa) + dya * (pyb - pya)) / 3 # print(dxa, dya, (pxb - pxa), (pyb - pya), _width) # return getOutTurnPoints(roada, _width, lanea, width) + getInTurnPoints(roadb, _width, laneb, width) return list(map(pointToDict2, path))
def get_junction_circle(p0, p1, t0, t1): mid_pt = (p0 + p1) / 2. DEBUG = 'IN_DEBUG' in globals() if DEBUG and IN_DEBUG: plt.plot([float(p0.x), float(p1.x)], [float(p0.y), float(p1.y)], color="#66FFB2", linewidth=0.5) p0tan = mpt.Arrow(float(p0.x), float(p0.y), float(t0.x), float(t0.y), width=0.6, fc="b", ec='none') p1tan = mpt.Arrow(float(p1.x), float(p1.y), float(t1.x), float(t1.y), width=0.6, fc="#2E86C1", ec='none') plt.gca().add_patch(p0tan) plt.gca().add_patch(p1tan) #crc = mpt.Circle([float(mid_pt.x), float(mid_pt.y)], # radius = float(0.2), ec = "k", fill = False) #plt.gca().add_patch(crc) if t1.distance(t0) < 0.0001: # The tangents are equal. We have the "parallelogram" case return mid_pt, -1. bisec1 = get_bisector(p0, p1) bisec2 = get_bisector(p0 + t0, p1 + t1) intr = bisec1.intersection(bisec2) if 0 == len(intr) and t0 == t1: raise ValueError("No intersection for adjacent circle center") #return mid_pt if isinstance(intr[0], Line): if t0 != t1: line0 = Line(p0, p0 + t0) line1 = Line(p1, p1 + t1) circ_cntr = line0.intersection(line1)[0] else: return mid_pt, -1. else: circ_cntr = intr[0] radius = p0.distance(circ_cntr) #if mid_pt.distance(circ_cntr) < 0.0001: # # Half a circle case # bisec_radius_vec = t0 #else: # bisec_radius_vec = Line(circ_cntr, mid_pt).direction.unit #anchor_pt = circ_cntr + bisec_radius_vec * radius DEBUG = 'IN_DEBUG' in globals() if DEBUG and IN_DEBUG: #draw_line(bisec1, "#F5CBA7") #draw_line(bisec2, "#F5CBA7") crc = mpt.Circle( [float(circ_cntr.x), float(circ_cntr.y)], radius=float(radius), ec="#FFCC99", fill=False) plt.gca().add_patch(crc) crc = mpt.Circle( [float(circ_cntr.x), float(circ_cntr.y)], radius=float(0.05), color="#FF9933") plt.gca().add_patch(crc) #plt.axis('equal') #plt.xlim([-5, 20]) #plt.ylim([-15, 10]) #plt.show() return Point(float(circ_cntr.x), float(circ_cntr.y), evaluate=False), \ float(radius) #anchor_pt
def smallest_rectangle(p): # mp.dps = 10 ch = convex_hull(p) print(ch) # Find extreme points x_min_index = 0 y_max_index = uppermost_point_index(ch) x_max_index = rightmost_point_index(ch) y_min_index = lowermost_point_index(ch) # Create vertical and horizontal Rays ray_1 = Ray(ch[x_min_index], angle=pi / 2) ray_2 = Ray(ch[y_min_index], angle=0) ray_3 = Ray(ch[x_max_index], angle=pi / 2) ray_4 = Ray(ch[y_max_index], angle=0) min_rectangle = Polygon((0, 0), (99999999, 0), (99999999, 99999999), (0, 99999999)) rotated_angle = 0 while rotated_angle <= pi / 2: # Convert Rays to lines line_1 = Line(ray_1) line_2 = Line(ray_2) line_3 = Line(ray_3) line_4 = Line(ray_4) # Find the intersections of the lines p1 = line_1.intersection(line_2)[0].evalf() p2 = line_2.intersection(line_3)[0].evalf() p3 = line_3.intersection(line_4)[0].evalf() p4 = line_4.intersection(line_1)[0].evalf() current_rectangle = Polygon(p1, p2, p3, p4) # Calculate the area of the rectangle try: if current_rectangle.area < min_rectangle.area: min_rectangle = current_rectangle except AttributeError: min_rectangle = current_rectangle # Find the next Ray on the convex hull for each Ray in counter clockwise direction next_ray_1 = Ray(ch[x_min_index], ch[get_prev_index(ch, x_min_index)]) next_ray_2 = Ray(ch[y_min_index], ch[get_prev_index(ch, y_min_index)]) next_ray_3 = Ray(ch[x_max_index], ch[get_prev_index(ch, x_max_index)]) next_ray_4 = Ray(ch[y_max_index], ch[get_prev_index(ch, y_max_index)]) #print(ray_1) #print(next_ray_1) # Find the minimal angle to rotate each Ray until one aligns with the convex hull angle_1 = float(positive_angle(next_ray_1.closing_angle(ray_1))) angle_2 = float(positive_angle(next_ray_2.closing_angle(ray_2))) angle_3 = float(positive_angle(next_ray_3.closing_angle(ray_3))) angle_4 = float(positive_angle(next_ray_4.closing_angle(ray_4))) #print(angle_1, angle_2, angle_3, angle_4) min_angle = min(angle_1, angle_2, angle_3, angle_4) # Rotate all Rays around its origin with the angle calculated """ray_1 = ray_1.rotate(min_angle) ray_2 = ray_2.rotate(min_angle) ray_3 = ray_3.rotate(min_angle) ray_4 = ray_4.rotate(min_angle)""" ray_1 = Ray(ray_1.p1, angle=atan(ray_1.slope) + min_angle) ray_2 = Ray(ray_2.p1, angle=atan(ray_2.slope) + min_angle) ray_3 = Ray(ray_3.p1, angle=atan(ray_3.slope) + min_angle) ray_4 = Ray(ray_4.p1, angle=atan(ray_4.slope) + min_angle) # Set the next point in the convex hull as the origin of the Ray that alligned # and decrement the index slope_1 = next_ray_1.slope slope_2 = next_ray_2.slope slope_3 = next_ray_3.slope slope_4 = next_ray_4.slope if min_angle == angle_1: if slope_1 == oo: slope_1 = pi / 2 ray_1 = Ray(next_ray_1.p2, angle=atan(slope_1)) x_min_index = get_prev_index(ch, x_min_index) elif min_angle == angle_2: if slope_2 == oo: slope_2 = pi / 2 ray_2 = Ray(next_ray_2.p2, angle=atan(slope_2)) y_min_index = get_prev_index(ch, y_min_index) elif min_angle == angle_3: if slope_3 == oo: slope_3 = pi / 2 ray_3 = Ray(next_ray_3.p2, angle=atan(slope_3)) x_max_index = get_prev_index(ch, x_max_index) elif min_angle == angle_4: if slope_4 == oo: slope_4 = pi / 2 ray_4 = Ray(next_ray_4.p2, angle=atan(slope_4)) y_max_index = get_prev_index(ch, y_max_index) else: print("fail") rotated_angle += min_angle return min_rectangle
from sympy import Line, Point f=open('D:\UVA\Python\Q378.txt','r') while f: a=f.readline().strip().split(' ') if a ==['']: break p1,p2,p3,p4=Point(int(a[0]),int(a[1])),Point(int(a[2]),int(a[3])),Point(int(a[4]),int(a[5])),Point(int(a[6]),int(a[7])) l1=Line(p1,p2) l2=Line(p3,p4) if l1.is_similar(l2): print("LINE") elif Line.is_parallel(l1,l2): print("NONE") elif Line.are_concurrent(l1,l2): smaepoint= l1.intersection(l2) print("POINT %.2f %.2f " %(smaepoint[0].x,smaepoint[0].y)) print("END OF OUTPUT")
def find_left_and_right_points_on_lines_from_corners(corners, mat_size): corners_tmp = deque(list(map(lambda x: list(map(lambda y: int(y), x)), corners))) assert (len(corners_tmp) == 4) left_top_c_id = 0 for c_id, c in enumerate(corners_tmp): if c[1] < corners_tmp[left_top_c_id][1]: left_top_c_id = c_id elif c[1] == corners_tmp[left_top_c_id][1] and c[0] < corners[left_top_c_id][0]: left_top_c_id = c_id corners = deque([]) for i in list(range(left_top_c_id, len(corners_tmp))) + list(range(0, left_top_c_id)): corners.append(corners_tmp[i]) left_corners, right_corners = deque([]), deque([]) if corners[0][1] == corners[1][1]: left_corners.append(corners[0]) right_corners.append(corners[1]) elif corners[0][1] < corners[1][1]: left_corners.append(corners[0]) right_corners.append(corners[0]) right_corners.append(corners[1]) else: left_corners.append(corners[1]) left_corners.append(corners[0]) right_corners.append(corners[1]) if corners[2][1] == corners[3][1]: right_corners.append(corners[2]) left_corners.append(corners[3]) elif corners[2][1] < corners[3][1]: left_corners.append(corners[3]) right_corners.append(corners[2]) right_corners.append(corners[3]) else: left_corners.append(corners[3]) left_corners.append(corners[2]) right_corners.append(corners[2]) left_corners = find_valid_corners(mat_size, left_corners) right_corners = find_valid_corners(mat_size, right_corners) if not (left_corners and right_corners): return [] assert (left_corners[0][1] == right_corners[0][1]) left1 = left_corners.popleft() left2 = left_corners.popleft() left_line = Line(left1, left2) right1 = right_corners.popleft() right2 = right_corners.popleft() right_line = Line(right1, right2) pts_on_lines = [] # y, left_x, right_x curr_y = left1[1] while True: if curr_y > left2[1]: if not left_corners: break else: left1 = left2 left2 = left_corners.popleft() left_line = Line(left1, left2) if curr_y > right2[1]: if not right_corners: break else: right1 = right2 right2 = right_corners.popleft() right_line = Line(right1, right2) hor_line_with_curr_y = Line(Point(0, curr_y), Point(100, curr_y)) temp_pt = left_line.intersection(hor_line_with_curr_y) left_cross = temp_pt[0] left_x = 0 if left_cross.x < 0 else (left_cross.x if left_cross.x < mat_size[0] else (mat_size[0] - 1)) temp_pt = right_line.intersection(hor_line_with_curr_y) right_cross = temp_pt[0] right_x = 0 if right_cross.x < 0 else (right_cross.x if right_cross.x < mat_size[0] else (mat_size[0] - 1)) pts_on_lines.append((curr_y, int(left_x), int(right_x))) curr_y += 1 return pts_on_lines
Hours = [0] Hours[0] = Time[0] * 24 for i in range(1, len(Time)): Hours.insert(i, Hours[i - 1] + Time[i] * 24) Q_T = [Q_y + (18 - t) / (18 - _.t_calc) * (Q_TTPS - Q_y) for t in Temps] Q_T[-1] = Q_y Q_T.append(Q_y) point_Te = Point(18, 18) # Thermodynamic equilibrium line_Q_Tm = Line(Point(20, _.Q_Tm), Point(Temps[0], _.Q_Tm)) line_2 = Line(Point(18, Q_y), Point(Temps[1], Q_TTPS)) line_3 = Line(point_Te, Point(Temps[1], 150)) line_4 = Line(point_Te, Point(Temps[1], t_os)) point_M = line_Q_Tm.intersection(line_2)[0] point_M1 = line_3.intersection(Line(Point(point_M.x, 0), Point(point_M.x, 150)))[0] point_M11 = line_4.intersection( Line(Point(point_M.x, 0), Point(point_M.x, 150)))[0] point_2 = line_2.intersection(Line(Point(8, 0), Point(8, Q_y)))[0] delta_t = point_M1.distance(point_M11) t_ps = t_os + delta_t if t_psm > t_ps: t_psm = t_ps p_T = IAPWS97(t=t_psm + delta_tsp, x=0).p / 0.9 Q = _.Q_Tm point_N1 = Point(Temps[0], t_ps) else: p_T = _.p_Tm