Esempio n. 1
0
def find_intersections(points, x, y, slope):
    intersection_set = []
    line_segments = []
    for i in range(0, len(points) - 1):
        if points[i].jump:
            continue
        suggested_point = intersection(LineSegment(points[i], points[i + 1]),
                                       stitchcode.Point(x, y), slope)
        if suggested_point is not None:
            if suggested_point == points[i]:
                index = get_surrounding_point_indexes(points, i)
                is_significant_corner = intersection(
                    LineSegment(points[index[0]], points[index[1]]),
                    stitchcode.Point(x, y), slope)
                if is_significant_corner is not None:
                    intersection_set.append(suggested_point)
                else:
                    intersection_set.append(suggested_point)
                    intersection_set.append(
                        stitchcode.Point(suggested_point.x, suggested_point.y))
            elif suggested_point != points[i + 1]:
                intersection_set.append(suggested_point)
    #for n in range(0, len(intersection_set)-1, 2):
    #    line_segments.append(LineSegment(intersection_set[n], intersection_set[n + 1]))
    while len(intersection_set) > 0:
        p1 = find_closest_points(intersection_set)
        line_segments.append(
            LineSegment(intersection_set[0],
                        straight_stitch.copy(intersection_set[p1])))
        if (p1 != 0):
            intersection_set.pop(p1)
        intersection_set.pop(0)
    return line_segments
 def set_hight(self, line):
     self.hight = line
     if (hasattr(self.third_side, 'length') == True):
         self.third_side_sub1 = LineSegment(self.lineSegment1.point1,
                                            self.hight.point1)
         print("self.third_side_sub1.name: ", self.third_side_sub1.name)
         self.third_side_sub1.set_length(self.third_side.length / 2)
         print("self.third_side_sub1.length: ", self.third_side_sub1.length)
         self.third_side_sub2 = LineSegment(self.lineSegment2.point1,
                                            self.hight.point1)
         print("self.third_side_sub2.name: ", self.third_side_sub2.name)
         self.third_side_sub2.set_length(self.third_side.length / 2)
         print("self.third_side_sub2.length: ", self.third_side_sub2.length)
Esempio n. 3
0
 def MDL_cost(self, segments, characteristic_points=[]):
     if len(characteristic_points) is 0:
         #MDLnopar
         LH = 0.0
         for segment in segments:
             LH += segment.length
         if LH != 0.0:
             return np.log2(LH)
         return 0.0
     characteristic_segment = LineSegment(characteristic_points[0],
                                          characteristic_points[1])
     if characteristic_segment.length > 0.0:
         LH = np.log2(characteristic_segment.length)
     else:
         LH = 0.0
     perp_d = 0.0
     ang_d = 0.0
     for segment in segments:
         perp_d += segment.perpendicular_distance(characteristic_segment)
         ang_d += segment.angle_distance(characteristic_segment)
     if perp_d != 0.0:
         perp_d = np.log2(perp_d)
     if ang_d != 0.0:
         ang_d = np.log2(ang_d)
     return LH + perp_d + ang_d
    def find_lines(self,
                   rho=5,
                   theta=np.pi / 180,
                   threshold=15,
                   min_line_len=10,
                   max_line_gap=5):
        """ uses hough transforms to find lines in the image """

        self.find_edges()

        #mask area
        self.mask_road_roi(self.edges_img)

        lines = cv2.HoughLinesP(self.edges_img,
                                rho,
                                theta,
                                threshold,
                                np.array([]),
                                minLineLength=min_line_len,
                                maxLineGap=max_line_gap)

        self.line_segments = LineSegment.create_lines(lines)

        self.lines_img = np.copy(self.image)
        self.draw_lines(self.lines_img, self.line_segments)
def findGlobalCorner(chamferLine, cubeLine, globalCubeLine, pose):
    intersectionPoint = LineSegment.intersectionPt(chamferLine, cubeLine)

    chamferLine = LineSegment(chamferLine.start_point, intersectionPoint)
    cubeLine = LineSegment(cubeLine.start_point, intersectionPoint)

    def lossFun(weight, intersectionPoint, line, pose):
        globalPoint = weight * line.start_point + (1 - weight) * line.end_point
        candidatePoint = pose.projectPointToImage(globalPoint)
        return pose.pointLoss(candidatePoint, intersectionPoint)

    weight = 0
    finalPose = least_squares(lossFun,
                              weight,
                              args=(intersectionPoint, globalCubeLine, pose))
    weight = finalPose.x
    return weight * globalCubeLine.start_point + (
        1 - weight) * globalCubeLine.end_point, intersectionPoint
