def hough_to_sympy(x): r, theta = x[0][0], x[0][1] a = np.cos(theta) b = np.sin(theta) x0, y0 = a * r, b * r return sp.Line(sp.Point(x0 + 2000. * b, y0 - 2000. * a), sp.Point(x0 - 2000. * b, y0 + 2000. * a))
def find_circles_tangent(circle1: myCircle, circle2: myCircle) -> tuple: # r0 -> a, b # r1 -> c, d if (circle1.intersect(circle2) or circle1.encloses(circle2)): log.warn("Tangents don't exist") return tuple() x_p = (circle1.radius * circle2.center.x + circle2.radius * circle1.center.x) / (circle1.radius + circle2.radius) y_p = (circle1.radius * circle2.center.y + circle2.radius * circle1.center.y) / (circle1.radius + circle2.radius) log.info(f'Tangents intersection ({x_p}, {y_p})') try: xt_1, xt_2 = get_x_out(circle1, x_p, y_p) yt_1, yt_2 = get_y_out(circle1, x_p, y_p) except Exception as e: return tuple() xt_3, xt_4 = get_x_inner(circle2, x_p, y_p) yt_3, yt_4 = get_y_inner(circle2, x_p, y_p) log.info(f'First tangent ({xt_1}, {yt_1}) ({xt_3}, {yt_3})') log.info(f'Second tangent ({xt_2}, {yt_2}) ({xt_4}, {yt_4})') return ((sy.Point(xt_1, yt_1), sy.Point(xt_3, yt_3)), (sy.Point(xt_2, yt_2), sy.Point(xt_4, yt_4)), (x_p, y_p))
def get_area(self) -> float: if (self.area is not None): return self.area left_quad_area = quadrangle_area(self.circle1.center, self.tangent1[0], sy.Point(self.i_p[0], self.i_p[1]), self.tangent2[0]) right_quad_area = quadrangle_area(self.circle2.center, self.tangent1[1], sy.Point(self.i_p[0], self.i_p[1]), self.tangent2[1]) log.debug( f'coord1 {self.tangent1[0]} {self.tangent2[0]} {self.circle1.center} {sy.Point(self.i_p[0], self.i_p[1])}' ) log.debug( f'coord2 {self.tangent1[1]} {self.tangent2[1]} {self.circle2.center} {sy.Point(self.i_p[0], self.i_p[1])}' ) log.info( f"Area: {left_quad_area} + {right_quad_area} = {left_quad_area + right_quad_area}" ) self.area = abs(left_quad_area - right_quad_area) return self.area
def test_shapely(self): self.assertEqual( point_line_dist(Point(0, 2), Point(0, 0), Point(1, 1)), LineString([(0, 0), (1, 1)]).project(shapely.geometry.Point(0, 2))) self.assertEqual( sympy.Line(sympy.Point(10, 10), sympy.Point(41, -1)).projection( sympy.Point(0.1, 2.3)).distance(sympy.Point(0.1, 2, 3)), LineString([(0, 0), (1, 1)]).project(shapely.geometry.Point(0, 2)))
def generate_hand_ray(center_point, edge): center = sp.Point(center_point) first = sp.Point(edge[0:2]) second = sp.Point(edge[2:4]) first_dist = center.distance(first) second_dist = center.distance(second) return sp.Ray(first, second) if first_dist < second_dist else sp.Ray(second, first)
def read_dial(config, idx, img): offset, clockwise = config offset_r = offset * (np.pi / 180) height, width = img.shape[:2] center = [width / 2, height / 2] radius = int(width / 2) circle = sp.Circle(sp.Point(center), radius) offset_ray = sp.Ray(sp.Point(center), angle=mp.radians(offset)) offset_img = img.copy() origin_point = [center[0], 0] offset_point = [ math.cos(offset_r) * (origin_point[0] - center[0]) - math.sin(offset_r) * (origin_point[1] - center[1]) + center[0], math.sin(offset_r) * (origin_point[0] - center[0]) + math.cos(offset_r) * (origin_point[1] - center[1]) + center[1] ] cv2.line(offset_img, (int(center[0]), int(center[1])), (int(offset_point[0]), int(offset_point[1])), (0, 255, 0), 2) write_debug(offset_img, f"dial-{idx}") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) write_debug(blurred, f"blurred-{idx}") edges = cv2.Canny(blurred, 50, 200) write_debug(edges, f"edges-{idx}") edge = find_hand_edge(edges) hand_edge_img = img.copy() cv2.line(hand_edge_img, (edge[0], edge[1]), (edge[2], edge[3]), (0, 255, 0), 2) write_debug(hand_edge_img, f"hand-edge-{idx}") hand_ray = generate_hand_ray(center, edge) circle_intersection = hand_ray.intersection(circle)[0] cv2.line(img, (int(center[0]), int(center[1])), (int(circle_intersection.x), int(circle_intersection.y)), (0, 0, 255), 2) write_debug(img, f"intersection-{idx}") angle_r = math.atan2(circle_intersection.y - center[1], circle_intersection.x - center[0]) - math.atan2( origin_point[1] - center[1], origin_point[0] - center[0]) angle = angle_r * 180 / np.pi if angle < 0: angle = 360 + angle angle_p = angle / 360 if not clockwise: angle_p = 1 - angle_p return int(10 * angle_p)
def get_l_focal(hue=45): """ hueから L_focal を得る """ # まずは L_cusp を求める # --------------------- lab_709, lab_2020, rgb = get_lab_edge(hue) chroma_709 = get_chroma(lab_709) chroma_2020 = get_chroma(lab_2020) bt709_cusp_idx = np.argmax(chroma_709) bt2020_cusp_idx = np.argmax(chroma_2020) bt709_point = sympy.Point(chroma_709[bt709_cusp_idx], lab_709[bt709_cusp_idx, 0]) bt2020_point = sympy.Point(chroma_2020[bt2020_cusp_idx], lab_2020[bt2020_cusp_idx, 0]) chroma_line = sympy.Line(bt709_point, bt2020_point) lightness_line = sympy.Line(sympy.Point(0, 0), sympy.Point(0, 100)) intersection = sympy.intersection(chroma_line, lightness_line)[0].evalf() l_cusp = np.array(intersection) # BT.2407 に従って補正 # --------------------- # plot ax1 = pu.plot_1_graph(fontsize=20, figsize=(10, 8), graph_title=None, graph_title_size=None, xlabel="Chroma", ylabel="Lightness", axis_label_size=None, legend_size=17, xlim=[0, 220], ylim=[0, 100], xtick=None, ytick=None, xtick_size=None, ytick_size=None, linewidth=3) ax1.plot(chroma_709, lab_709[..., 0], c="#808080", label='BT.709') ax1.plot(chroma_2020, lab_2020[..., 0], c="#000000", label='BT.2020') ax1.plot(chroma_709[bt709_cusp_idx], lab_709[bt709_cusp_idx, 0], 'or', markersize=10, alpha=0.5) ax1.plot(chroma_2020[bt2020_cusp_idx], lab_2020[bt2020_cusp_idx, 0], 'or', markersize=10, alpha=0.5) ax1.plot(l_cusp[0], l_cusp[1], 'ok', markersize=10, alpha=0.5) # annotation ax1.annotate(r'L^*_{cusp}', xy=(l_cusp[0], l_cusp[1]), xytext=(l_cusp[0] + 10, l_cusp[1] + 10), arrowprops=dict(facecolor='black', shrink=0.1)) ax1.plot([chroma_2020[bt2020_cusp_idx], l_cusp[0]], [lab_2020[bt2020_cusp_idx, 0], l_cusp[1]], '--k', alpha=0.3) plt.legend(loc='upper right') plt.show()
def bow_circumference(x0c, y0c, x1c, y1c, r): p1 = sy.Point(x0c, y0c) p2 = sy.Point(x1c, y1c) cat = p1.distance(p2) ipo = 2 * r sin_alfa = float(cat / ipo) if sin_alfa > 1: sin_alfa = 1 bow = 2 * nmp.arcsin(sin_alfa) * r return bow
def __init__(self, x1=None, y1=None, x2=None, y2=None, slape=None, obstacle=None): self.x1 = x1 self.y1 = y1 self.p1 = sympy.Point(x1, y1) self.x2 = x2 self.y2 = y2 self.p2 = sympy.Point(x2, y2) self.slape = slape self.obstacle = obstacle
def _find_circle_center(self, start0, start1, end0, end1, radius): """each circle defines all possible coordinates the arc center could be the two circles intersect at the possible centers of the arc radius""" c1 = sp.Circle(sp.Point(start0, start1), abs(radius)) c2 = sp.Circle(sp.Point(end0, end1), abs(radius)) intersection = c1.intersection(c2) if len(intersection) < 1: raise Exception( "radius circles do not intersect") # TODO : proper way of handling GCode error (?) if len( intersection) < 2 or radius > 0: # single intersection or "positive" radius center point return intersection[0].x, intersection[0].y return intersection[1].x, intersection[1].y # "negative" radius center point
def onClick(event): xe, ye = event.xdata, event.ydata if xe and ye: global arrang point = sym.Point(xe, ye) faceIdx = arrang.decomposition.find_face(point) print(faceIdx)
def __init__(self, x, y, radius, estimateRadius=None, key=None): self.x = x self.y = y self.radius = radius #self.area = math.pi * radius**2 self.estimateRadius = estimateRadius self.key = key self.circle = sympy.Circle(sympy.Point(self.x, self.y), radius)
def __init__( self, coord: tuple, set_num: int, ind: int, ) -> None: self.sy_point = sy.Point(coord[0], coord[1], evaluate=False) self.ind = int(ind) self.set_num = int(set_num)
def is_inside_arena(pose): p1, p2, p3, p4 = map(sympy.Point, [(-0.9909883, -4.218833), (-1.92709, 0.9022037), (-7.009388, -1.916794), (-4.107592, -7.078834)]) living_room = sympy.Polygon(p1, p2, p3, p4) person_pose = sympy.Point(pose.pose.position.x, pose.pose.position.y) # Inspection test pose return living_room.encloses_point(person_pose)
def get_l_cusp(hue=0): lab_709, lab_2020, rgb = get_lab_edge(hue) chroma_709 = get_chroma(lab_709) chroma_2020 = get_chroma(lab_2020) bt709_cusp_idx = np.argmax(chroma_709) bt2020_cusp_idx = np.argmax(chroma_2020) bt709_point = sympy.Point(chroma_709[bt709_cusp_idx], lab_709[bt709_cusp_idx, 0]) bt2020_point = sympy.Point(chroma_2020[bt2020_cusp_idx], lab_2020[bt2020_cusp_idx, 0]) chroma_line = sympy.Line(bt709_point, bt2020_point) lightness_line = sympy.Line(sympy.Point(0, 0), sympy.Point(0, 100)) intersection = sympy.intersection(chroma_line, lightness_line)[0].evalf() l_cusp = np.array(intersection) return l_cusp[1]
def onMove(event): xe, ye = event.xdata, event.ydata if xe and ye: global arrang global ax point = sym.Point(xe, ye) fIdx = arrang.decomposition.find_face(point) if fIdx is not None: # explicit, because fIdx could be 0 plot_new_face_with_patch(ax, faceIdx=fIdx)
def intersezione(C,r): x,y=s.symbols('x y') eq=C.equation(x,y) c=r.coefficients m,q=-c[0]/c[1], -c[2]/c[1] eq2=eq.subs(y,m*x+q).as_poly().as_expr() a,b,c=eq2.coeff(x**2), eq2.coeff(x), eq2.subs(x,0) xlist=secondogrado(a,b,c) return [s.Point(x_,m*x_+q) for x_ in xlist]
def get_intersection_primary(out_side_name, in_side_name): """ BT.2020 の Primary と D65 を結ぶ直線と BT.709 の Gamut が交差する点を求める """ bt2020_p, _ = tpg.get_primaries(name=out_side_name) primary, _ = tpg.get_primaries(name=in_side_name) white_point = sympy.Point(tpg.D65_WHITE[0], tpg.D65_WHITE[1]) bt2020_p_points = [ sympy.Point(bt2020_p[x][0], bt2020_p[x][1]) for x in range(3) ] primary_points = [ sympy.Point(primary[x][0], primary[x][1]) for x in range(4) ] bt2020_p_lines = [ sympy.Line(bt2020_p_points[x], white_point) for x in range(3) ] # よく考えたら、どの線と交差するかは gamut の形で決まるんだった…マニュアルで。 # ---------------------------------------------------------------------- primary_lines = [ sympy.Line(primary_points[2], primary_points[3]), sympy.Line(primary_points[1], primary_points[2]), sympy.Line(primary_points[1], primary_points[2]) ] # 交点求める。evalf() して式の評価も済ませておく # ------------------------------------------- intersections = [ sympy.intersection(bt2020_p_lines[x], primary_lines[x])[0].evalf() for x in range(3) ] # 後で扱いやすいように xy の配列に変換しておく # ----------------------------------------- intersections = [[intersections[x].x, intersections[x].y] for x in range(3)] return np.array(intersections)
def setInsects(self, insects: list): self.insects.clear() self.insects.extend(insects) # setting starting point and vector startingPoint = sy.Point(int(self.width / 2), int(self.height / 2), evaluate=False) for insect in self.insects: insect.position = startingPoint insect.vector = Vector().setMagDeg(5, random.randrange(0, 360))
def DPE(self, t): ''' CircleModified class Direct Parametric Equation (x,y) = fd(t)|(xc,yc,rc) ''' fx = self.obj.center.x + self.obj.radius * np.cos(t) # sym.cos(t) fy = self.obj.center.y + self.obj.radius * np.sin(t) # sym.sin(t) return sym.Point(fx.evalf(), fy.evalf())
def DPE(self, t): ''' LineModified class TD: not sure when and how I did this, double-check Direct Parametric Equation (x,y) = df(t) = ( xl + a*t , yl + b*t ) a**2 + b**2 = 1 --> b = sqrt(1-a**2) sl = b/a --> b = a *sl ''' if self.obj.slope == 0: return sym.Point(self.obj.p1.x + t, self.obj.p1.y) elif self.obj.slope == sym.oo or self.obj.slope == -sym.oo: return sym.Point(self.obj.p1.x, self.obj.p1.y + t) else: a = sym.sqrt(self.obj.slope**2 + 1) / (self.obj.slope**2 + 1) b = a * self.obj.slope return sym.Point(self.obj.p1.x + a.evalf() * t, self.obj.p1.y + b.evalf() * t)
def get_intersection_secondary(out_side_name, in_side_name): """ BT.2020 の Secondary と D65 を結ぶ直線と BT.709 の Gamut が交差する点を求める """ secondary, _ = tpg.get_secondaries(name=out_side_name) primary, _ = tpg.get_primaries(name=in_side_name) white_point = sympy.Point(tpg.D65_WHITE[0], tpg.D65_WHITE[1]) secondary_points = [ sympy.Point(secondary[x][0], secondary[x][1]) for x in range(3) ] primary_points = [ sympy.Point(primary[x][0], primary[x][1]) for x in range(4) ] secondary_lines = [ sympy.Line(secondary_points[x], white_point) for x in range(3) ] primary_lines = [ sympy.Line(primary_points[(x + 2) % 3], primary_points[(x + 3) % 3]) for x in range(3) ] # 交点求める。evalf() して式の評価も済ませておく # ------------------------------------------- intersections = [ sympy.intersection(secondary_lines[x], primary_lines[x])[0].evalf() for x in range(3) ] # 後で扱いやすいように xy の配列に変換しておく # ----------------------------------------- intersections = [[intersections[x].x, intersections[x].y] for x in range(3)] return np.array(intersections)
def DPE(self, t): ''' SegmentModified class TD: not sure when and how I did this, double-check Direct Parametric Equation (x,y) = df(t) = ( xl + a*t , yl + b*t ) a**2 + b**2 = 1 --> b = sqrt(1-a**2) sl = b/a --> b = a *sl ''' if self.obj.slope == 0: point = sym.Point(self.obj.p1.x + t, self.obj.p1.y) elif self.obj.slope == sym.oo or self.obj.slope == -sym.oo: point = sym.Point(self.obj.p1.x, self.obj.p1.y + t) else: a = sym.sqrt(self.obj.slope**2 + 1) / (self.obj.slope**2 + 1) b = a * self.obj.slope #TODO:saesha, shouldn't this be a * self.obj.slope point = sym.Point(self.obj.p1.x + a.evalf() * t, self.obj.p1.y + b.evalf() * t) return point if self.obj.contains(point) else False
def generateFood(self, num_food, width, height): self.food.clear() seenCoords = [] for i in range(num_food): coords = (None, None) point = None while True: coords = (random.randrange(0, width), random.randrange(0, height)) point = sy.Point(coords[0], coords[1], evaluate=False) if coords not in seenCoords: seenCoords.append(coords) self.food.append(point) break
def geometry(): ''' API endpoint used to solve the revist geometry problem ''' data = request.get_json() if "input" in data: data = data["input"] points_arr_shape = [] for i in data['shapeCoordinates']: points_arr_shape.append(sympy.Point(i["x"], i["y"])) line_array_shape = [] for i in range(len(points_arr_shape) - 1): line_array_shape.append( sympy.Segment(points_arr_shape[i], points_arr_shape[i + 1])) line_array_shape.append( sympy.Segment(points_arr_shape[0], points_arr_shape[-1])) line_points = [] for i in data['lineCoordinates']: line_points.append(sympy.Point(i["x"], i["y"])) main_line = sympy.Line(line_points[0], line_points[1]) intersections = [] output = [] for i in line_array_shape: res = sympy.geometry.intersection(i, main_line) if (len(res)): res = list(res[0]) output.append({ "x": round(float(res[0]), 2), "y": round(float(res[1]), 2), }) return jsonify(output)
def mouseClick_face_selection(self, event): ''' ''' # print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%( # event.button, event.x, event.y, event.xdata, event.ydata) if event.button == 1: if self.data['arrangement'] != None: point = sym.Point(event.xdata, event.ydata) face_idx = self.data['arrangement'].decomposition.find_face( point) if face_idx != None: self.selected_faces.append(face_idx) self.set_textEdit_face_selection_list() self.arrangement_canvas.highlight_face( self.data['arrangement'], face_idx) elif event.button == 3: # print 'I could wrap up everything here, right?' pass
def is_partnered(coordinates, image, line): """ Given a binary image and a reflecting line, checks if an input pixel has the same value as its reflection across the line iff the original pixel value is 1. If the original value is 1, always returns false Parameters ---------- coordinates : tuple of ints coordinates of the pixel in question. image : 2d numpy array a 2d slice of an image. line : sympy line2d object a 2d sympy line. Returns ------- A logical bit indicating if the values at the both the original and reflected coordinates are 1. """ x, y = coordinates original_val = image[x, y] if original_val == 0: return 0 original_coords = sp.Point(coordinates[0], coordinates[1]) reflected_coords = original_coords.reflect(line) # not always going to be an int, need to coerce rx, ry = round(reflected_coords[0]), round(reflected_coords[1]) try: reflected_val = image[rx, ry] except IndexError: return 0 # print(f'Original: {x},{y} is {original_val}') # print(f'Reflected: {rx},{ry} is {reflected_val}') return int(original_val == reflected_val)
def second_moments(self): """The second moments of area of the polygon. Returns ======= Ix, Iy, Ixy : Second moments of area Examples ======== >>> from sympy import Point, Polygon, S >>> from numpy import arange >>> p=[(cos(i),sin(i)) for i in arange(6)/S.One/3*pi] >>> poly = Polygon(*p) >>> second_moments(poly) (5*sqrt(3)/16, 5*sqrt(3)/16, 0) """ xc, yc = self.centroid.args Ix, Iy, Ixy = 0, 0, 0 args = self.args for i in xrange(len(args)): x1, y1 = args[i - 1].args x2, y2 = args[i].args x1 -= xc x2 -= xc y1 -= yc y2 -= yc v = x1 * y2 - x2 * y1 Ix += v * (y1 * y1 + y1 * y2 + y2 * y2) Iy += v * (x1 * x1 + x1 * x2 + x2 * x2) Ixy += v * (x1 * y2 + 2 * x1 * y1 + 2 * x2 * y2 + x2 * y1) Ix /= 12 Iy /= 12 Ixy /= 24 return sympy.Point(Ix, Iy, Ixy)
def midpoint_as_sympy(self) -> S.Point: return S.Point(self.midpoint.x, self.midpoint.y, self.midpoint.z)
def source_point(self) -> S.Point: return S.Point(*self.source_coords)