Esempio n. 6
0
 def average_segments(self, clusters):
     for cluster in clusters:
         av_vector = np.array([0.0, 0.0])
         av_start = np.array([0.0, 0.0])
         for line in cluster:
             av_vector += line.vector
             av_start += line.a
         av_vector /= len(cluster)
         av_start /= len(cluster)
     self.cluster_info.append({"average": LineSegment(av_start, av_start + av_vector), "num": len(cluster)})
Esempio n. 7
0
    def build_line_segments(layout, edges, nodes):
        node_mapping = {node: index for index, node in enumerate(nodes)}

        lines = set()
        for node1 in edges.keys():
            for node2 in edges[node1]:
                lines.add(
                    LineSegment(layout[node_mapping[node1]],
                                layout[node_mapping[node2]]))
        return lines
Esempio n. 8
0
    def representative_trajectory(self, cluster):
        # TODO: Fix this :/
        rep_trajectory = []
        #Average direction vector:
        av_vector = np.array([0.0, 0.0])
        for line in cluster:
            av_vector += line.vector
        av_vector /= len(cluster)
        print(av_vector)
        unit_av = av_vector/np.linalg.norm(av_vector)
        print(unit_av)
        x = np.array([1.0, 0.0])
        theta = np.arccos(x.dot(unit_av))
        if unit_av[1] > 0.0:
            theta = -theta
        rotation_mat = np.array([[np.cos(theta), -np.sin(theta)],
                                 [np.sin(theta), np.cos(theta)]])
        back_rotation_mat = np.array([[np.cos(-theta), np.sin(-theta)],
                              [-np.sin(-theta), np.cos(-theta)]])
        rotated_points = []
        rotated_lines = []
        for line in cluster:
            rot_v = rotation_mat.dot(line.vector)
            rot_b = line.a + line.length*rot_v
            rotated_points.append({"end": False, "point":line.a})
            rotated_points.append({"end": True, "point": rot_b})
            rotated_lines.append(LineSegment(line.a, rot_b))

        rotated_points = sorted(rotated_points, key=lambda x: x["point"][0])
        #Sort lines by starting x value
        line_start_lookup = SortedKeyList(rotated_lines, key=lambda x: x.a[0])
        #Sort lines the sweep line crosses by ending x value
        intersecting_lines = SortedKeyList([], key=lambda x:x.b[0])
        last_x = 0.0
        for point_dict in rotated_points:
            if point_dict["end"]:
                try:
                    intersecting_lines.pop(0)
                except Exception as e:
                    print("Could not generate a representative trajectory. Examine your clustering parameters")
                    break;
            else:
                intersecting_lines.add(line_start_lookup.pop(0))
            if len(intersecting_lines) >= self.min_lns:
                # diff = point_dict["point"][0] - last_x
                # if diff >= self.gamma:
                average_y = 0.0
                for line in intersecting_lines:
                    slope = line.vector[1]/line.vector[0]
                    average_y += (point_dict["point"][0]-line.a[0])*slope
                average_y /= len(intersecting_lines)
                rep_trajectory.append(np.array([point_dict["point"][0], average_y]))
        return rep_trajectory
Esempio n. 9
0
    def addSegment(self, point, turnRadius):
        point = np.array(point)
        if len(self.segments) is 0:
            self.segments.append(LineSegment(np.array([0,0]), point, 0, config.CONSTANT_VELOCITY, config.ACCEL))
        else:
            prev = self.segments[-1]
            # We don't want to change velocity constraints on the first segment, but
            # any addition segments need to have velocity constraints adjusted because
            # they are added with a vf of 0
            if len(self.segments) is not 1:
                prev.setVelocityConstraints(config.CONSTANT_VELOCITY, config.CONSTANT_VELOCITY, 0)

            vecB = point - prev.start

            # Arc to the goal point with a set turn radius
            # AB = The previous path vector segment 
            # C = new goal point
            # Then the sign of AB (cross) AC determines the direction of the arc
            self.segments.append(ArcSegment(point, turnRadius, np.cross(prev.vector(), vecB) > 0))
            # Add this segment assuming its the last one in the path
            self.segments.append(LineSegment(prev.stop, point, config.CONSTANT_VELOCITY, 0, config.ACCEL))
    def __init__(self, points):
        assert isinstance(points, list) and all(
            isinstance(p, Point) for p in points)
        self.V = points

        # check if points assume general position
        # assert self.is_general_position, 'Input points must have distinct x-coordinates'

        # create edges and randomize
        self.E = []
        for i, p in enumerate(points):
            self.E.append(LineSegment(p, points[(i + 1) % len(points)]))
Esempio n. 11
0
class Isosceles_triangle:
    def __init__(self, lineSegment1, lineSegment2):
        self.lineSegment1 = lineSegment1
        self.lineSegment2 = lineSegment2

    def set_third_side(self, lineSegment3):
        self.third_side = lineSegment3

    def set_hight(self, line):
        self.hight = line
        if (hasattr(self.third_side, 'length') == True):
            self.third_side_sub1 = LineSegment(self.lineSegment1.point1,
                                               self.hight.point1)
            print("self.third_side_sub1.name: ", self.third_side_sub1.name)
            self.third_side_sub1.set_length(self.third_side.length / 2)
            print("self.third_side_sub1.length: ", self.third_side_sub1.length)
            self.third_side_sub2 = LineSegment(self.lineSegment2.point1,
                                               self.hight.point1)
            print("self.third_side_sub2.name: ", self.third_side_sub2.name)
            self.third_side_sub2.set_length(self.third_side.length / 2)
            print("self.third_side_sub2.length: ", self.third_side_sub2.length)
Esempio n. 12
0
    def setPoint_on_circle(self, point):

        self.pointlist.append(point)
        if (len(self.pointlist) >= 2):
            self.line_segment = LineSegment(
                self.pointlist[len(self.pointlist) - 2],
                self.pointlist[len(self.pointlist) - 1])
            print("The circle's arc line segment's name is: ",
                  self.line_segment.name)
            self.isosceles_triangle = Isosceles_triangle(
                LineSegment(self.pointlist[len(self.pointlist) - 2],
                            self.center),
                LineSegment(self.pointlist[len(self.pointlist) - 1],
                            self.center))
            self.isosceles_triangle.lineSegment1.set_length(self.radius)
            self.isosceles_triangle.lineSegment2.set_length(self.radius)
            self.isosceles_triangle.set_third_side(self.line_segment)
            print(
                "There is a isosceles_triangle in the circle: one equal side is:",
                self.isosceles_triangle.lineSegment1.name,
                " and the other equal side is",
                self.isosceles_triangle.lineSegment2.name)
            print("the isosceles_triangle's two equal side length is ",
                  self.isosceles_triangle.lineSegment2.length)
Esempio n. 13
0
def connect(points, start, stop):
    path = []
    found_start = False
    found_stop = False
    found_start_first = False
    count = 0
    while count < (len(points) * 2):
        i = count % (len(points) - 1)
        if is_along(LineSegment(points[i], points[i + 1]), start, 1):
            found_start = True
            if not found_stop:
                found_start_first = True
        if is_along(LineSegment(points[i], points[i + 1]), stop, 1):
            found_stop = True
        if found_start or found_stop:
            path.append(straight_stitch.copy(points[i]))
        if found_start and found_stop:
            break
        count = count + 1
    if not found_start_first:
        path.reverse()
    if found_start and found_stop:
        return path
    return []
Esempio n. 14
0
 def calculate_right_lane(self, right_lines):
     if right_lines:
         m, b = self.calculate_average_line(right_lines)
         self.right_line = LineSegment.from_slope_equation(
             m, b, self.min_y, self.max_y)
Esempio n. 15
0
 def create_line_with_point(self, point):
     return LineSegment(self, point)
Esempio n. 16
0
from Circle import Circle
from Point import Point
from LineSegment import LineSegment
import math
def prependicular(line1,line2):
    return True



point_list = []
circle =Circle('O')
circle.set_radius(5)
point_list.append(Point('A'))
point_list.append(Point('B'))
circle.setPoint_on_circle(point_list[0])
circle.setPoint_on_circle(point_list[1])
for element in circle.pointlist:
    print("The point on the circle is: ", element.name)
point_list.append(Point('C'))
circle.line_segment.set_on_line_point(point_list[len(point_list)-1])
circle.line_segment.set_length(6)
if(LineSegment(point_list[2],circle.center).name=='CO'):
    if(prependicular(LineSegment(point_list[2],circle.center),circle.line_segment)==True):
        if(hasattr(circle, 'isosceles_triangle')):
            circle.isosceles_triangle.set_hight(LineSegment(point_list[2],circle.center))
            print("iso triangle's hight is: ",circle.isosceles_triangle.hight.name)


print("the circle's line_segment's sublinesegment1 is: ",circle.line_segment.sublineSegment1.name)
print("the circle's line_segment's sublinesegment2 is: ",circle.line_segment.sublineSegment2.name)
print("CO's length is",math.sqrt((circle.isosceles_triangle.lineSegment1.length)**2-(circle.isosceles_triangle.third_side_sub1.length)**2))
    print(image_name)
    file = np.load(image_name + '.npy', allow_pickle=True)
    points = []
    detectedHoughLines = []

    for num, line in enumerate(file):
        rho, theta = line[-3:-1]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0 + 10000 * (-b))
        y1 = int(y0 + 10000 * (a))
        x2 = int(x0 - 10000 * (-b))
        y2 = int(y0 - 10000 * (a))
        detectedHoughLines.append(LineSegment((x1, y1), (x2, y2)))

    file = np.load(image_name + '_chamfer.npy')
    points = []
    chamferLines = []

    for line in file:
        rho, theta = line[-3:-1]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0 + 10000 * (-b))
        y1 = int(y0 + 10000 * (a))
        x2 = int(x0 - 10000 * (-b))
        y2 = int(y0 - 10000 * (a))
Esempio n. 18
0
 def calculate_left_lane(self, left_lines):
     if left_lines:
         m, b = self.calculate_average_line(left_lines)
         self.left_line = LineSegment.from_slope_equation(
             m, b, self.min_y, self.max_y)
Esempio n. 19
0
 def trajectory_partition(self, trajectory):
     """
     Input: A trajectory T Ri = p1p2p3 · · · pj · · · pleni
     Output: A set CPi of characteristic points
     Algorithm:
     01: Add p1 into the set CPi; /* the starting point */
     02: startIndex := 1, length := 1;
     03: while (startIndex + length ≤ leni) do
     04: currIndex := startIndex + length;
     05: cost_par := MDL_par(pstartIndex, pcurrIndex);
     06: cost_nopar := MDL_nopar(pstartIndex, pcurrIndex);
     /* check if partitioning at the current point makes
     the MDL cost larger than not partitioning */
     07: if (costpar > costnopar) then
     /* partition at the previous point */
     08: Add pcurrIndex−1 into the set CPi;
     09: startIndex := currIndex − 1, length := 1;
     10: else
     11: length := length + 1;
     12: Add pleni
     into the set CPi; /* the ending point */
     (Lee, Han, & Whang, 2007)
     """
     start_index = 0
     length = 1
     characteristic_points = []
     segments = []
     last_point = None
     for point in trajectory:
         if last_point is not None:
             segments.append(LineSegment(last_point, point))
         last_point = point
     segments = np.array(segments)
     characteristic_points.append(trajectory[0])
     while start_index + length < len(trajectory):
         curr_index = start_index + length
         """
         MDL_par denotes the MDL Cost of a trajectory between p_i and p_j,
         when assuming that p_i and p_j are the only characteristic points.
         MDL_nopar denotes the MDL cost when assuming there is no characteristic
         point between the two, i.e preserving the original trajectory.
         """
         cost_par = self.MDL_cost(
             segments[start_index:curr_index],
             [trajectory[start_index], trajectory[curr_index]])
         cost_nopar = self.MDL_cost(segments[start_index:curr_index])
         if cost_par > cost_nopar + 10:
             characteristic_points.append(trajectory[curr_index - 1])
             start_index = curr_index - 1
             length = 1
         else:
             length += 1
     characteristic_points.append(trajectory[len(trajectory) - 1])
     char_segments = []
     last_point = None
     for point in characteristic_points:
         if last_point is not None:
             char_segments.append(LineSegment(last_point, point))
         last_point = point
     char_segments = np.array(char_segments)
     return (characteristic_points, char_segments)
Esempio n. 20
0
def get_grays(filename):
    original = cv2.imread(filename, cv2.IMREAD_COLOR)

    filename = filename.split('//')[1]
    img = original.copy()
    height, width, depth = img.shape

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    th, bw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    edges = cv2.Canny(gray, th / 2, th)
    # edges = cv2.Canny(gray, 50, 150, apertureSize=3)
    lines = cv2.HoughLinesP(edges,
                            1,
                            np.pi / 180,
                            100,
                            minLineLength=80,
                            maxLineGap=10)
    if lines is None:
        print(filename + ' No line detected.')
        return

    lss = []
    black = np.zeros((height, width, depth), np.uint8)

    for line in lines:
        x1, y1, x2, y2 = line[0]
        cv2.line(img, (x1, y1), (x2, y2), green, 1)
        cv2.line(black, (x1, y1), (x2, y2), green, 1)
        ls = LineSegment(x1, y1, x2, y2)
        lss.append(ls)

    lines = sorted(lss, key=lambda x: x.theta)
    line_group = []

    for ls in lines:

        if len(line_group) == 0:  # first line group
            line_group.append([ls])
        else:
            done = False
            for i in range(0, len(line_group)):
                if min(abs(line_group[i][0].theta - ls.theta),
                       math.pi - abs(line_group[i][0].theta -
                                     ls.theta)) < theta_tolerance:  # 比较斜率
                    line_group[i].append(ls)
                    done = True
                    break

            if not done:
                line_group.append([ls])

    max_group = max(line_group, key=lambda x: len(x))

    if all(abs(x.k < 1.0) for x in max_group):
        avg_k = sum([ls.k for ls in max_group]) / float(len(max_group))
        avg_theta = math.atan(avg_k)
    else:
        avg_theta = sum([ls.theta for ls in max_group]) / float(len(max_group))

    for ls in max_group:
        # 根据斜率找到的线段
        ls.update(avg_theta)

    max_group.sort(key=lambda x: x.d)
    group_d = []

    black2 = np.zeros((height, width, depth), np.uint8)
    for i in range(0, len(max_group)):
        ls = max_group[i]
        x1, x2, y1, y2 = ls.x1, ls.x2, ls.y1, ls.y2
        cv2.line(black2, (x1, y1), (x2, y2), red, 3)

        j = len(group_d) - 1
        if j < 0:
            new_g = LineSegmentGroup()
            new_g.insert(ls)
            group_d.append(new_g)
        else:
            if group_d[j].is_near(ls):
                group_d[j].insert(ls)
            else:
                new_g = LineSegmentGroup()
                new_g.insert(ls)
                group_d.append(new_g)

    cv2.putText(black, 'Group by d: ' + str(len(group_d)), (40, 200), font, 2,
                (255, 255, 255), 2)

    max_group = max(group_d, key=lambda x: len(x.lines)).lines
    for ls in max_group:
        x1, x2, y1, y2 = ls.x1, ls.x2, ls.y1, ls.y2
        cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 3)
        cv2.line(black, (x1, y1), (x2, y2), (0, 0, 255), 3)
        # 根据斜率 & x找到的线段

    line_min = min(max_group, key=lambda x: x.d)
    line_max = max(max_group, key=lambda x: x.d)

    x_avgt = sum([ls.x for ls in max_group]) / (1.0 * len(max_group))
    y_avgt = sum([ls.y for ls in max_group]) / (1.0 * len(max_group))
    xx = x_avgt + 100
    yy = y_avgt + 100 * math.tan(avg_theta)

    new_line = LineSegment(x_avgt, y_avgt, xx, yy)
    new_line.update(avg_theta)
    delta_d = (line_min.d + line_max.d) / 2.0 - new_line.d
    # cv2.circle(black, (int(x_avgt), int(y_avgt)), 20, (255, 0, 255), -1)
    xn = np.zeros((4, 2))
    yn = np.zeros((4, 2))
    dn = np.zeros(2)

    for i in range(0, 2):
        try:
            if i == 0:
                x_avg = x_avgt + delta_d * math.cos(avg_theta + math.pi / 2.0)
                y_avg = y_avgt + delta_d * math.sin(avg_theta + math.pi / 2.0)
                enlarge = (line_max.d - line_min.d) / 8.0
            else:
                x_avg = x_avgt - delta_d * math.cos(avg_theta + math.pi / 2.0)
                y_avg = y_avgt - delta_d * math.sin(avg_theta + math.pi / 2.0)
                enlarge = (line_max.d - line_min.d) / 8.0

            # print str(x_avg) + ' ' + str(y_avg)
            cv2.circle(black, (int(x_avg), int(y_avg)), 10, (255, 255, 255),
                       -1)

            cv2.putText(black,
                        'theta: ' + str(avg_theta) + 'd: ' + str(delta_d),
                        (80, 300), font, 1, (255, 255, 255), 2)
            cv2.imwrite(output_path + 'theta_' + filename, black)
            # continue

            enlarge = 0
            x1, y1, x2, y2 = line_min.x1, line_min.y1, line_min.x2, line_min.y2
            x1 -= enlarge * math.cos(avg_theta + math.pi / 2.0)
            x2 -= enlarge * math.cos(avg_theta + math.pi / 2.0)
            y1 -= enlarge * math.sin(avg_theta + math.pi / 2.0)
            y2 -= enlarge * math.sin(avg_theta + math.pi / 2.0)

            line_min_new = LineSegment(x1, y1, x2, y2)

            x1, y1, x2, y2 = line_max.x1, line_max.y1, line_max.x2, line_max.y2
            x1 += enlarge * math.cos(avg_theta + math.pi / 2.0)
            x2 += enlarge * math.cos(avg_theta + math.pi / 2.0)
            y1 += enlarge * math.sin(avg_theta + math.pi / 2.0)
            y2 += enlarge * math.sin(avg_theta + math.pi / 2.0)

            line_max_new = LineSegment(x1, y1, x2, y2)

            w = line_max_new.distance(line_min_new.x, line_min_new.y)
            h = w / 3.0 * 2.1
            r_2 = (w**2 + h**2) / 4.0

            l = line_min_new
            x1, x2, y1, y2 = l.x1, l.x2, l.y1, l.y2
            a = (y1 - y2)**2 + (x1 - x2)**2
            b = 2.0 * ((y1 - y2) * (y1 - y_avg) + (x1 - x2) * (x1 - x_avg))
            c = (y1 - y_avg)**2 + (x1 - x_avg)**2 - r_2

            t1 = (-b - math.sqrt(b**2 - 4.0 * a * c)) / (2.0 * a)
            t2 = (-b + math.sqrt(b**2 - 4.0 * a * c)) / (2.0 * a)

            xn[0, i] = x1 + t1 * (x1 - x2)
            yn[0, i] = y1 + t1 * (y1 - y2)

            xn[1, i] = x1 + t2 * (x1 - x2)
            yn[1, i] = y1 + t2 * (y1 - y2)

            l = line_max_new
            x1, x2, y1, y2 = l.x1, l.x2, l.y1, l.y2
            a = (y1 - y2)**2 + (x1 - x2)**2
            b = 2.0 * ((y1 - y2) * (y1 - y_avg) + (x1 - x2) * (x1 - x_avg))
            c = (y1 - y_avg)**2 + (x1 - x_avg)**2 - r_2

            t1 = (-b - math.sqrt(b**2 - 4.0 * a * c)) / (2.0 * a)
            t2 = (-b + math.sqrt(b**2 - 4.0 * a * c)) / (2.0 * a)

            xn[2, i] = x1 + t1 * (x1 - x2)
            yn[2, i] = y1 + t1 * (y1 - y2)

            xn[3, i] = x1 + t2 * (x1 - x2)
            yn[3, i] = y1 + t2 * (y1 - y2)

            dn[i] = abs(
                math.sqrt((xn[0, i] - xn[1, i])**2 +
                          (yn[0, i] - yn[1, i])**2) -
                math.sqrt((xn[2, i] - xn[3, i])**2 + (yn[2, i] - yn[3, i])**2))

        except ValueError:
            dn[i] = float('inf')

    ni = 1 if dn[1] < dn[0] else 0

    xn = xn[:, ni]
    yn = yn[:, ni]

    for i in range(0, 4):
        cv2.circle(black, (int(xn[i]), int(yn[i])), 30, (255, 255, 255), -1)

    # 4 3
    #  2 1
    pts1 = np.float32([[xn[1], yn[1]], [xn[3], yn[3]], [xn[0], yn[0]],
                       [xn[2], yn[2]]])
    pts2 = np.float32([[0, 0], [DST_WIDTH, 0], [0, DST_HEIGHT],
                       [DST_WIDTH, DST_HEIGHT]])
    M = cv2.getPerspectiveTransform(pts1, pts2)

    dst = cv2.warpPerspective(original, M, (DST_WIDTH, DST_HEIGHT))

    xn = np.uint(xn)
    yn = np.uint(yn)
    cv2.line(img, (xn[0], yn[0]), (xn[1], yn[1]), yellow, thickness)
    cv2.line(img, (xn[1], yn[1]), (xn[3], yn[3]), yellow, thickness)
    cv2.line(img, (xn[3], yn[3]), (xn[2], yn[2]), yellow, thickness)
    cv2.line(img, (xn[2], yn[2]), (xn[0], yn[0]), yellow, thickness)

    cv2.line(black, (xn[0], yn[0]), (xn[1], yn[1]), yellow, thickness)
    cv2.line(black, (xn[1], yn[1]), (xn[3], yn[3]), yellow, thickness)
    cv2.line(black, (xn[3], yn[3]), (xn[2], yn[2]), yellow, thickness)
    cv2.line(black, (xn[2], yn[2]), (xn[0], yn[0]), yellow, thickness)

    cv2.imwrite(output_path + 'line_' + filename, img)
    cv2.imwrite(output_path + 'only_line_' + filename, black)

    black_small = np.zeros(dst.shape, np.uint8)
    gray_small = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)

    # 检测数字位置
    dst1 = cv2.cornerHarris(gray_small, 2, 3, 0.04)
    dst1 = cv2.dilate(dst1, None)
    t = dst1 > 0.01 * dst1.max()
    black_small[t] = [0, 0, 255]
    up = t[0:40, :]
    down = t[DST_HEIGHT - 41:DST_HEIGHT - 1, :]
    if sum(sum(up)) > sum(sum(down)):
        # 旋转180度
        dst = cv2.flip(dst, -1)
        gray_small = cv2.flip(gray_small, -1)

    # cv2.imwrite(output_path + 's_only_line_' + filename, black_small)
    cv2.imwrite(output_path + 'dst_' + filename, dst)

    # 使用平均灰度值进行二值化
    height, width = gray_small.shape
    avg_gray = sum(sum(1.0 * gray_small)) / (height * width)

    cv2.imwrite(output_path + "gray_" + filename, gray_small)
    std = np.std(gray_small)
    gray_small = (gray_small - avg_gray) / std
    return gray_small
Esempio n. 21
0
from LineSegment import LineSegment

##Segmenti verticali su rette differenti
S = LineSegment([3.0, 1.0], [3.0, 3.0])
O = LineSegment([4.0, 1.0], [4.0, 3.0])
assert not S.intersects(O), "Errore per segmenti verticali su rette differenti"
assert not O.intersects(S), "Errore per segmenti verticali su rette differenti"

##Segmenti verticali su rette coincidenti
S = LineSegment([3.0, 1.0], [3.0, 3.0])
O = LineSegment([3.0, 1.5], [3.0, 3.4])
assert S.intersects(O), "Errore per segmenti verticali sulla stessa retta"
assert O.intersects(S), "Errore per segmenti verticali sulla stessa retta"

##Segmenti verticali su rette coincidenti
S = LineSegment([3.0, 1.0], [3.0, 3.0])
O = LineSegment([3.0, 4.0], [3.0, 7.0])
assert not S.intersects(O), "Errore per segmenti paralleli su rette differenti"
assert not O.intersects(S), "Errore per segmenti paralleli su rette differenti"

##Segmenti paralleli ma non verticali su rette coincidenti
S = LineSegment([0.0, 0.0], [3.0, 3.0])
O = LineSegment([4.0, 4.0], [5.0, 5.0])
assert not S.intersects(O), "Errore per segmenti paralleli sulla stessa retta"
assert not O.intersects(S), "Errore per segmenti paralleli sulla stessa retta"

S = LineSegment([0.0, 0.0], [3.0, 3.0])
O = LineSegment([1.0, 1.0], [2.0, 2.0])
assert S.intersects(O), "Errore per segmenti paralleli sulla stessa retta"
assert O.intersects(S), "Errore per segmenti paralleli sulla stessa retta"