示例#1
0
def histogram(values, binSize):
    """
    Returns a :class:`boomslang.Line.Line` representing a histogram of the list
    of values given in `values` with bin size `binSize`.
    """

    line = Line()
    line.stepFunction('post')

    bins = collections.defaultdict(int)

    maxBin = 0

    for value in values:
        currentBin = value / binSize
        bins[currentBin] += 1
        maxBin = max(maxBin, currentBin)

    for currentBin, binCount in bins.items():
        nextBin = currentBin + binSize

        if nextBin not in bins:
            bins[nextBin] = 0

    for currentBin in sorted(bins.keys()):
        line.xValues.append(currentBin * binSize)
        line.yValues.append(bins[currentBin])

    return line
示例#2
0
文件: circle.py 项目: KoenP/topdown
 def doesCircleCollideWithBox(self, box):
     dstBetweenCenters = function.getDistanceBetweenPoints(self.center, box.center)
     if dstBetweenCenters > self.radius + box.distanceCtrToPt:
         return False
     
     for point in box.points:
         if function.getDistanceBetweenPoints(self.center, point) <= self.radius:
             return True
     
     #HIER ZIT DE FOUT
     for i in range (0, 4):
         if type(box.sides[i].gradient) == str:
             orthogonal = Line(self.center, 0.0)
         elif box.sides[i].gradient != 0:
             orthogonal = Line(self.center, - 1.0 / box.sides[i].gradient)
         elif box.sides[i].gradient == 0:
             orthogonal = Line(self.center, 'vertical')
         
         nearestPoint = orthogonal.getIntersectionWithLineSegment(box.sides[i])
         if nearestPoint != False:
             if nearestPoint == 'coinciding':
                 return True
             else:
                 dstCenterToSide = function.getDistanceBetweenPoints(self.center, nearestPoint)
                 if dstCenterToSide <= self.radius:
                     return True
     return False
示例#3
0
def linear_regression():
  line = Line()
  line.slanting_line()
  sample = line.generate_sample(N)

  lr = LinearRegression()
  lr.learn(sample)

  # in-sample error
  e_in = lr.calculate_error(sample)
  # Plotting in-sample graph
  #plt = lr.plot(sample) #plot the samples
  #plt.plot([-lr.weight[0]/lr.weight[1] for y in xrange(-1,2)], [y for y in xrange(-1,2)]) # Add the x intercept line
  #plt.show()

  # out-sample error
  sample = line.generate_sample(1000)
  e_out = lr.calculate_error(sample)
  # Plotting out-sample graph
  #plt = lr.plot(sample) #plot the samples
  #plt.plot([-lr.weight[0]/lr.weight[1] for y in xrange(-1,2)], [y for y in xrange(-1,2)]) # Add the x intercept line
  #plt.show()

  #print "Line: slope=", line.slope, " intercept=", line.intercept
  #print "W_Vec: weight=", lr.weight[1], " threshold=", lr.weight[0]

  return e_in, e_out
    def setUp(self):
        p0 = Point(0,0)
        p1 = Point(3,0)
        p2 = Point(3,4)
 
        self.l1 = Line(p0, p1)
        self.l2 = Line(p1, p2)
        self.l3 = Line(p2, p0)
    def testLength(self):
        p = Path()
        p.addPoint(self.p0)
        p.addPoint(self.p1)

        l0 = Line(self.p0, self.p1)
        l1 = Line(self.p1, self.p2)
        self.assertEquals(p.length(), l0.length())
        p.addPoint(self.p2)
        self.assertEquals(p.length(), l0.length() + l1.length())
示例#6
0
def getLinesFromFile(filename, regex, postFunction=None, autofillXValues=False):
    (xValues, yValues) = getXYValsFromFile(filename, regex, postFunction,
                                           autofillXValues)

    lines = []

    for i in xrange(len(yValues)):
        line = Line()
        line.xValues = xValues[:]
        line.yValues = yValues[i][:]
        lines.append(line)
    return lines
示例#7
0
def getCDF(values):
    line = Line()
    cdfValues = values[:]
    cdfValues.sort()

    count = float(len(cdfValues))

    line.xValues = cdfValues
    line.yValues = [float(x) / count for x in xrange(1, int(count) + 1)]
    assert(count == len(line.yValues))

    return line
示例#8
0
def getLinesFromFile(filename, regex, postFunction=None, autofillXValues=False):
    """
    Turn a regularly-structured file into a collection of
    :class:`boomslang.Line.Line` objects.

    Parses each line in `filename` using the regular expression `regex`. By
    default, the first matching group from the regular expression gives the
    x-axis value for a set of points and all subsequent matching groups give
    the y-axis values for each line. If `postFunction` is not None, it is a
    function that is applied to the matching groups before they are inserted
    into the lines. If `autofillXValues` is True, all matching groups are
    treated as y-axis values for lines and the x-axis value is the line number,
    indexed from 0.

    Returns a list of :class:`boomslang.Line.Line` objects.

    **Example:** Suppose I had a file `blah.txt` that looked like this::

       1980 - 1, 2, 3
       1981 - 4, 5, 6
       1982 - 7, 8, 9

    The snippet below shows the result of running :py:func:`boomslang.Utils.getLinesFromFile` on `blah.txt`:

       >>> lines = boomslang.Utils.getLinesFromFile("blah.txt", "(\d+) - (\d+), (\d+), (\d+)")
       >>> len(lines)
       3
       >>> lines[0].xValues
       [1980, 1981, 1982]
       >>> lines[1].xValues
       [1980, 1981, 1982]
       >>> lines[2].xValues
       [1980, 1981, 1982]
       >>> lines[0].yValues
       [1, 4, 7]
       >>> lines[1].yValues
       [2, 5, 8]
       >>> lines[1].yValues
       [3, 6, 9]

    """

    (xValues, yValues) = getXYValsFromFile(filename, regex, postFunction,
                                           autofillXValues)

    lines = []

    for i in xrange(len(yValues)):
        line = Line()
        line.xValues = xValues[:]
        line.yValues = yValues[i][:]
        lines.append(line)
    return lines
def lr_booting_preceptron():
  line = Line()
  line.slanting_line()
  sample = line.generate_sample(N)

  lr = LinearRegression()
  lr.learn(sample)

  p = Preceptron(lr.weight)
  p.learn(sample)

  return p.count
    def solveStep( self, threshold, screen ):
        if self.mMisMatch < threshold:
            # Generate a random sample
            random.seed();
            rndX = random.randint( self.mPolygon.mMinX, self.mPolygon.mMaxX ) 
            rndY = random.randint( self.mPolygon.mMinY, self.mPolygon.mMaxY ) 
            sample = (rndX, rndY);
            self.mAllSamples = self.mAllSamples + [sample];
            #print sample;

            # if the sample is not inside the polygon
            if not self.mPolygon.pointInPoly( rndX, rndY ):
                return;

            if( len(self.mGuards) == 0 ):  # first valid point is always a guard
                self.mGuards = self.mGuards + [ sample ];
                print "Got one guard!\n"
                return;

            # Test each edge of the polygon and the line btw a gurad and the sample
            passTest = False;
            innerPass = 0;
            for guard in self.mGuards:
                line1 = Line( guard[0], guard[1], rndX, rndY );
                guardEdgeIntersectCount = 0;
                for line2 in self.mPolygon.mLines:
                    if line1.intersect( line2 ):
                        guardEdgeIntersectCount += 1;
                        break;
                    pass
                if guardEdgeIntersectCount == 0: # the sample can see the existing guard
                    passTest = False;
                    continue;
                else:
                    innerPass += 1;
            
            if innerPass == len(self.mGuards):
                passTest = True;

            if passTest:
                self.mGuards = self.mGuards + [ sample ];
                self.mUpdate = True;
                self.mMisMatch = 0;
                print "Got one guard!\n"
            else:
                self.mMisMatch = self.mMisMatch + 1;
            pass;
        else:
            print "Solved. Guards number: " + str( len(self.mGuards) );
            self.mSolved = True;
            return;
示例#11
0
def preceptron_learning():
  line = Line()
  line.random_line()
  sample = line.generate_sample(100)
  # print sample

  p = Preceptron([.01,0])
  p.learn(sample)

  sample = line.generate_sample(100000)

  incorrect = p.fng(sample)
  #print p.weight
  #print p.count

  return p.count, incorrect
示例#12
0
	def scale(self, x, y, factor_x, factor_y):
		tmp_point_list = []
		for i in range(len(self.point_list)):
			# Two vertex points to local vars
			x1 = self.point_list[i][0]
			y1 = self.point_list[i][1]
			x2 = self.point_list[(i+1)%len(self.point_list)][0]
			y2 = self.point_list[(i+1)%len(self.point_list)][1]

			# Preform rotation on temporary line 
			tmp_line = Line(x1, y1, x2, y2)
			tmp_line.scale(x, y, factor_x, factor_y)

			# Rotated points back to point list
			tmp_point_list.append((tmp_line.x1, tmp_line.y1))
		self.point_list = tmp_point_list
示例#13
0
 def numOfIntersectOutline(self,point):
     num = 0 
     line = Line(self.refPoint, point)
     for wall in self.outlineList:
         if Line.isIntersected(wall, line):
             num += 1
     return num 
示例#14
0
文件: Code.py 项目: resturp/Symilar
 def createBaseMatrix(self):     
     self.rootScope = Scope(-1)
     indentLevel(-1)
     self.rootScope.antiTranslator = translator.getBuiltInNames()
     self.rootScope.antiTranslator.update(translator.getKeywords())
     
     self.baseMatrix = []
     lastIndent = 0
     #print self.code
     for part in self.code.split('~'):
         for line in part.splitlines(1):
             thisLine = Line(line)
             
             if thisLine.line != '': 
                 thisLine.setDeltaIndent(lastIndent)
                 lastIndent = thisLine.indent             
                 self.baseMatrix.append(thisLine) 
示例#15
0
def cdf(values):
    """
    Returns a :class:`boomslang.Line.Line` representing the CDF of the list of
    values given in `values`.
    """

    line = Line()
    cdfValues = values[:]
    cdfValues.sort()

    count = float(len(cdfValues))

    line.xValues = cdfValues
    line.yValues = [float(x) / count for x in xrange(1, int(count) + 1)]
    assert(count == len(line.yValues))

    return line
示例#16
0
    def addLineToTextColumn(self, currentTextElementsList, textColumnsWidth):
        """
            Creates a TextElement object and adds it to a line
        """
        for xmlTextElement in currentTextElementsList:
            currentTxtColumn = None
            currentTextElement = self.createTextElement(xmlTextElement)
            self.__rightColumn = abs(currentTextElement.getLeft()/textColumnsWidth)

            if (int(self.__rightColumn) < len(self.__textColumnsList)):
                currentTxtColumn = self.__textColumnsList[int(self.__rightColumn)]

                if (len(currentTxtColumn.getLinesList())) > 0:
                    line = currentTxtColumn.getLine(-1) #returns the value in the last position

                    if self.inTheLine(currentTextElement, line) == True:
                        # exactly in the boundaries of the line
                        line.addText(currentTextElement)
                        self.updateLineValues(currentTextElement, line)
                    else:
                        newLine = Line()
                        newLine.addText(currentTextElement)
                        self.setNewLineValues(currentTextElement, newLine)
                        currentTxtColumn.addLine(newLine)
                        self.__distance += int(newLine.getFirstTop()) - int(line.getLastTop())

                else:
                    newLine = Line()
                    newLine.addText(currentTextElement)
                    self.setNewLineValues(currentTextElement, newLine)
                    currentTxtColumn.addLine(newLine)
def intersection_of_lines_in_2D():
    l1 = Line(normal_vector = Vector(['4.046', '2.836']), constant_term = '1.21')
    l2 = Line(normal_vector = Vector(['10.115', '7.09']), constant_term = '3.025')
    print("{0} intersects with {1} in ".format(l1, l2) + str(l1.intersection_with(l2)))

    l1 = Line(Vector(['7.204', '3.182']), '8.68')
    l2 = Line(Vector(['8.172', '4.114']), '9.883')
    print("{0} intersects with {1} in ".format(l1, l2) + str(l1.intersection_with(l2)))

    l1 = Line(Vector(['1.182', '5.562']), '6.744')
    l2 = Line(Vector(['1.773', '8.343']), '9.525')
    print("{0} intersects with {1} in ".format(l1, l2) + str(l1.intersection_with(l2)))
示例#18
0
 def DrawBenchmarkLines(self):
     # Draw benchmark lines.
     currentpad = ROOT.gPad
     if not currentpad:
         return
     xmin = currentpad.GetUxmin()
     xmax = currentpad.GetUxmax()
     ymin = currentpad.GetUymin()
     ymax = currentpad.GetUymax()
     self._benchmarklines = []
     for bm in [i * 0.1 for i in range(-5, 41, 5)]:
         if bm < ymin or bm == 1:
             continue
         if bm > ymax:
             break
         self._benchmarklines.append(
             Line(xmin, bm, xmax, bm, linestyle=7, linecoloralpha=(ROOT.kBlack, 0.6))
         )
     for line in self._benchmarklines:
         line.Draw()
示例#19
0
文件: SOT23.py 项目: brucemack/SCAM
    def __init__(self, rotation_ccw=0):
        super().__init__()
        self.rotation_ccw = rotation_ccw

        # Horizontal lines from bottom up
        start_point = rotate((0.0 * self.pitch_mm, 0.0 * self.pitch_mm), rotation_ccw)
        end_point = rotate((1.0 * self.pitch_mm,   0.0 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((0.0 * self.pitch_mm, 1.0 * self.pitch_mm), rotation_ccw)
        end_point = rotate((1.0 * self.pitch_mm,   1.0 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((0.0 * self.pitch_mm, 2.0 * self.pitch_mm), rotation_ccw)
        end_point = rotate((1.0 * self.pitch_mm,   2.0 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((1.0 * self.pitch_mm, 0.5 * self.pitch_mm), rotation_ccw)
        end_point = rotate((2.0 * self.pitch_mm,   0.5 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((1.0 * self.pitch_mm, 1.5 * self.pitch_mm), rotation_ccw)
        end_point = rotate((2.0 * self.pitch_mm,   1.5 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        # Vertical lines from left to right
        start_point = rotate((0.0 * self.pitch_mm, 0.0 * self.pitch_mm), rotation_ccw)
        end_point = rotate((0.0 * self.pitch_mm,   2.0 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((1.0 * self.pitch_mm, 0.0 * self.pitch_mm), rotation_ccw)
        end_point = rotate((1.0 * self.pitch_mm,   2.0 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((2.0 * self.pitch_mm, 0.5 * self.pitch_mm), rotation_ccw)
        end_point = rotate((2.0 * self.pitch_mm,   1.5 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))
示例#20
0
def choose_best_line(resistance_lines, support_lines, frame_size):
	support_end_points = []
	good_support = []
	support_slope = []
	for l in reversed(support_lines[-7:]):
		good_support.append(l["line"])
		support_slope.append(l["line"].slope)
		support_end_points.append(l["line"].get_y(0))
		support_end_points.append(l["line"].get_y(frame_size))
	good_resisitance = []
	resistance_slope = []

	resistance_end_points = []
	for l in reversed(resistance_lines[-7:]):
		good_resisitance.append(l["line"])
		resistance_slope.append(l["line"].slope)
		resistance_end_points.append(l["line"].get_y(0))
		resistance_end_points.append(l["line"].get_y(frame_size))

	normalize_slope_val = max(resistance_end_points) - min(support_end_points) 
	resistance_slope.remove(max(resistance_slope))
	resistance_slope.remove(min(resistance_slope))
	support_slope.remove(max(support_slope))
	support_slope.remove(min(support_slope))

	good_lines = []
	for index in range(2):
		good_lines.append([good_support[index], good_resisitance[index]])

	final_support = Line(2,2,1,1)
	final_support.slope = (good_lines[0][0].slope+good_lines[1][0].slope)/2
	final_support.intercept = (good_lines[0][0].intercept+good_lines[1][0].intercept)/2

	final_resistance = Line(2,2,1,1)
	final_resistance.slope = (good_lines[0][1].slope+good_lines[1][1].slope)/2
	final_resistance.intercept = (good_lines[0][1].intercept+good_lines[1][1].intercept)/2
	return (final_support, final_resistance)
示例#21
0
    def __init__(self, pins=8, ground_pin=False, rotation_ccw=0):
        super().__init__()
        self.rotation_ccw = rotation_ccw
        self.pins = pins
        # DIP packages arrange pins in rows of 8
        rows = int(pins / 2)

        # Horizontal lines from bottom up
        if ground_pin:
            start_point = rotate((self.width_mm / 2, 0), rotation_ccw)
            end_point = rotate((self.width_mm, 0), rotation_ccw)
            self.add(self.NO_OFFSET, Line(start_point, end_point))
        else:
            start_point = rotate((0, 0), rotation_ccw)
            end_point = rotate((self.width_mm, 0), rotation_ccw)
            self.add(self.NO_OFFSET, Line(start_point, end_point))

        for pin in range(1, rows + 1):
            start_point = rotate((0, pin * self.pitch_mm), rotation_ccw)
            end_point = rotate((self.width_mm, pin * self.pitch_mm),
                               rotation_ccw)
            self.add(self.NO_OFFSET, Line(start_point, end_point))

        # Vertical lines from left to right
        if ground_pin:
            start_point = rotate((0, self.pitch_mm), rotation_ccw)
            end_point = rotate((0, rows * self.pitch_mm), rotation_ccw)
            self.add(self.NO_OFFSET, Line(start_point, end_point))
        else:
            start_point = rotate((0, 0), rotation_ccw)
            end_point = rotate((0, rows * self.pitch_mm), rotation_ccw)
            self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((self.width_mm / 2.0, 0), rotation_ccw)
        end_point = rotate((self.width_mm / 2.0, rows * self.pitch_mm),
                           rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((self.width_mm, 0), rotation_ccw)
        end_point = rotate((self.width_mm, rows * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))
    def __init__(self, json_path):
        node_json = json.load(open(json_path, 'r'))
        self._nodes = {}
        self._lines = {}
        for node_label in node_json:
            #create a node
            node_dict = node_json[node_label]
            node_dict['label'] = node_label
            node = Node(node_dict)
            self._nodes[node_label] = node

            # create a line
            for connected_node_label in node_dict['connected_nodes']:
                line_dict = {}
                line_label = node_label + connected_node_label
                line_dict['label'] = line_label
                node_position = np.array(node_json[node_label]['position'])
                connected_node_position = np.array(
                    node_json[connected_node_label]['position'])
                line_dict['length'] = np.sqrt(
                    np.sum((node_position - connected_node_position)**2))
                line = Line(line_dict)
                self._lines[line_label] = line
    def drawLine(self, a, b):
        if not a == b:
            for line in Line.lines:
                if line.a == a and line.b == b:
                    return
                if line.a == b and line.b == a:
                    return

            try:
                x1 = a.x_orig + a.x_off
                y1 = a.y_orig + a.y_off
                x2 = b.x_orig + b.x_off
                y2 = b.y_orig + b.y_off
            except:
                x1, y1 = a.canvas.coords(a.canvas_id)
                x2, y2 = b.canvas.coords(b.canvas_id)

            lineid = self.canvas.create_line(x1, y1, x2, y2)
            line = Line(lineid, a, b, [x1, y1, x2, y2])
            a.lines.append(line)
            b.lines.append(line)
            self.canvas.coords(lineid, x1, y1, x2, y2)

            self.canvas.pack(fill=BOTH, expand=1)
示例#24
0
def collectLines(pointsList, minYDiff):

    pointsList.sort(key=lambda point: point.y, reverse=False)

    for p in pointsList:
        print(p.y)
    lines = list()
    line_curr = list()
    line_curr.append(pointsList[0])
    avg_y = pointsList[0].y
    cal_idx = 0

    for i in range(0, len(pointsList) - 1):

        pointsList[i].x = int(pointsList[i].x)
        pointsList[i].y = int(pointsList[i].y)
        diff = math.fabs(avg_y - pointsList[i + 1].y)

        if diff <= minYDiff:

            line_curr.append(pointsList[i + 1])

            avg_y = 0

            for p in line_curr:
                avg_y += p.y
            avg_y = avg_y / len(line_curr)

        else:

            lines.append(Line(line_curr))
            line_curr = []
            line_curr.append(pointsList[i + 1])
            avg_y = pointsList[i + 1].y

    return lines
    def Mousedown(self, event):
        event.widget.focus_set()  # so escape key will work
        if self.current is None:
            # the new line starts where the user clicked
            x0 = event.x
            y0 = event.y

            # Start the new line:
            self.current = event.widget.create_line(x0, y0, event.x, event.y)

        else:
            coords = event.widget.coords(self.current)
            x0 = coords[0]
            y0 = coords[1]

            #Draw the final line
            event.widget.create_line(x0, y0, event.x, event.y)

            self.lines[self.get_image_name()].append(
                Line(x0, y0, event.x, event.y))
            print("Creating line: {0}, {1}, {2}, {3}".format(
                x0, y0, event.x, event.y))
            self.print_lines()
            self.current = None
示例#26
0
def GetInitialGuessLine(fullData):

    plt.scatter(fullData['Population'], fullData['Profit'])
    #plt.plot([10, 20], [5, 20], 'k-', lw=2)
    x = fullData['Population']
    y = fullData['Profit']

    # To start get Two Points
    # First Point
    # average of x and y
    initialGuessLine_Point1_x = x.mean()
    initialGuessLine_Point1_y = y.mean()

    # point 2
    # Max(x)-Min(x),Max(y)-Min(y)
    initialGuessLine_Point2_x = (x.max() + x.min()) / 2
    initialGuessLine_Point2_y = (y.max() + y.min()) / 2
    plt.plot([initialGuessLine_Point1_x, initialGuessLine_Point2_x],
             [initialGuessLine_Point1_y, initialGuessLine_Point2_y],
             'k-',
             lw=2)
    ln = Line(initialGuessLine_Point1_x, initialGuessLine_Point1_y,
              initialGuessLine_Point2_x, initialGuessLine_Point2_y)
    return ln
示例#27
0
class LineTestCase(unittest.TestCase):
    def setUp(self):
        p0 = Point(0,0)
        p1 = Point(3,0)
        p2 = Point(3,4)
 
        self.l1 = Line(p0, p1)
        self.l2 = Line(p1, p2)
        self.l3 = Line(p2, p0)
    
    def testLengths(self):
        self.assertAlmostEqual(self.l1.length(), 3.0)
        self.assertAlmostEqual(self.l2.length(), 4.0)
        self.assertAlmostEqual(self.l3.length(), 5.0)

    def testDot(self):
        a0 = self.l2.angle(Point(1,1))
        a1 = self.l2.angle(Point(5, 1))
        a2 = self.l1.angle(Point(1,2))
        a3 = self.l1.angle(Point(1,-2))
        self.assertTrue(a0 > 0)
        self.assertTrue(a1 < 0)
        self.assertTrue(a2 > 0)
        self.assertTrue(a3 < 0)
示例#28
0
 def getLineData(self):
     self.getRequest()
     title = self.soup.title.text
     line = Line()
     if title == "Wykaz linii":
         return None
     stationFromToList = self.soup.title.text.replace("Linia ", "")
     if isinstance(stationFromToList, list):
         cityFrom = self.soup.title.text.replace("Linia ", "").split("–")[0]
         if cityFrom[-1] == " ":
             cityFrom = cityFrom[:-1]
         line.stationFrom = cityFrom
         cityTo = self.soup.title.text.replace("Linia ", "").split("–")[1]
         for sign in ["(", ")"]:
             if sign in cityTo:
                 cityTo = cityTo.replace(sign, "")
             if cityTo[0] == " ":
                 cityTo = cityTo[1:]
             if cityTo[-1] == " ":
                 cityTo = cityTo[:-1]
         line.stationTo = cityTo
     ret = re.search("\(([^)]*)\)[^(]*$", title)
     if ret is not None:
         try:
             number = int(ret.group(1))
         except ValueError:
             if "/" in ret.group(1):
                 number = int(ret.group(1).split("/")[0])
             else:
                 number = None
         line.number = number
     line.bazaCode = self.bazaCode
     for trElem in self.soup.find_all("table")[0].find_all("tr"):
         try:
             tdList = trElem.find_all("td")
             stationData = (tdList[1].a.text, tdList[2].input["value"],
                            tdList[0].span["title"])
             line.stationList.append(stationData)
         except:
             pass
     return line
示例#29
0
def createSubLine(line, t):
    newLine = Line([])
    pointLeftOf = None
    for point in line.points:
        if pointLeftOf != None:
            x = point.x - pointLeftOf.x
            y = point.y - pointLeftOf.y

            x *= t / 100
            y *= t / 100

            x += pointLeftOf.x
            y += pointLeftOf.y

            newLine.addPoint(Point(x, y))

        pointLeftOf = point

    plt.plot(newLine.xArray(), newLine.yArray(), '-o')

    if len(newLine.points) > 1:
        createSubLine(newLine, t)
    else:
        bezierLine.addPoint(newLine.points[0])
示例#30
0
def crop_lines(model_robust, skeleton, x, y, win_w, win_h):
    i = win_w
    cropped = []
    suspicious_count = 0
    suspicious_inter = 0
    start_x = -1
    isLine = False

    # initialization
    inliers_count = inliers_around_point(skeleton, x[win_w], y[win_w], win_w,
                                         win_h)
    if inliers_count > win_w * 2 - 5:
        isLine = True
        start_x = 0
    # find line crops:
    while i < 1024:
        inliers_count = inliers_around_point(skeleton, i, int(y[i]), win_w,
                                             win_h) > (win_w * 2 - 5)
        if isLine:
            if inliers_count:
                suspicious_count = 0
                inter_count = inliers_around_point(skeleton, x[i], int(y[i]),
                                                   5, 20)
                if inter_count > 30:
                    suspicious_inter += 1
                    if suspicious_inter > 5:
                        suspicious_inter = 0
                        # remove short lines
                        if i - start_x > 50:
                            newLine = Line(start_x, i, y[start_x], y[i],
                                           model_robust)
                            cropped.append(
                                Line(start_x, i, y[start_x], y[i],
                                     model_robust))
                        start_x = x[i] + 5
                        i += 5
                else:
                    suspicious_inter = 0
            else:
                suspicious_count += 1
                if suspicious_count >= win_w:
                    suspicious_count = 0
                    if x[i] - start_x > 100:
                        cropped.append(
                            Line(start_x, i - win_w, y[start_x], y[i - win_w],
                                 model_robust))
                    isLine = False
        else:
            if inliers_count:
                suspicious_count += 1
                if suspicious_count >= win_w:
                    suspicious_count = 0
                    start_x = i - win_w
                    isLine = True
            else:
                suspicious_count = 0
        i += 1
    if isLine and start_x < x.shape[0]:
        cropped.append(
            Line(start_x, x.shape[0] - 1 - 70, y[start_x],
                 y[(x.shape[0] - 1 - 70)], model_robust))
    return cropped
示例#31
0
						labelled_rectangle_to_compare = Rectangle(relabel_x,relabel_y, int(labelled_rect[2]), int(labelled_rect[3]))
					else:
						labelled_rectangle_to_compare = Rectangle(int(labelled_rect[0]),int(labelled_rect[1]), int(labelled_rect[2]), int(labelled_rect[3]))
			#many labels
			else:

				if iteration == 0:
					if classifier_type == "S" and dataset =="training":
						relabel_x = int(labRect[0]) + int((110-100)/2)
						relabel_y = int(labRect[1]) + int((110-40)/2)
						closest_labelled_rectangle = Rectangle(relabel_x,relabel_y, int(labelled_rect[2]), int(labelled_rect[3]))
					else:
						closest_labelled_rectangle = Rectangle(int(labelled_rect[0]),int(labelled_rect[1]), int(labelled_rect[2]), int(labelled_rect[3]))

					# define first labelled rectangle as closest
					current_path = Line(detected_rectangle.getCenter(), closest_labelled_rectangle.getCenter())
					closest_distance = current_path.getDistance()
					labelled_rectangle_to_compare = closest_labelled_rectangle

				else:

					if classifier_type == "S" and dataset =="training":
						relabel_x = int(labRect[0]) + int((110-100)/2)
						relabel_y = int(labRect[1]) + int((110-40)/2)
						labelled_rectangle = Rectangle(relabel_x,relabel_y, int(labelled_rect[2]), int(labelled_rect[3]))
					else:
						labelled_rectangle = Rectangle(int(labelled_rect[0]),int(labelled_rect[1]), int(labelled_rect[2]), int(labelled_rect[3]))

					# get straight line distance between the center of labelled and detection rectangles.
					current_path = Line(detected_rectangle.getCenter(), labelled_rectangle.getCenter())
					current_distance = current_path.getDistance()
    def _calculateDistanceLineOfSight(self, particle):
        '''
    Calculate the distance line of sight and intersection of the given particle
    @param particle - list describing the particle distance line of sight [X, Y, Heading, Weight]
    @return particle closest distance intersection on its left side
    @return particle closest distance intersection on its right side
    '''
        print("DBG: _calculateDistanceLineOfSight called")
        particleDistLeft, particleDistRight = 0.0, 0.0

        # Left Distance
        rX, rY = self._rotate(Constants.DIST_LEFT_SENSOR_POSITION[Constants.X],
                              Constants.DIST_LEFT_SENSOR_POSITION[Constants.Y],
                              particle[Constants.HEADING])
        print("DBG: Rotate Left (rX, rY) = ({0}, {1})".format(rX, rY))
        leftStartPoint = [
            particle[Constants.X] + rX, particle[Constants.Y] + rY
        ]
        print("DBG: leftStartPoint(X, Y) = {0}".format(leftStartPoint))

        rX, rY = self._rotate(
            Constants.DIST_MAX_DISTANCE, 0.0, particle[Constants.HEADING] +
            Constants.DIST_LEFT_SENSOR_OREINTATION)
        print("DBG: Rotate Left (rX, rY) = ({0}, {1})".format(rX, rY))
        leftEndPoint = [
            leftStartPoint[Constants.X] + rX, leftStartPoint[Constants.Y] + rY
        ]
        print("DBG: leftEndPoint(X, Y) = {0}".format(leftEndPoint))
        leftDistLine = Line(leftStartPoint, leftEndPoint)

        # Right Distance
        rX, rY = self._rotate(
            Constants.DIST_RIGHT_SENSOR_POSITION[Constants.X],
            Constants.DIST_RIGHT_SENSOR_POSITION[Constants.Y],
            particle[Constants.HEADING])
        print("DBG: Rotate Right (rX, rY) = ({0}, {1})".format(rX, rY))
        rightStartPoint = [
            particle[Constants.X] + rX, particle[Constants.Y] + rY
        ]
        print("DBG: rightStartPoint(X, Y) = {0}".format(rightStartPoint))

        rX, rY = self._rotate(
            Constants.DIST_MAX_DISTANCE, 0.0, particle[Constants.HEADING] +
            Constants.DIST_RIGHT_SENSOR_OREINTATION)
        print("DBG: Rotate Right (rX, rY) = ({0}, {1})".format(rX, rY))
        rightEndPoint = [
            rightStartPoint[Constants.X] + rX,
            rightStartPoint[Constants.Y] + rY
        ]
        print("DBG: rightEndPoint(X, Y) = {0}".format(rightEndPoint))
        rightDistLine = Line(rightStartPoint, rightEndPoint)

        # Get left intersections with map walls
        leftIntersections = []
        for c in self.courseMap.circles:
            inter = c.findIntersection(leftDistLine)
            if inter is not None:
                for i in inter:
                    if i is not None:
                        leftIntersections += [i]

        leftIntersections += [
            l.findIntersection(leftDistLine) for l in self.courseMap.lines
        ]

        print("DBG: leftIntersections = {0}".format(leftIntersections))

        # Get right intersections with map walls
        rightIntersections = []
        for c in self.courseMap.circles:
            inter = c.findIntersection(leftDistLine)
            if inter is not None:
                for i in inter:
                    if i is not None:
                        rightIntersections += [i]

        rightIntersections += [
            l.findIntersection(rightDistLine) for l in self.courseMap.lines
        ]
        print("DBG: rightIntersections = {0}".format(rightIntersections))

        # Calculate distances
        try:
            particleDistLeft = math.sqrt(
                min([
                    math.pow(li[Constants.X] - leftStartPoint[Constants.X],
                             2.0) +
                    math.pow(li[Constants.Y] - leftStartPoint[Constants.Y],
                             2.0) for li in leftIntersections if li is not None
                ]))
        except:
            particleDistLeft = None

        try:
            particleDistRight = math.sqrt(
                min([
                    math.pow(ri[Constants.X] - rightStartPoint[Constants.X],
                             2.0) +
                    math.pow(ri[Constants.Y] - rightStartPoint[Constants.Y],
                             2.0) for ri in rightIntersections
                    if ri is not None
                ]))
        except:
            particleDistRight = None

        # Sanity check
        if particleDistLeft is None or particleDistLeft >= Constants.DIST_MAX_DISTANCE:
            particleDistLeft = Constants.DIST_MAX_DISTANCE + 2.0 * Constants.DISTANCE_NOISE

        if particleDistRight is None or particleDistRight >= Constants.DIST_MAX_DISTANCE:
            particleDistRight = Constants.DIST_MAX_DISTANCE + 2.0 * Constants.DISTANCE_NOISE

        return particleDistLeft, particleDistRight
示例#33
0
# of error (such as remote create/update failures) listing
# all fields with mismatched or invalid options .. see invalidOptionsReport
#
from Contact import Contact
from Line import Line, Index

x = Contact()
x.emailAddress = '*****@*****.**'

logFile = open('NateMike.log', 'r')

log = [line for line in logFile]

meta = []
for line in log:
    meta.append(Line.digest_with_ts(line))


# logic for getting to a MISSING FIELDS error
for metaline in meta:
    if metaline.mType != '':
        print metaline.mType
    if metaline.mType == 'INDEX':
        metaline.process()
        if x.emailAddress == metaline.mEmail:
            x.externalIds.add(metaline.mContact)
    else:
        pass

# we've slurped externalIds
for metaline in meta:
class RollerCoaster:
    def __init__(self):
        self.ticketCost = 16
        self.trainCarLimit = 60
        self.totalRuntime = 180
        self.numberOfOperators = 1
        self.line = Line()
        self.currentRuntime = 0
        self.setupTime = 0
        self.running = False
        self.numberOfPeopleGettingOnRide = 0
        self.car = []
        self.totalTicketsReceived = 0
        self.postRide = False
        self.postRideTime = 30

    def StartSetup(self):
        if self.line.GetNumberOfPeople() >= 60:
            self.numberOfPeopleGettingOnRide = 60
            self.setupTime = 60
        else:
            self.numberOfPeopleGettingOnRide = self.line.GetNumberOfPeople()
            self.setupTime = 60
        self.running = True

    def CheckIfReady(self):
        self.setupTime -= 1
        if self.setupTime == 0:
            self.car = []
            for i in range(0, self.numberOfPeopleGettingOnRide):
                person = self.line.GetPerson()
                self.line.DecrementLineCount()
                person.UseTickets(16)
                self.totalTicketsReceived += 16
                self.car.append(person)
            return True
        else:
            return False

    def CheckIfDone(self):
        self.currentRuntime += 1
        if self.currentRuntime == self.totalRuntime:
            self.running = False
            self.currentRuntime = 0
            self.postRide = True
            return True
        else:
            return False

    def UpdatePostRiders(self):  #riders gather their stuff. 30 seconds
        self.postRideTime -= 1
        if self.postRideTime == 0:
            self.postRideTime = 30
            self.postRide = False
            return True
        else:
            return False

    def GetCurrentWaitTime(self):
        numberOfCars = 0
        if int(self.line.GetNumberOfPeople() / self.trainCarLimit
               ) == self.line.GetNumberOfPeople() / self.trainCarLimit:
            numberOfCars = int(self.line.GetNumberOfPeople() /
                               self.trainCarLimit)
        else:
            numberOfCars = int(
                self.line.GetNumberOfPeople() / self.trainCarLimit) + 1
        rollerCoasterWaitTime = (numberOfCars * 240)
        if self.running:
            rollerCoasterWaitTime += (180 - self.currentRuntime)
        else:
            rollerCoasterWaitTime += 180 + self.setupTime
        return rollerCoasterWaitTime
示例#35
0
    def _getLineConfiguration(self, nLine):

        # if the data directory does not exist, create it
        if not os.path.exists(self.sDirectory):
            os.makedirs(self.sDirectory)

        sFilename = ('route_' + str(nLine) + '_directionsTable.txt')
        sFilename = os.path.join(self.sDirectory, sFilename)

        try:
            bFileExists = os.path.isfile(sFilename)
            bUpdatedToday = (datetime.date.today() == datetime.date.fromtimestamp(os.path.getmtime(sFilename)))

        except OSError:
            bFileExists = False
            bUpdatedToday = False

        # configuration files are only updated once a day
        if bFileExists is False or bUpdatedToday is False:

            output = Line(id=nLine)

            sRoute = '&r=' + str(nLine)
            try:
                urlHandle = urllib.urlopen(self.sUrlNextbus + self.sCommandGetStops
                                           + self.sAgency + sRoute + self.sFlags)
                xml = urlHandle.read()
                urlHandle.close()
                root = etree.fromstring(xml)

            except Exception as e:
                print "Could not load configuration: %s" % e
                return

            lStops = {}

            for elementA in root:
                if elementA.tag == 'route':
                    for elementB in elementA:

                        if elementB.tag == 'stop':
                            stopID = elementB.attrib['tag']

                            lStops[stopID] = Stop(
                                id=elementB.attrib['tag'],
                                name=elementB.attrib['title'],
                                latitude=elementB.attrib['lat'],
                                longitude=elementB.attrib['lon']
                            )

                        if elementB.tag == 'direction':
                            sBusDirection = elementB.attrib['tag']
                            direction = Direction(line=nLine, id=sBusDirection, title=elementB.attrib['title'])

                            for elementC in elementB:
                                direction.addStop(lStops[elementC.attrib['tag']])

                            output.addDirection(direction)

            # Write out direction "variables" table to a file
            fhDirections = open(sFilename, 'wb')
            pickle.dump(output, fhDirections)
            fhDirections.close()

            return output

        # route information is cached, so just restore it
        else:
            fhDirections = open(sFilename, 'rb')
            output = pickle.load(fhDirections)
            fhDirections.close()
            return output
示例#36
0
    def process_screengrab(self, orig_image, capture_region):

        # topleftx, toplefty, botrightx, botrighty = capture_region
        tlx, tly, brx, bry = capture_region
        w = brx - tlx
        h = bry - tly
        t = tly     # t = tly = 40
        b = bry     # b = bry = 520
        l = tlx     # t = tlx = 0
        r = brx     # r = brx = 640

        # 3rd person camera adjustments
        vertices=mask_vertices(l,t,b,r,w,h)
        roi_extracted_image = mask_image(orig_image,vertices)

        # Focussing on the road portion of the image
        # This depends on camera settings from game to game
        v_cutoff = np.int(0.35*h)
        mask_3ch = generate_lane_mask(roi_extracted_image, v_cutoff=v_cutoff)
        lane_masked_image = cv2.bitwise_and(roi_extracted_image, mask_3ch)
        # Convert to a binary mask
        mask = mask_3ch[:,:,0]

        mask_1ch =  mask * ((mask == 255).astype('uint8'))

        # Applying the Birds Eye Transformation
        #mask = mask_1ch
        mask_birdeye = BirdsEyePerspective(mask_1ch, capture_region)

        # Always pass a 1-D array to histogram function.
        # Hence, we need to convert from 3-channel color image to grayscale
        #processed_image = cv2.cvtColor(processed_image, cv2.COLOR_RGB2GRAY)

        left_detected = right_detected = False
        left_x = left_y = right_x = right_y = []

        # If there have been lanes detected in the past, the algorithm will first try to
        # find new lanes along the old one. This will improve performance

        if self.left_line is not None and self.right_line is not None:
            left_x, left_y = detect_lane_along_poly(mask_birdeye, self.left_line.best_fit_poly, self.line_segments)
            right_x, right_y = detect_lane_along_poly(mask_birdeye, self.right_line.best_fit_poly, self.line_segments)

            left_detected, right_detected = self.__check_lines(left_x, left_y, right_x, right_y)

        # If no lanes are found a histogram search will be performed
        if not left_detected:
            left_x, left_y = histogram_lane_detection(
                mask_birdeye, self.line_segments, (self.image_offset, np.int(0.5*lane_masked_image.shape[1])), h_window=7)
            left_x, left_y = outlier_removal(left_x, left_y)
        if not right_detected:
            right_x, right_y = histogram_lane_detection(
                mask_birdeye, self.line_segments, (np.int(0.5*lane_masked_image.shape[1]), lane_masked_image.shape[1] - self.image_offset), h_window=7)
            right_x, right_y = outlier_removal(right_x, right_y)

        if not left_detected or not right_detected:
            left_detected, right_detected = self.__check_lines(left_x, left_y, right_x, right_y)

        print(left_detected, right_detected)

        # Updated left lane information.
        if left_detected:
            # switch x and y since lines are almost vertical
            if self.left_line is not None:
                self.left_line.update(y=left_x, x=left_y)
            else:
                self.left_line = Line(self.n_frames, left_y, left_x)

        # Updated right lane information.
        if right_detected:
            # switch x and y since lines are almost vertical
            if self.right_line is not None:
                self.right_line.update(y=right_x, x=right_y)
            else:
                self.right_line = Line(self.n_frames, right_y, right_x)

        # Add information onto the frame
        if self.left_line is not None and self.right_line is not None:
            self.dists.append(self.left_line.get_best_fit_distance(self.right_line))
            self.center_poly = (self.left_line.best_fit_poly + self.right_line.best_fit_poly) / 2
            self.curvature = calc_curvature(self.center_poly)
            self.offset = (lane_masked_image.shape[1] / 2 - self.center_poly(719)) * 3.7 / 700

            self.__draw_lane_overlay(orig_image, capture_region)
            self.__draw_info_panel(orig_image)


        return mask_birdeye, mask_1ch, lane_masked_image, roi_extracted_image, orig_image
示例#37
0
from Grid_220 import Grid220
from Line import Line
from Transformer import Transformer
from Area import Area

if __name__ == "__main__":
    lines = Line()
    transformers = Transformer()
    for 
    grid = Grid220(lines, transformers, buses, areas)
    grid.CalcPowerFlowLoss()
示例#38
0
    def __init__(self, rotation_ccw=0):
        super().__init__()
        self.rotation_ccw = rotation_ccw

        # Horizontal lines
        start_point = rotate((0.5 * self.width_mm, 0.0 * self.pitch_mm),
                             rotation_ccw)
        end_point = rotate((1.25 * self.width_mm, 0.0 * self.pitch_mm),
                           rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((0.5 * self.width_mm, 3.0 * self.pitch_mm),
                             rotation_ccw)
        end_point = rotate((1.0 * self.width_mm, 3.0 * self.pitch_mm),
                           rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((0.0 * self.width_mm, 4.0 * self.pitch_mm),
                             rotation_ccw)
        end_point = rotate((1.25 * self.width_mm, 4.0 * self.pitch_mm),
                           rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        # self.add(self.NO_OFFSET, Line(0,                   5.0 * self.pitch_mm, 1.0 * self.width_mm, 0))
        start_point = rotate((0.0 * self.width_mm, 5.0 * self.pitch_mm),
                             rotation_ccw)
        end_point = rotate((1.0 * self.width_mm, 5.0 * self.pitch_mm),
                           rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        # self.add(self.NO_OFFSET, Line(0,                   6.0 * self.pitch_mm, 1.0 * self.width_mm, 0))
        start_point = rotate((0.0 * self.width_mm, 6.0 * self.pitch_mm),
                             rotation_ccw)
        end_point = rotate((1.0 * self.width_mm, 6.0 * self.pitch_mm),
                           rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        # self.add(self.NO_OFFSET, Line(0,                  10.0 * self.pitch_mm, 1.0 * self.width_mm, 0))
        start_point = rotate((0.0 * self.width_mm, 10.0 * self.pitch_mm),
                             rotation_ccw)
        end_point = rotate((1.0 * self.width_mm, 10.0 * self.pitch_mm),
                           rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        # Vertical
        start_point = rotate((0, 4.0 * self.pitch_mm), rotation_ccw)
        end_point = rotate((0, 5.0 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((0, 6.0 * self.pitch_mm), rotation_ccw)
        end_point = rotate((0, 10.0 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((self.width_mm / 2, 3.0 * self.pitch_mm),
                             rotation_ccw)
        end_point = rotate((self.width_mm / 2, 10.0 * self.pitch_mm),
                           rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((self.width_mm / 2, 0.0 * self.pitch_mm),
                             rotation_ccw)
        end_point = rotate((self.width_mm / 2, 3.0 * self.pitch_mm),
                           rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((self.width_mm, 0.0 * self.pitch_mm),
                             rotation_ccw)
        end_point = rotate((self.width_mm, 10.0 * self.pitch_mm), rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))

        start_point = rotate((1.25 * self.width_mm, 0.0 * self.pitch_mm),
                             rotation_ccw)
        end_point = rotate((1.25 * self.width_mm, 4.0 * self.pitch_mm),
                           rotation_ccw)
        self.add(self.NO_OFFSET, Line(start_point, end_point))
class LaneFinder:
    def __init__(self, parallel_thresh=(0.0003, 0.55), lane_dist_thresh=(300, 460), n_frames=1):
        self.n_frames = n_frames
        self.left_line = None
        self.right_line = None   
        self.curvature_radius_left = 0
        self.curvature_radius_right = 0
        self.center_poly = None
        self.offset = 0   
        self.diag_frame_count = 0

        self.parallel_thresh = parallel_thresh
        self.lane_dist_thresh = lane_dist_thresh

        # Define the source points
        self.src = np.float32([[ 300, Y_BOTTOM],    # bottom left
                        [ 580, Y_HORIZON],          # top left
                        [ 730, Y_HORIZON],          # top right
                        [1100, Y_BOTTOM]])          # bottom right

        # Define the destination points
        self.dst = np.float32([
            (self.src[0][0]  + OFFSET, Y_BOTTOM),
            (self.src[0][0]  + OFFSET, 0),
            (self.src[-1][0] - OFFSET, 0),
            (self.src[-1][0] - OFFSET, Y_BOTTOM)])

        # Compute the perspective transform
        self.M = cv2.getPerspectiveTransform(self.src, self.dst)
        self.Minv = cv2.getPerspectiveTransform(self.dst, self.src)


   # Detect lane lines using the sliding window approach for the first frame
    def process_image(self, orig_image, diag=False):
        rawImageProcessor = RawImageProcessor()

        # 1. Correct image distortion
        image_undist = rawImageProcessor.undistort(orig_image)

        # 2. Create thresholded binary image
        image_thres = rawImageProcessor.binary_pipeline(image_undist)
        
        # 3. Apply perspective transform to create a bird's-eye view 
        image_warp = self.__warp(image_thres)

        # 4. Detect and plot the lane
        image_final, out_img = self.__detect_lanes(image_warp, image_undist)

        if (diag==False):
            return image_final

        # 3. Optional: return the diagnostic image instead
        diag_image = self.__create_diag_output(image_undist, image_thres, out_img, image_final)

        return diag_image


    # Detect lane lines using the sliding window approach for the first frame
    # After the first frame the algorith will search in a margin around the previous line position.
    # This appraoch speeds up video processing
    def process_video_frame(self, frame):
        rawImageProcessor = RawImageProcessor()

        # 1. Correct image distortion
        image_undist = rawImageProcessor.undistort(frame)

        # 2. Create thresholded binary image
        image_thres = rawImageProcessor.binary_pipeline(image_undist)
        
        # 3. Apply perspective transform to create a bird's-eye view 
        image_warp = self.__warp(image_thres)

        # 4. Detect and plot the lane
        if (self.left_line is not None and self.right_line is not None and self.left_line.best_fit_exits() 
            and self.right_line.best_fit_exits()):
            # Use existing polynomes as starting point
            lanes_found, image_final, out_img = self.__search_around_poly(image_warp, image_undist)
            if not lanes_found:
                # Fallback, start from scratch at current frame
                image_final, out_img = self.__detect_lanes(image_warp, image_undist)     
        else:
            # Start from scratch
            image_final, out_img = self.__detect_lanes(image_warp, image_undist)

        out_img = self.__create_diag_output(image_undist, image_thres, out_img, image_final)
        if self.diag_frame_count == 12:
            mpimg.imsave('Term1/CarND-Advanced-Lane-Lines/output_images/video_frame_output.jpg', out_img)
        self.diag_frame_count += 1
        return out_img

  
    # Uses a sliding window algorithm to identify pixels within the image
    # which are part of a lane line
    def __sliding_window(self, binary_warped):
        # Take a histogram of the bottom half of the image
        histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)
        # Create an output image to draw on and visualize the result
        out_img = np.dstack((binary_warped, binary_warped, binary_warped))
        # Find the peak of the left and right halves of the histogram
        # These will be the starting point for the left and right lines
        midpoint = np.int(histogram.shape[0]//2)
        leftx_base = np.argmax(histogram[:midpoint])
        rightx_base = np.argmax(histogram[midpoint:]) + midpoint

        # HYPERPARAMETERS
        # Choose the number of sliding windows
        nwindows = 9
        # Set the width of the windows +/- margin
        margin = 90
        # Set minimum number of pixels found to recenter window
        minpix = 60

        # Set height of windows - based on nwindows above and image shape
        window_height = np.int(binary_warped.shape[0]//nwindows)
        # Identify the x and y positions of all nonzero pixels in the image
        nonzero = binary_warped.nonzero()
        nonzeroy = np.array(nonzero[0])
        nonzerox = np.array(nonzero[1])
        # Current positions to be updated later for each window in nwindows
        leftx_current = leftx_base
        rightx_current = rightx_base

        # Create empty lists to receive left and right lane pixel indices
        left_lane_inds = []
        right_lane_inds = []

        # Step through the windows one by one
        for window in range(nwindows):
            # Identify window boundaries in x and y (and right and left)
            win_y_low = binary_warped.shape[0] - (window+1)*window_height
            win_y_high = binary_warped.shape[0] - window*window_height
            win_xleft_low = leftx_current - margin
            win_xleft_high = leftx_current + margin
            win_xright_low = rightx_current - margin
            win_xright_high = rightx_current + margin
            
            # Draw the windows on the visualization image
            cv2.rectangle(out_img,(win_xleft_low,win_y_low),
            (win_xleft_high,win_y_high),(0,255,0), 2) 
            cv2.rectangle(out_img,(win_xright_low,win_y_low),
            (win_xright_high,win_y_high),(0,255,0), 2) 
            
            # Identify the nonzero pixels in x and y within the window #
            good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & 
            (nonzerox >= win_xleft_low) &  (nonzerox < win_xleft_high)).nonzero()[0]
            good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & 
            (nonzerox >= win_xright_low) &  (nonzerox < win_xright_high)).nonzero()[0]
            
            # Append these indices to the lists
            left_lane_inds.append(good_left_inds)
            right_lane_inds.append(good_right_inds)
            
            # If you found > minpix pixels, recenter next window on their mean position
            if len(good_left_inds) > minpix:
                leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
            if len(good_right_inds) > minpix:        
                rightx_current = np.int(np.mean(nonzerox[good_right_inds]))

        # Concatenate the arrays of indices (previously was a list of lists of pixels)
        
        left_lane_inds = np.concatenate(left_lane_inds)
        right_lane_inds = np.concatenate(right_lane_inds)

        # Extract left and right line pixel positions
        leftx = nonzerox[left_lane_inds]
        lefty = nonzeroy[left_lane_inds] 
        rightx = nonzerox[right_lane_inds]
        righty = nonzeroy[right_lane_inds]

        return leftx, lefty, rightx, righty, out_img


    # Determines if detected lane lines are plausible lines based on curvature and distance
    def __check_lane_quality(self, left, right):
        if len(left[0]) < MIN_POINTS_REQUIRED or len(right[0]) < MIN_POINTS_REQUIRED:
            return False
        else:
            new_left = Line(detected_y=left[0], detected_x=left[1])
            new_right = Line(detected_y=right[0], detected_x=right[1])

            parallel_check = new_left.check_lines_parallel(new_right, threshold=self.parallel_thresh)
            dist = new_left.distance_between_lines(new_right)
            dist_check = self.lane_dist_thresh[0] < dist < self.lane_dist_thresh[1]

            return parallel_check & dist_check

    # Check detected lines against each other and against previous frames' lines to ensure they are valid lines
    def __validate_lines(self, left_points, right_points):
        left_detected = False
        right_detected = False

        if self.__check_lane_quality(left_points, right_points):
            left_detected = True
            right_detected = True
        elif self.left_line is not None and self.right_line is not None:
            if self.__check_lane_quality(left_points, (self.left_line.ally, self.left_line.allx)):
                left_detected = True
            if self.__check_lane_quality(right_points, (self.right_line.ally, self.right_line.allx)):
                right_detected = True

        return left_detected, right_detected


    # Calculate the line curvature (in meters)
    def __calc_curvature_radius(self, fit_cr):
        y = np.array(np.linspace(0, IMAGE_MAX_Y, num=10))
        x = np.array([fit_cr(x) for x in y])
        y_eval = np.max(y)

        fit_cr = np.polyfit(y * YM_PER_PIXEL, x * XM_PER_PIXEL, 2)
        curverad = ((1 + (2 * fit_cr[0] * y_eval / 
                    2. + fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * fit_cr[0])

        return curverad


    # Perspective transformation to bird's eye view
    def __warp(self, image):
        return cv2.warpPerspective(image, self.M, (image.shape[1], image.shape[0]), flags=cv2.INTER_LINEAR)

    # Reverse perspective transformation
    def __warp_inv(self, image):
        return cv2.warpPerspective(image, self.Minv, (image.shape[1], image.shape[0]), flags=cv2.INTER_LINEAR)


    # Detect lane lines using the sliding window approach 
    def __detect_lanes(self, image_warp, image_undist):
        left_detected = right_detected = False

        # Get lane pixels for left and right lane using sliding window approach
        # out_img contains visualization of the process
        leftx, lefty, rightx, righty, out_img = self.__sliding_window(image_warp)

        ## Visualization ##
        # Colors in the left and right lane regions
        out_img[lefty, leftx] = [255, 0, 0]
        out_img[righty, rightx] = [0, 0, 255]

        if not left_detected or not right_detected:
            left_detected, right_detected = self.__validate_lines((leftx, lefty ),
                                                                  (rightx, righty ))

        # Update line information
        if left_detected:
            if self.left_line is not None:
                self.left_line.update(y = leftx, x = lefty)
            else:
                self.left_line = Line(self.n_frames,
                                      detected_y = leftx,
                                      detected_x = lefty)

        if right_detected:
            if self.right_line is not None:
                self.right_line.update(y = rightx, x = righty)
            else:
                self.right_line = Line(self.n_frames,
                                       detected_y = rightx,
                                       detected_x = righty)

        # Draw the lane and add additional information
        if self.left_line is not None and self.right_line is not None:
            self.curvature_radius_left = self.__calc_curvature_radius(self.left_line.best_fit_poly)
            self.curvature_radius_right = self.__calc_curvature_radius(self.right_line.best_fit_poly)
            self.center_poly = (self.left_line.best_fit_poly + self.right_line.best_fit_poly) / 2
            self.offset = (image_undist.shape[1] / 2 - self.center_poly(IMAGE_MAX_Y)) * XM_PER_PIXEL

            image_undist = self.__plot_lane(image_undist, image_warp)  
        return image_undist, out_img


    # Another approach to detec lane lines. This one uses the information
    # about line location from the previous video frame to narrow down
    # the area of intest.
    def __search_around_poly(self, image_warp, image_undist):
        # HYPERPARAMETER
        # Choose the width of the margin around the previous polynomial to search
        # The quiz grader expects 100 here, but feel free to tune on your own!
        margin = 70
        out_img = None

        # Grab activated pixels
        nonzero = image_warp.nonzero()
        nonzeroy = np.array(nonzero[0])
        nonzerox = np.array(nonzero[1])

        left_fit = self.left_line.best_fit
        right_fit = self.right_line.best_fit

        left_lane_inds = ((nonzerox > (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + 
                        left_fit[2] - margin)) & (nonzerox < (left_fit[0]*(nonzeroy**2) + 
                        left_fit[1]*nonzeroy + left_fit[2] + margin)))
        right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + 
                        right_fit[2] - margin)) & (nonzerox < (right_fit[0]*(nonzeroy**2) + 
                        right_fit[1]*nonzeroy + right_fit[2] + margin)))
            
        # Again, extract left and right line pixel positions
        leftx = nonzerox[left_lane_inds]
        lefty = nonzeroy[left_lane_inds] 
        rightx = nonzerox[right_lane_inds]
        righty = nonzeroy[right_lane_inds]

        left_detected, right_detected =self.__validate_lines((leftx, lefty), (rightx, righty))
        if left_detected and right_detected:
            self.left_line.update(y = leftx, x = lefty)
            self.right_line.update(y = rightx, x = righty)

            ## Visualization ##
            # Create an image to draw on and an image to show the selection window
            ploty = np.linspace(0, image_warp.shape[0]-1, image_warp.shape[0])
            left_fitx = (self.left_line.current_fit[0]*ploty**2 + self.left_line.current_fit[1]*ploty + 
                         self.left_line.current_fit[2])
            right_fitx = (self.right_line.current_fit[0]*ploty**2 + self.right_line.current_fit[1]*ploty + 
                          self.right_line.current_fit[2])

            out_img = np.dstack((image_warp, image_warp, image_warp))*255
            window_img = np.zeros_like(out_img)

            # Color in left and right line pixels
            out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]
            out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]

            # Generate a polygon to illustrate the search window area
            # And recast the x and y points into usable format for cv2.fillPoly()
            left_line_window1 = np.array([np.transpose(np.vstack([left_fitx-margin, ploty]))])
            left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx+margin, 
                                    ploty])))])
            left_line_pts = np.hstack((left_line_window1, left_line_window2))
            right_line_window1 = np.array([np.transpose(np.vstack([right_fitx-margin, ploty]))])
            right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx+margin, 
                                    ploty])))])
            right_line_pts = np.hstack((right_line_window1, right_line_window2))

            # Draw the lane onto the warped blank image
            cv2.fillPoly(window_img, np.int_([left_line_pts]), (0,255, 0))
            cv2.fillPoly(window_img, np.int_([right_line_pts]), (0,255, 0))

            # Plot the polynomial lines onto the image
            out_img = cv2.addWeighted(out_img, 0.9, window_img, 0.1, 0)
            cv2.polylines(out_img, np.int_([np.array([np.transpose(np.vstack([right_fitx, ploty]))])]),  False,  (255, 240, 0),  thickness=3)
            cv2.polylines(out_img, np.int_([np.array([np.transpose(np.vstack([left_fitx, ploty]))])]),  False,  (255, 240, 0),  thickness=3)

            ## End visualization steps ##

        
            # Draw the lane and add additional information
            if self.left_line is not None and self.right_line is not None:
                self.curvature_radius_left = self.__calc_curvature_radius(self.left_line.best_fit_poly)
                self.curvature_radius_right = self.__calc_curvature_radius(self.right_line.best_fit_poly)
                self.center_poly = (self.left_line.best_fit_poly + self.right_line.best_fit_poly) / 2
                self.offset = (image_undist.shape[1] / 2 - self.center_poly(IMAGE_MAX_Y)) * XM_PER_PIXEL

                image_undist = self.__plot_lane(image_undist, image_warp)
                lanes_found = True
        else:
            lanes_found = False

        return lanes_found, image_undist, out_img


    # Plot the detected lane and information about curvature radius and car off-center 
    def __plot_lane(self, imgage_org, imgage_warp):
        warp_zero = np.zeros_like(imgage_warp).astype(np.uint8)
        color_warp = np.dstack((warp_zero, warp_zero, warp_zero))

        # Recast the x and y points into usable format for cv2.fillPoly()
        yrange = np.linspace(0, 720)
        fitted_left_x = self.left_line.best_fit_poly(yrange)
        fitted_right_x = self.right_line.best_fit_poly(yrange)

        pts_left = np.array([np.transpose(np.vstack([fitted_left_x, yrange]))])
        pts_right = np.array([np.flipud(np.transpose(np.vstack([fitted_right_x, yrange])))])
        pts = np.hstack((pts_left, pts_right))

        # Draw the lane onto the warped blank image
        cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))

        # Warp the blank image back to original image space using inverse perspective matrix (Minv)
        newwarp = self.__warp_inv(color_warp)

        # Combine the result with the original image
        result = cv2.addWeighted(imgage_org, 1, newwarp, 0.3, 0)
                                                                               
        # Add information overlay rectangle
        font = cv2.FONT_HERSHEY_SIMPLEX
        result_overlay = result.copy()
        cv2.rectangle(result_overlay, (10, 10), (410, 150), (255, 255, 255), -1)
        cv2.addWeighted(result_overlay, 0.7, result, 0.3, 0, result)

        lane_center_x = int(self.center_poly(IMAGE_MAX_Y))
        image_center_x = int(result.shape[1] / 2)
        offset_from_centre = (image_center_x - lane_center_x) * XM_PER_PIXEL               # in meters
        
        # Add curvature and offset information
        font_color = (60, 60, 60) # dark grey
        left_right = 'left' if offset_from_centre < 0 else 'right'
        cv2.putText(result, "{:>14}: {:.2f}m ({})".format("off-center", abs(offset_from_centre), left_right),
                    (24, 50), font, 0.8, font_color, 2)

        text = "{:.1f}m".format(self.curvature_radius_left)
        cv2.putText(result, "{:>15}: {}".format("Left curvature", text), (19, 90), font, 0.8, font_color, 2)

        text = "{:.1f}m".format(self.curvature_radius_right)
        cv2.putText(result, "{:>15}: {}".format("Right curvature", text), (15, 130), font, 0.8, font_color, 2)

        return result


    def __create_diag_output(self, image, preprocessed_image, warp_image, image_final):
        # Create a combined image with final result and intermidiate processing steps
        diag_output = np.zeros((1080, 1280, 3), dtype=np.uint8)

        # Main screen
        diag_output[0:720, 0:1280] = image_final

        # Three screens along the bottom
        diag_output[720:1080, 0:426] = cv2.resize(image, (426,360), interpolation=cv2.INTER_AREA)            # original frame
        
        color_thresh = np.dstack((preprocessed_image, preprocessed_image, preprocessed_image)) * 255
        diag_output[720:1080, 426:852] = cv2.resize(color_thresh, (426,360), interpolation=cv2.INTER_AREA)    # undistorted binary filtered
       
        if len(warp_image.shape) == 2:
            color_warp = np.dstack((warp_image, warp_image, warp_image)) * 255
        else:
            color_warp = warp_image
        diag_output[720:1080, 852:1278] = cv2.resize(color_warp, (426,360), interpolation=cv2.INTER_AREA)   # warped image

        return diag_output
from Line import Line
from Rectangle import Rectangle
from Text import Text
from Picture import Picture

if __name__ == '__main__':
    picture1 = Picture()
    picture1.add(Line())
    picture1.add(Rectangle())

    picture2 = Picture()
    picture2.add(Text())
    picture2.add(Line())
    picture2.add(Rectangle())

    picture1.add(picture2)

    picture1.add(Line())
    picture1.draw()
示例#41
0
 def givebirth(self):
     line = Line()
     line.ignoreMe = False
     # line.parent=self
     return line
示例#42
0
def string(line: str) -> Parsed:
    line = Line(line)
    return head(line)
示例#43
0
class Lane_Detector:

    def __init__(self, n_frames=1, line_segments = 10, transform_offset=0):
        """
        Tracks lane lines on images or a video stream using techniques like Sobel operation, color thresholding and
        sliding histogram.
        :param perspective_src: Source coordinates for perspective transformation
        :param perspective_dst: Destination coordinates for perspective transformation
        :param n_frames: Number of frames which will be taken into account for smoothing
        :param cam_calibration: calibration object for distortion removal
        :param line_segments: Number of steps for sliding histogram and when drawing lines
        :param transform_offset: Pixel offset for perspective transformation
        """
        self.n_frames = n_frames
        self.line_segments = line_segments
        self.image_offset = transform_offset

        self.left_line = None
        self.right_line = None
        self.center_poly = None
        self.curvature = 0.0
        self.offset = 0.0

        self.dists = []


    def __line_plausible(self, left, right):
        """
        Determines if pixels describing two line are plausible lane lines based on curvature and distance.
        :param left: Tuple of arrays containing the coordinates of detected pixels
        :param right: Tuple of arrays containing the coordinates of detected pixels
        :return:
        """
        if len(left[0]) < 3 or len(right[0]) < 3:
            return False
        else:
            new_left = Line(y=left[0], x=left[1])
            new_right = Line(y=right[0], x=right[1])
            return are_lanes_plausible(new_left, new_right)

    def __check_lines(self, left_x, left_y, right_x, right_y):
        """
        Compares two line to each other and to their last prediction.
        :param left_x:
        :param left_y:
        :param right_x:
        :param right_y:
        :return: boolean tuple (left_detected, right_detected)
        """
        left_detected = False
        right_detected = False

        if self.__line_plausible((left_x, left_y), (right_x, right_y)):
            left_detected = True
            right_detected = True
        elif self.left_line is not None and self.right_line is not None:
            if self.__line_plausible((left_x, left_y), (self.left_line.ally, self.left_line.allx)):
                left_detected = True
            if self.__line_plausible((right_x, right_y), (self.right_line.ally, self.right_line.allx)):
                right_detected = True

        return left_detected, right_detected

    def __draw_info_panel(self, img):
        """
        Draws information about the center offset and the current lane curvature onto the given image.
        :param img:
        """
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img, 'Radius of Curvature = %d(m)' % self.curvature, (50, 50), font, 1, (255, 255, 255), 2)
        left_or_right = 'left' if self.offset < 0 else 'right'
        cv2.putText(img, 'Vehicle is %.2fm %s of center' % (np.abs(self.offset), left_or_right), (50, 100), font, 1,
                    (255, 255, 255), 2)

    def __draw_lane_overlay(self, img, capture_region):
        """
        Draws the predicted lane onto the image. Containing the lane area, center line and the lane lines.
        :param img:
        """
        overlay = np.zeros([*img.shape])
        mask = np.zeros([img.shape[0], img.shape[1]])

        # lane area
        lane_area = calculate_lane_area((self.left_line, self.right_line), img.shape[0], 20)
        mask = cv2.fillPoly(mask, np.int32([lane_area]), 1)
        mask = BirdsEyePerspectiveInverse(mask, capture_region)

        overlay[mask == 1] = (255, 128, 0)
        selection = (overlay != 0)
        img[selection] = img[selection] * 0.3 + overlay[selection] * 0.7

        # center line
        mask[:] = 0
        mask = draw_poly_arr(mask, self.center_poly, 20, 255, 5, True, tip_length=0.5)
        mask = BirdsEyePerspectiveInverse(mask, capture_region)
        img[mask == 255] = (255, 75, 2)

        # lines best
        mask[:] = 0
        mask = draw_poly(mask, self.left_line.best_fit_poly, 5, 255)
        mask = draw_poly(mask, self.right_line.best_fit_poly, 5, 255)
        mask = BirdsEyePerspectiveInverse(mask, capture_region)
        img[mask == 255] = (255, 200, 2)

    def process_screengrab(self, orig_image, capture_region):

        # topleftx, toplefty, botrightx, botrighty = capture_region
        tlx, tly, brx, bry = capture_region
        w = brx - tlx
        h = bry - tly
        t = tly     # t = tly = 40
        b = bry     # b = bry = 520
        l = tlx     # t = tlx = 0
        r = brx     # r = brx = 640

        # 3rd person camera adjustments
        vertices=mask_vertices(l,t,b,r,w,h)
        roi_extracted_image = mask_image(orig_image,vertices)

        # Focussing on the road portion of the image
        # This depends on camera settings from game to game
        v_cutoff = np.int(0.35*h)
        mask_3ch = generate_lane_mask(roi_extracted_image, v_cutoff=v_cutoff)
        lane_masked_image = cv2.bitwise_and(roi_extracted_image, mask_3ch)
        # Convert to a binary mask
        mask = mask_3ch[:,:,0]

        mask_1ch =  mask * ((mask == 255).astype('uint8'))

        # Applying the Birds Eye Transformation
        #mask = mask_1ch
        mask_birdeye = BirdsEyePerspective(mask_1ch, capture_region)

        # Always pass a 1-D array to histogram function.
        # Hence, we need to convert from 3-channel color image to grayscale
        #processed_image = cv2.cvtColor(processed_image, cv2.COLOR_RGB2GRAY)

        left_detected = right_detected = False
        left_x = left_y = right_x = right_y = []

        # If there have been lanes detected in the past, the algorithm will first try to
        # find new lanes along the old one. This will improve performance

        if self.left_line is not None and self.right_line is not None:
            left_x, left_y = detect_lane_along_poly(mask_birdeye, self.left_line.best_fit_poly, self.line_segments)
            right_x, right_y = detect_lane_along_poly(mask_birdeye, self.right_line.best_fit_poly, self.line_segments)

            left_detected, right_detected = self.__check_lines(left_x, left_y, right_x, right_y)

        # If no lanes are found a histogram search will be performed
        if not left_detected:
            left_x, left_y = histogram_lane_detection(
                mask_birdeye, self.line_segments, (self.image_offset, np.int(0.5*lane_masked_image.shape[1])), h_window=7)
            left_x, left_y = outlier_removal(left_x, left_y)
        if not right_detected:
            right_x, right_y = histogram_lane_detection(
                mask_birdeye, self.line_segments, (np.int(0.5*lane_masked_image.shape[1]), lane_masked_image.shape[1] - self.image_offset), h_window=7)
            right_x, right_y = outlier_removal(right_x, right_y)

        if not left_detected or not right_detected:
            left_detected, right_detected = self.__check_lines(left_x, left_y, right_x, right_y)

        print(left_detected, right_detected)

        # Updated left lane information.
        if left_detected:
            # switch x and y since lines are almost vertical
            if self.left_line is not None:
                self.left_line.update(y=left_x, x=left_y)
            else:
                self.left_line = Line(self.n_frames, left_y, left_x)

        # Updated right lane information.
        if right_detected:
            # switch x and y since lines are almost vertical
            if self.right_line is not None:
                self.right_line.update(y=right_x, x=right_y)
            else:
                self.right_line = Line(self.n_frames, right_y, right_x)

        # Add information onto the frame
        if self.left_line is not None and self.right_line is not None:
            self.dists.append(self.left_line.get_best_fit_distance(self.right_line))
            self.center_poly = (self.left_line.best_fit_poly + self.right_line.best_fit_poly) / 2
            self.curvature = calc_curvature(self.center_poly)
            self.offset = (lane_masked_image.shape[1] / 2 - self.center_poly(719)) * 3.7 / 700

            self.__draw_lane_overlay(orig_image, capture_region)
            self.__draw_info_panel(orig_image)


        return mask_birdeye, mask_1ch, lane_masked_image, roi_extracted_image, orig_image
示例#44
0
def analyze(name: str, query_genome_path: str, ref_genome_path: str,
            segments_file_path: str, show_plot: bool, output_folder: str,
            settings: dict):
    print("---| {} |---".format(name))

    output_folder = mkpath(ROOT_PATH, output_folder)

    if not os.path.exists(mkpath(output_folder)):
        os.mkdir(mkpath(output_folder))

    setSettings(settings, mkpath(output_folder, "settings.json"))

    with open(mkpath(ROOT_PATH, "src", "analysis", "STORAGE",
                     "CIGAR_FLAGS.json"),
              'r',
              encoding="utf-8") as file:
        CIGAR_FLAGS = json_load(file, encoding="utf-8")

    with open(mkpath(ROOT_PATH, query_genome_path), 'r',
              encoding="utf-8") as file:
        for name, sequence in SimpleFastaParser(file):
            query_genome_name = name
            query_genome_length = len(sequence)
            break

    with open(mkpath(ROOT_PATH, ref_genome_path), 'r',
              encoding="utf-8") as file:
        for name, sequence in SimpleFastaParser(file):
            ref_genome_name = name
            ref_genome_length = len(sequence)
            break

    print("Query: {} [{}]".format(query_genome_name,
                                  prtNum(query_genome_length)))
    print("Reference: {} [{}]\n".format(ref_genome_name,
                                        prtNum(ref_genome_length)))

    # ====================================================================================================================================================================
    # Creating plot
    print("Creating plot...")

    plot = Plot("Main plot", settings["fontsize"], settings["grid_size"],
                settings["figsize"], query_genome_name, ref_genome_name)
    plot.legendLine(
        {
            "Insertion": "#0f0",
            "Deletion": "#f00",
            "Duplication": "#f0f",
            "Translocation": "#0ff"
        },
        fontsize=settings["fontsize"],
        lw=2)

    # return
    # ====================================================================================================================================================================
    # Parse input file and create dots
    print("Reading input file and creating dots...")

    if os.path.splitext(segments_file_path)[1] == ".sam":
        graph = read_dots_from_sam(mkpath(ROOT_PATH, segments_file_path),
                                   settings, CIGAR_FLAGS, query_genome_length,
                                   ref_genome_length)

    else:
        # graph = read_dots_from_sam(mkpath(ROOT_PATH, "BWA/large01/bwa_output.sam"), settings, CIGAR_FLAGS, query_genome_length, ref_genome_length)
        graph = read_dots_from_alignment(mkpath(ROOT_PATH, segments_file_path),
                                         query_genome_length)

    # return


# ====================================================================================================================================================================
# Counting lines
    print("Counting lines...", end="")

    lines_join_size2 = settings["lines_join_size"]**2
    line_min_size2 = settings["line_min_size"]**2

    lines = []

    for x in range(0, len(graph), settings["dot_skip_rate"]):
        # if x % 100 == 0:
        #     print(x, len(lines))
        for y in graph[x]:
            for line in lines:
                if distance2(x, y, *line.dots[-1]) <= lines_join_size2 and \
                        (len(line.dots) == 1 or distance2(x, y, *line.dots[-2]) <= lines_join_size2):
                    line.dots.append([x, y])
                    break
            else:
                lines.append(Line(dots=[[x, y]]))

    for line in lines:
        line.dots.sort()

        line.start_x, line.start_y = line.dots[0]
        line.end_x, line.end_y = line.dots[-1]

        if len(line.dots) >= 2:
            k, b = linearApproxDots(line.dots)  # \
            line.start_y = int(k * line.start_x +
                               b)  # |--> Approximation  TODO: int
            line.end_y = int(k * line.end_x + b)  # /

        # line[4] = line[4][::settings["dot_skip_rate"]]  # Optional compress

    lines = [
        line for line in lines
        if distance2(line.start_x, line.start_y, line.end_x, line.end_y) >=
        line_min_size2
    ]

    lines.sort(key=lambda line: (line.start_x, line.start_y))

    print(" {} lines".format(len(lines)))
    print("Lines:", *lines, sep='\n')

    # for line in lines:
    #     plot.plotLine(line)
    # plot.show()

    # return
    # ====================================================================================================================================================================
    # Shift and rotations
    print("\nCounting shift and rotations...")

    # not_shifted_lines = deepcopy(lines)

    def countMetric(lines):
        result = 0

        # First option:
        # k, b = linearApproxLines(lines)
        # main_line = Line(0, b, query_genome_length, query_genome_length * k + b)

        # Second option:
        # main_line = Line(0, 0, query_genome_length, query_genome_length) -> Second "for" option

        # Third option: TODO - approx with k: 1, b: search

        # Fourth option: TODO - approx with k: search, b: 0

        # First "for" option:
        # for line in lines:
        #     result += int((line.start_y - YCoordOnLine(*main_line.coords, line.start_x)) ** 2)
        #     result += int((line.end_y - YCoordOnLine(*main_line.coords, line.end_x)) ** 2)

        # Second "for" option:
        for line in lines:
            result += int((line.start_y - line.start_x)**2) + int(
                (line.end_y - line.end_x)**2)

        return result

    def countMetricWithRotation(lines, rotation, apply_rotation=False) -> int:
        rotation_center = (min(lines[rotation.start_line].start_y, lines[
            rotation.start_line].end_y, lines[rotation.end_line].start_y,
                               lines[rotation.end_line].end_y) +
                           max(lines[rotation.start_line].start_y,
                               lines[rotation.start_line].end_y,
                               lines[rotation.end_line].start_y,
                               lines[rotation.end_line].end_y)) // 2

        for line_index in range(rotation.start_line, rotation.end_line + 1):
            lines[line_index].rotateY(rotation_center)

        metric_value = countMetric(lines)

        if not apply_rotation:
            for line_index in range(rotation.start_line,
                                    rotation.end_line + 1):
                lines[line_index].rotateY(rotation_center)

        if apply_rotation:
            rotation.rotation_center = rotation_center
            for line_index in range(rotation.start_line,
                                    rotation.end_line + 1):
                lines[line_index].rotateY(rotation_center,
                                          line=False,
                                          dots=True)

        return metric_value

    def countBestRotations(rotated_lines) -> List[Line]:
        possible_rotations = [
            Rotation(start_line, end_line)
            for start_line in range(len(rotated_lines))
            for end_line in range(start_line, len(rotated_lines))
        ]
        # print("\nPossible rotations:", *possible_rotations, sep='\n')

        cur_metric_value = countMetric(rotated_lines)
        rotation_actions = []

        # if draw:
        #     fastDrawLines(plot, rotated_lines, save=mkpath(output_folder, "history", "x0.png"))
        #     index = 1

        while True:
            best_metric_value = float('inf')
            best_rotation_index = 0

            for i, rotation in enumerate(possible_rotations):
                # TODO: WORKAROUND #1
                min_line_center, max_line_center = float('inf'), float("-inf")
                for line_index in range(rotation.start_line,
                                        rotation.end_line + 1):
                    min_line_center = min(min_line_center,
                                          rotated_lines[line_index].center_y)
                    max_line_center = max(max_line_center,
                                          rotated_lines[line_index].center_y)
                bad = False
                for line_index in range(len(rotated_lines)):
                    if not (rotation.start_line <= line_index <= rotation.end_line) and \
                            min_line_center < rotated_lines[line_index].center_y < max_line_center:
                        bad = True
                if bad:
                    continue

                # TODO: WORKAROUND-CONDITION #2
                if rotated_lines[rotation.start_line].isTiltedCorrectly(
                ) or rotated_lines[rotation.end_line].isTiltedCorrectly():
                    continue

                cur_metric = countMetricWithRotation(rotated_lines, rotation)

                if cur_metric < best_metric_value:
                    best_metric_value = cur_metric
                    best_rotation_index = i

            if best_metric_value >= cur_metric_value:
                break

            cur_metric_value = countMetricWithRotation(
                rotated_lines,
                possible_rotations[best_rotation_index],
                apply_rotation=True)

            # print("\n{} -> {}".format(possible_rotations[best_rotation_index], cur_metric_value))
            # print("best_metric_value = {}".format(best_metric_value))
            # print("best_rotation_index = {}".format(best_rotation_index))

            rotation_actions.append(possible_rotations[best_rotation_index])

            # if draw:
            #     fastDrawLines(plot, rotated_lines, save=mkpath(output_folder, "history", "x{}.png".format(index)))

        # print("Final metric value: ", cur_metric_value, countMetric(rotated_lines))
        print("\nRotation actions:", *rotation_actions, sep='\n')
        # print("\nRotated lines:", *rotated_lines, sep='\n')

        # fastDrawLines(plot, rotated_lines, show=True)

        return cur_metric_value, rotated_lines, rotation_actions

    def countShift(lines, start_line, apply_shift=False) -> int:
        d_x = lines[start_line].start_x

        for line_index in range(start_line, len(lines)):
            lines[line_index].shift(dx=-d_x)

        for line_index in range(0, start_line):
            lines[line_index].shift(dx=query_genome_length - d_x)

        # print("\nLines:", *lines, sep='\n')

        rotated_lines = shiftLines(deepcopy(lines), start_line)
        # print("\nRotated lines:", *rotated_lines, sep='\n')

        metric_value, rotated_lines, rotation_actions = countBestRotations(
            rotated_lines)

        print("metric_value = {} or {}".format(
            metric_value, metric_value * len(rotation_actions)))

        if apply_shift:
            return shiftLines(lines,
                              start_line), rotated_lines, rotation_actions

        for line_index in range(start_line, len(lines)):
            lines[line_index].shift(dx=d_x)

        for line_index in range(0, start_line):
            lines[line_index].shift(dx=d_x - query_genome_length)

        return metric_value * len(rotation_actions)

    best_metric_value = float("inf")
    best_metric_value_start_line = 0

    for start_line in range(len(lines)):
        print("\n-| Counting with start_line = {}...".format(start_line))
        cur_metric_value = countShift(lines, start_line)

        if cur_metric_value < best_metric_value:
            best_metric_value = cur_metric_value
            best_metric_value_start_line = start_line

    print("\n===| Counting end result with start_line = {}...".format(
        best_metric_value_start_line))
    lines, rotated_lines, rotation_actions = countShift(
        lines, best_metric_value_start_line, apply_shift=True)

    # plot.clear()
    # for line in lines:
    #     plot.plotLine(line)
    # plot.show()
    # plot.clear()

    print("\nLines:", *lines, sep='\n')
    print("\nRotated lines:", *rotated_lines, sep='\n')

    # return
    # ====================================================================================================================================================================
    # Insertions and deletions
    print("\nCounting insertions and deletions...")

    spaceless_lines = deepcopy(rotated_lines)

    insertion_actions = []
    cur_pos, last_line_end = 0, 0
    for line in sorted(spaceless_lines, key=lambda line: line.start_y):
        if line.start_y > cur_pos:
            insertion_actions.append(Insertion(cur_pos,
                                               line.start_y - cur_pos))
        elif line.start_y < cur_pos:
            pass  # TODO: duplication Y

        cur_pos = max(cur_pos, line.end_y)
        line.shift(dy=last_line_end - line.start_y)
        last_line_end = line.end_y

    deletion_actions = []
    cur_pos, last_line_end = 0, 0
    for line in sorted(spaceless_lines, key=lambda line: line.start_x):
        if line.start_x > cur_pos:
            deletion_actions.append(Deletion(cur_pos, line.start_x - cur_pos))
        elif line.start_x < cur_pos:
            pass  # TODO: duplication X

        cur_pos = max(cur_pos, line.end_x)
        line.shift(dx=last_line_end - line.start_x)
        last_line_end = line.end_x

    large_insertion_actions = [
        action for action in insertion_actions
        if action.size >= settings["min_event_size"]
    ]
    large_deletion_actions = [
        action for action in deletion_actions
        if action.size >= settings["min_event_size"]
    ]

    print("\nLarge insertions:", *large_insertion_actions, sep='\n')
    print("\nLarge deletions:", *large_deletion_actions, sep='\n')

    # return
    # ====================================================================================================================================================================
    # Translocations
    print("\nCounting translocations....")

    translocation_actions = []

    def recountPos(end_line):
        last_x = spaceless_lines[end_line - 1].end_x if end_line > 0 else None
        last_y = spaceless_lines[end_line - 1].end_y if end_line > 0 else None
        next_x = spaceless_lines[
            end_line +
            1].start_x if end_line < len(spaceless_lines) - 1 else None
        next_y = spaceless_lines[
            end_line +
            1].start_y if end_line < len(spaceless_lines) - 1 else None
        return last_x, last_y, next_x, next_y

    start_line = 0

    while start_line < len(spaceless_lines):
        end_line = start_line
        last_x, last_y, next_x, next_y = recountPos(end_line)

        while end_line < len(spaceless_lines) and (
            (last_x is not None
             and not equalE(last_x, spaceless_lines[end_line].start_x, 3)) or
            (last_y is not None
             and not equalE(last_y, spaceless_lines[end_line].start_y, 3)) or
            (next_x is not None
             and not equalE(next_x, spaceless_lines[end_line].end_x, 3)) or
            (next_y is not None
             and not equalE(next_y, spaceless_lines[end_line].end_y, 3))):
            end_line += 1
            last_x, last_y, next_x, next_y = recountPos(end_line)

        if end_line - start_line > 1:
            order = [(i, lines[i])
                     for i in range(start_line + 1, end_line - 1)]
            order.sort(key=lambda item: item[1].center_y)
            translocation_actions.append(
                Translocation(start_line + 1, end_line - 2,
                              [i for i, line in order]))

        start_line = end_line + 1

    print("\nTranslocations:", *translocation_actions, sep='\n')

    # return
    # ====================================================================================================================================================================
    # Plotting dots, lines and large actions
    print("\nPlotting dots, lines and large actions...")

    for insertion in large_insertion_actions:
        plot.poligon(
            [(0, insertion.start_y), (0, insertion.start_y + insertion.height),
             (query_genome_length, insertion.start_y + insertion.height),
             (query_genome_length, insertion.start_y)],
            color=(0, 1, 0, 0.3))

    for deletion in large_deletion_actions:
        plot.poligon([(deletion.start_x, 0),
                      (deletion.start_x, ref_genome_length),
                      (deletion.start_x + deletion.length, ref_genome_length),
                      (deletion.start_x + deletion.length, 0)],
                     color=(1, 0, 0, 0.3))

    # for line in lines:
    #     plot.plotLine(line, color="#fa0")
    #     plot.scatter(line.dots[::settings["dot_skip_rate"]], dotsize=settings["dotsize"], color="#00f")

    for line in rotated_lines:
        plot.plotLine(line)

    for line in spaceless_lines:
        plot.plotLine(line, color="#0ff")

    # for line in not_shifted_lines:
    #     plot.scatter(line.dots[::settings["dot_skip_rate"]], dotsize=settings["dotsize"], color="#eee")

    print("Saving plot...")
    # plot.tight()
    plot.save(mkpath(output_folder, "sam_analyze.png"))

    if show_plot:
        print("Showing plot...")
        plot.show()

    plot.clear()

    # return
    # ====================================================================================================================================================================
    # Make and save history
    print("Making history...", end="")

    if not os.path.exists(mkpath(output_folder, "history")):
        os.mkdir(mkpath(output_folder, "history"))

    for filename in os.listdir(mkpath(output_folder, "history")):
        os.remove(mkpath(output_folder, "history", filename))

    large_actions = [Pass()] + rotation_actions + \
        sorted(large_insertion_actions + large_deletion_actions, key=lambda action: -action.size) + translocation_actions

    print(" {} records\n".format(len(large_actions)))
    # print("Large actions:", *large_actions, sep='\n')

    history_text_output = []
    for action in large_actions:

        if isinstance(action, Rotation):
            history_text_output.append(
                "Rotation from {} (Query) to {} (Query)".format(
                    prtNum(int(lines[action.start_line].start_x)),
                    prtNum(int(lines[action.end_line].end_x))))

        elif isinstance(action, Deletion):
            history_text_output.append("Deletion of {}-{} (Query)".format(
                prtNum(int(action.start_x)),
                prtNum(int(action.start_x + action.length))))

        elif isinstance(action, Insertion):
            history_text_output.append("Insertion of {}-{} (Ref)".format(
                prtNum(int(action.start_y)),
                prtNum(int(action.start_y + action.height))))

        elif isinstance(action, Translocation):
            history_text_output.append("Translocation (COMING SOON)")

        # elif isinstance(action, Duplication):
        #     history_text_output.append("Duplication of {}-{} (Query) {}-{} (Ref)".format(
        #         prtNum(int(action.start_x)),
        #         prtNum(int(action.start_x + action.length)),
        #         prtNum(int(action.start_y)),
        #         prtNum(int(action.start_y + action.height))
        #     ))

    with open(mkpath(output_folder, "history.txt"), 'w',
              encoding="utf-8") as file:
        file.write('\n\n'.join(history_text_output) + '\n')

    for action_index, action in enumerate(large_actions):

        if isinstance(action, Rotation):
            for line_index in range(action.start_line, action.end_line + 1):
                lines[line_index].rotateY(action.rotation_center,
                                          line=True,
                                          dots=True)

        elif isinstance(action, Insertion):
            for line in rotated_lines:

                if line.center_y >= action.start_y:
                    line.shift(dy=-action.height)

                # new_dots = []
                # for dot_x, dot_y in line.dots:
                #     if dot_y > action.start_y:
                #         dot_y -= action.height
                #     # if dot_x != action.start_x:
                #     #     new_dots.append([dot_x, dot_y])
                # line.dots = new_dots

            for i in range(action_index + 1, len(large_actions)):
                if isinstance(large_actions[i], Insertion):
                    if large_actions[i].start_y > action.start_y:
                        large_actions[i].start_y -= action.height

        elif isinstance(action, Deletion):
            for line in rotated_lines:
                if line.center_x >= action.start_x:
                    line.shift(dx=-action.length)

                # for i in range(len(line.dots)):
                #     if line.dots[i][0] >= action.start_x + action.length:
                #         line.dots[i][0] -= action.length

            for i in range(action_index + 1, len(large_actions)):
                if isinstance(large_actions[i], Deletion):
                    if large_actions[i].start_x > action.start_x:
                        large_actions[i].start_x -= action.length

        # elif isinstance(action, Duplication):
        #     new_dots = []
        #     for dot in rotated_lines[action.line_index].dots:
        #         if not (action.start_x <= dot[0] <= action.start_x + action.length):
        #             new_dots.append(dot)
        #     rotated_lines[action.line_index].dots = new_dots

        #     for line in rotated_lines:
        #         for i in range(len(line.dots)):
        #             if line.dots[i][0] >= action.start_x:
        #                 line.dots[i][1] -= action.height

        #     for i in range(action_index + 1, len(large_actions)):
        #         if large_actions[i].start_x >= action.start_x:
        #             large_actions[i].start_y -= action.height

        elif isinstance(action, Translocation):
            # tmp_rotated_lines = rotated_lines.copy()
            # for i in range(action.start_line, action.end_line + 1):
            #     rotated_lines[i] = tmp_rotated_lines[action.order[i - action.start_line]]

            # print("tmp_rotated_lines = ", *tmp_rotated_lines, sep='\n')
            # print("rotated_lines = ", *rotated_lines, sep='\n')

            # cur_x = min(rotated_lines[line_index].start_x for line_index in range(action.start_line, action.end_line + 1))
            cur_y = min(
                min(rotated_lines[line_index].start_y,
                    rotated_lines[line_index].end_y)
                for line_index in range(action.start_line, action.end_line +
                                        1))
            for line_index in range(action.start_line, action.end_line + 1):
                rotated_lines[line_index].shift(
                    # dx=cur_x - rotated_lines[line_index].start_x,
                    dy=cur_y - rotated_lines[line_index].start_y)
                # cur_x += rotated_lines[line_index].sizeX  # cur_x = rotated_lines[line_index].end_x
                cur_y += rotated_lines[
                    line_index].sizeY  # cur_y = rotated_lines[line_index].end_y

        elif isinstance(action, Pass):
            pass

        else:
            raise ValueError("History: Unknown action type")

        if isinstance(action, (Pass, Rotation)):
            # plot.scatter(dots, dotsize=settings["dotsize"], color="#00f")
            for line in lines:
                plot.scatter(line.dots,
                             dotsize=settings["dotsize"],
                             color="#00f")
        else:
            # Adjusting axes (bottom):
            bottom = float("inf")
            for line in rotated_lines:
                for dot_x, dot_y in line.dots:
                    bottom = min(bottom, dot_y)
            if bottom == float('inf'):
                bottom = 0

            for line in rotated_lines:
                line.shift(dy=-bottom)

            for i in range(action_index + 1, len(large_actions)):
                if hasattr(large_actions[i], "start_x") and hasattr(large_actions[i], "start_y") and \
                        large_actions[i].start_x >= action.start_x:
                    large_actions[i].start_y += bottom

            # for line in rotated_lines:
            #     plot.plotLine(line)

            for line in rotated_lines:
                plot.scatter(line.dots,
                             dotsize=settings["dotsize"],
                             color="#00f")

        print("Saving large action #{}{}...\n".format(
            action_index,
            "" if isinstance(action, Pass) else " ({})".format(action.type)))
        plot.tight()
        plot.save(
            mkpath(
                output_folder, "history", "{}{}.png".format(
                    str(action_index).zfill(3), "" if isinstance(action, Pass)
                    else " ({})".format(action.type))))
        plot.clear()

    del plot
示例#45
0
def main():
    # Choose Examples

    coordinatesA = ((-5, 5), (1, 2))
    line = Line(coordinatesA[0], coordinatesA[1])
    line.draw_line_normal()
示例#46
0
    print(dog.tale)
    print(dog.feet)
    dog.bark(5)
    dog.swing()
    dog.eat()  #this is an inherited method
    dog.who_am_i()
    print(dog)

    myCircle = Circle(30)
    print(myCircle.area)
    print(myCircle.get_circumference())

    coordinate1 = (3, 2)
    coordinate2 = (8, 10)

    li = Line(coordinate1, coordinate2)
    li.distance()
    li.slope()

    c = Cilindre(2, 3)
    c.volume()
    c.surface_area()
    #nr1 = HandleExceptions().get_int()
    #nr2 = HandleExceptions().get_int()

    #nr2=HandleExceptions.get_int()
    #nr2=int(input("Please add a number "))
    #result = HandleExceptions().sumNr(nr1, nr2) # here, for nr2, the fact that we are requesting a number via input - results a string. # therefore the error "TypeError: sumNr() missing 1 required positional argument: 'nr2'"# we need to cast it

    account1 = Account("Olga", 150)
    account1.deposit(52)
示例#47
0
# Main program -- production mode
if DEBUG == False:

    if len(sys.argv) == 1:
        print("The program main.py requires one video file as an argument")
    else:
        # Read a video file passed by sys.argv
        fname = sys.argv[1]
        if len(sys.argv) == 4:
            start = np.int_(sys.argv[2])
            end = np.int_(sys.argv[3])
            input_clip = VideoFileClip(fname).subclip(start, end)
        else:
            input_clip = VideoFileClip(fname)
        output_file = output_video_location + "/" + fname
        left_line = Line('left')
        right_line = Line('right')
        # Frame by frame visualization of lane line and road information
        output_clip = input_clip.fl_image(image_to_lane_visualization)
        # Write the output vide in a file
        output_clip.write_videofile(output_file, audio=False)

# Main program -- DEBUG mode
if DEBUG:
    # Go through the test files and output the intermediate pipeline steps into files
    for file in test_files:
        img = mpimg.imread(test_location + "/" + file)
        undist = undistort(img, mtx, dist)
        thresh = thresholding(undist)
        warped = warp(thresh, M)
        left_line = Line('left')
示例#48
0
from Line import Line
from Cylinder import Cylinder

coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)

print('Line Equation Test')
print(li.distance())
print(li.slope())

c = Cylinder(2,3)

print('Cylinder Equation Test')
print(c.volume())
print(c.surface_area())
示例#49
0
def EM_wall_mixture_model(points, K = 3, MAX_ITER = 30, init_from_gmm=True, force_connected=True, debug_output = None):
    """ initialization """
    N = points.shape[0]
    # init lines
    L = []
    if init_from_gmm:
        cen_lst, cov_lst, p_k, logL = gmm.em_gm(points, K = K)
        for cen, cov in zip(cen_lst, cov_lst):
            L.append(Line.fromEllipse(cen, cov))
    else:
        for k in range(K):
            L.append(Line.getRandom(points))
    # init pi
    pi_k = 1./K * ones(K)
    
    """ run algorithm """
    oldgamma = zeros((N, K))
    for iter_num in range(MAX_ITER):
        """ E-step """
        pi_times_prob = zeros((N, K))
        gamma = zeros((N, K))
        for n in range(N):
            for k in range(K):
                pi_times_prob[n,k] = pi_k[k] * L[k].Prob(points[n])
            # normalized version of pi_times_prob is gamma
            gamma[n,:] = pi_times_prob[n,:] / pi_times_prob[n,:].sum()

        """ debug output """
        if debug_output:
            debug_output(L, gamma, iter_num)
        
        """ M-step (general) """
        N_k = gamma.sum(0)
        pi_k = N_k / N_k.sum()
        
        """ M-step (gaussian mixture with inf primary eigenval) """
        eOptimizer = EOptimizer(L, gamma, pi_k, N_k, points, pi_times_prob)
        for k in range(K):
            """ get mean """
            mu = 1/N_k[k] * sum(gamma[n,k]*points[n] for n in range(N))
            """ get cov matrix """
            x = [array([points[n]-mu]).T for n in range(N)]
            cov = 1/N_k[k] * sum(gamma[n,k]*x[n]*x[n].T for n in range(N))
            # re-initilize M, alpha and sigma from ellipse
            L[k].updateFromEllipse(mu, cov)
            """ get e """
            eOptimizer.setK(k)
            L[k].e = eOptimizer.optimize()
        """ force that all lines are connected """
        for l in L:
            l.connectToNearestLines(L)
        
        """ check sanity of lines """
        for k in range(K):
            if L[k].inBadCondition():
                #print "L[%d] in bad condition" % k
                L[k] = Line.getRandom(points)
            for kk in range(k):
                if L[k].almostEqualTo(L[kk]):
                    #print "L[%d] almost equal to L[%d]" % (k, kk)
                    L[k] = Line.getRandom(points)
                    break
        
        """ remove 2 lines that are on same real line """
        DTHETA = 20 * pi/180 # margin
        for k, l in enumerate(L):
            for kk, line in ([kk, ll] for kk, ll in enumerate(L) if k != kk):
                if l.isConnectedTo(line) or l.isAlmostConnectedTo(line, L):
                    theta = l.getAngleWith(line)
                    if pi/2 - abs(theta - pi/2) < DTHETA:
                        # remove line with least responsibility
                        del_k = k if N_k[kk] > N_k[k] else kk
                        L[del_k] = Line.getRandom(points)
        
        """ remove crossing lines """
        for k, l in enumerate(L):
            for kk, line in ([kk, ll] for kk, ll in enumerate(L) if k != kk):
                # if l and line are connected, they can't cross
                if l.isConnectedTo(line):
                    continue
                X = l.getIntersectionWith(line)
                # if X lies on line and l, this is an intersection
                if line.hasPoint(X) and l.hasPoint(X):
                    # remove line with least responsibility
                    del_k = k if N_k[kk] > N_k[k] else kk
                    L[del_k] = Line.getRandom(points)
        
        """ check stop cond """
        if norm(oldgamma - gamma) < .05:
            break
        oldgamma = gamma
    
    """ debug output """
    if debug_output:
        debug_output(L, gamma)
    
    """ calc probablility P[{Lk} | X] ~ P[X | {Lk}] * P[{Lk}] """
    totalLogProb = sum(log(pi_times_prob.sum(1)))
    logProbLk = 0
    anglecounter = 0
    ## add prob of theta ~ N(pi/2, sigma_theta)
    sigma_theta = .01 * pi/2
    for k, l in enumerate(L):
        lines = l.getAllConnectedLinesFrom(L[k+1:])
        for line in lines:
            theta = l.getAngleWith(line)
            dtheta = abs(theta - pi/2)
            logProbLk += - dtheta**2 / (2*sigma_theta**2) - log(sqrt(2*pi)*sigma_theta)
            anglecounter += 1
    logProbLk /= anglecounter if anglecounter else 1
    ## in case of crossing: Prob = 0
    for k, l in enumerate(L):
        for line in (ll for kk, ll in enumerate(L) if k != kk):
            X = l.getIntersectionWith(line)
            # if l and line are connected, no extra prob is needed
            if l.isConnectedTo(line):
                continue
            # if X lies on line and l, this is an intersection
            if line.hasPoint(X) and l.hasPoint(X):
                logProbLk += float('-inf')
                break
    ## add prob for unattached but near line (extension has to cross)
    ##         ~ N(THRESHOLD_E/d | 0, sigma_unatt) * N(theta | pi/2, sigma_theta)
    sigma_unatt = 0.05
    for k, l in enumerate(L):
        for line in (ll for kk, ll in enumerate(L) if k != kk):
            # if l and line are connected, no extra prob is needed
            if l.isConnectedTo(line):
                continue
            for E in line.E():
                # if E is near l, add probabilities as described above
                d = l.diff(E) + .001 # d should never be zero
                if d < THRESHOLD_E:
                    logProbLk += - (THRESHOLD_E / d)**2 / (2 * sigma_unatt**2)
                    theta = l.getAngleWith(line)
                    logProbLk += - (theta - pi/2)**2 / (2*sigma_theta**2)
                    break
    
    logProbLkX = totalLogProb + logProbLk
    
    return L, logProbLkX
示例#50
0
 def length(self):
     result = 0
     for i in range(0, len(self.points) - 1):
         line = Line(self.points[i], self.points[i+1])
         result = result + line.length()
     return result
示例#51
0
    def __init__(self,
                 lines,
                 halfLines,
                 rect,
                 dotSpread,
                 startPoint=Point(0, 0)):
        self.rect = rect

        self.halfsies = False
        self.overlap = [0, 0]

        anchorPoint = Point(self.rect.topleft)
        self.startPoint = startPoint
        self.lines = []
        self.halfLines = []
        self.dotSpread = dotSpread

        #* Now loop through and get the relative points of all the lines to the anchor point
        #* There is no concept of dotSpread here; they are related to each other via how many boxes seperate them
        # self.lines     = scaleLines(lines,     Point(0, 0), self.dotSpread, 1)
        # self.halfLines = scaleLines(halfLines, Point(0, 0), self.dotSpread, 1)

        # self.lines = lines

        # for line in self.lines:
        #     for point in [line.start, line.end]:
        #         scaleX = True
        #         scaleY = True

        #         if point.x == 0:
        #             scaleX = False
        #         if point.y == 0:
        #             scaleY = False

        #         # returnPoint = Point(point)

        #         # if scaleX:
        #         #     point.x -= ((originPoint.x - returnPoint.x) / startDotSpread) * (newDotSpread - startDotSpread)
        #         # if scaleY:
        #         #     point.y -= ((originPoint.y - returnPoint.y) / startDotSpread) * (newDotSpread - startDotSpread)

        #         if scaleX:
        #             point.x -= (point.x / dotSpread)
        #         if scaleY:
        #             point.y -= (point.y / dotSpread)

        # + startPoint - anchorPoint
        # + startPoint - anchorPoint
        # + startPoint - anchorPoint
        # + startPoint - anchorPoint

        for line in lines:
            self.lines.append(
                Line((line.start - anchorPoint) / dotSpread,
                     (line.end - anchorPoint) / dotSpread, line.color))

        for line in halfLines:
            self.lines.append(
                Line((line.start - anchorPoint) / dotSpread,
                     (line.end - anchorPoint) / dotSpread, line.color))

        # for i in self.lines:
        #     print(i)

        self.size = (Point(self.rect.bottomright) + startPoint -
                     anchorPoint) / self.dotSpread
# Global variables (just to make the moviepy video annotation work)
# with open('calibrate_camera.p', 'rb') as f:
# 	save_dict = pickle.load(f)
# mtx = save_dict['mtx']
# dist = save_dict['dist']

mtx = np.array([[1.15687796e+03, 0.00000000e+00, 6.70608746e+02],
       [0.00000000e+00, 1.15353388e+03, 3.88894697e+02],
       [0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])

dist = np.array([[-2.45563526e-01,  2.56430985e-03, -5.88014374e-04,
        -1.34979788e-04, -6.85209263e-02]])


window_size = 5  # how many frames for line smoothing
left_line = Line(n=window_size)
right_line = Line(n=window_size)
detected = False  # did the fast line fit detect the lines?
left_curve, right_curve = 0., 0.  # radius of curvature for left and right lanes
left_lane_inds, right_lane_inds = None, None  # for calculating curvature


# MoviePy video annotation will call this function
def annotate_image(img_in):
	"""
	Annotate the input image with lane line markings
	Returns annotated image
	"""
	global mtx, dist, left_line, right_line, detected
	global left_curve, right_curve, left_lane_inds, right_lane_inds
示例#53
0
class Detect:
    def __init__(self, img):
        self.image = img
        self.HEIGHT = img.shape[0]
        self.WIDTH = img.shape[1]
        self.cte = 0
        self.center_line = Line(self.WIDTH/2,self.HEIGHT,self.WIDTH/2,self.HEIGHT/2)
        self.angle_steer = 0
        self.speed = 10
        self.dt = 0.1
        self.yaw = 90   #  phi(center,ox)

        ##initialize MPC
        x_start = 140
        y_start = 240
        yaw = -1.4489
        v = 10

        #region of interest
        self.vertices = np.array([[(int(0*img.shape[1]),img.shape[0]),(int(0*img.shape[1]), 
                    int(0.15*img.shape[0])), (int(1.00*img.shape[1]), int(0.15*img.shape[0])), (
                    img.shape[1],img.shape[0])]], dtype=np.int32)
        #img = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
        self.final_img, self.left_line, self.right_line = LD.color_frame_pipeline([self.image], solid_lines=True)
        self.speed_pub = rospy.Publisher("Team1_speed", Float32, queue_size = 10)
        self.steer_pub = rospy.Publisher("Team1_steerAngle", Float32, queue_size = 10)
        # start_time = time()
        #self.sign_image, self.DIRECTION = TD.detect_sign(img)
        # end_time = time()
        # duration = end_time-start_time
        # print(duration,"duration")
        rate = rospy.Rate(30)
        # self.DIRECTION = 'straight' # 0 : straight, 1 rigth, -1 left
    def find_all(self):
        x_axis, y_axis = self.right_line.seperate_axis()
        pol_right = np.polyfit(x_axis,y_axis,1)
        rm  = pol_right[0]
        rb  = pol_right[1]
        x_axis, y_axis = self.left_line.seperate_axis()
        pol_left = np.polyfit(x_axis,y_axis,1)
        lm  = pol_left[0]
        lb  = pol_left[1]
        yb = self.HEIGHT
        yt = yb/3.5
        xt_r = (yt - rb) / rm;
        xb_r = (yb - rb) / rm;
        xt_l = (yt - lb) / lm;
        xb_l = (yb - lb) / lm;
        xb_center = (xb_r + xb_l)/2
        xt_center = (xt_r + xt_l)/2
        self.center_line = Line(xb_center,yb,xt_center,yt)
        self.left_line = Line(xb_l,yb,xt_l,yt)
        self.right_line = Line(xb_r,yb,xt_r,yt)

        self.yaw = np.arctan(self.center_line.compute_slope())
        self.center_line.draw(self.final_img,(255,0,0))
        self.left_line.draw(self.final_img,(0,255,0))
        self.right_line.draw(self.final_img,(0,255,0))
        self.cte = self.center_line.x2 - self.center_line.x1
        
        
    def drive(self):
        return
示例#54
0
文件: man.py 项目: super3/ClassDev
# ˆ
# The left leg is a line with start and end points of (180,110) and
# (200,50).
img.blit( Line(180,110,200,50) )

# ˆThe right foot is an ellipse with center point of (120,50), major axis
# is 20, and minor axis is 5.
img.blit( Ellipse(120,50,20,5).fill( Color(0, 255, 0) ) )

# ˆThe left foot is also an ellipse with center point of (200,50), major
# axis is 20, and minor axis is 5.
img.blit( Ellipse(200,50,20,5).fill( Color(0, 255, 0) ) )

# The flag is constructed as such:
# ˆThe pole is a line with start and end points of (100,125) and (100,50).
line1 = Line(100, 125, 100, 50)

# ˆThe flag is a polygon with vertex points of (100,125), (100,95), and
# (60,110)
polygon1 = Polygon([(100,125), (100,95), (60,110)]).fill( Color(128, 0, 128) )

# ˆThe pole and flag are translated by (0,35), in order to fit in the right
# hand of the stick figure.
line1.translate(0,35)
polygon1.translate(0,35)

# ˆThe pole and flag are rotated by 45 degrees for a fix point of (100,100),
# so the flag and pole are tilted in the right hand of the stick figure.
line1.rotate(100,100,45)
polygon1.rotate(100,100,45)
import math
from Line import Line

N = 100
lr = 0.01

l = Line()


def scalar(V):
  return math.sqrt(V[0]**2+V[1]**2)

def Eout(W, n):
  samples = l.generate_sample(n)
  count = 0.0
  for sample in samples:
    pred = 1 if (W[0]*1 + W[1]*sample[0]) > 0 else -1
    if pred is not sample[1]:
      count += 1
  return count

def learn():
  samples = l.generate_sample(N)

  W = [0, 0]
  w = [99, 99]
  error = [0, 0]
  c = 0
  while(scalar([W[0]-w[0], W[1]-w[1]]) > 0.01):
    c += 1
    for sample in samples:
示例#56
0
class MerryGoRound:
    def __init__(self, capacity):
        self.ticketCost = 8
        self.capacity = capacity
        self.totalRuntime = 240
        self.numberOfOperators = 1
        self.line = Line()
        self.currentRuntime = 0
        self.setupTime = 0
        self.running = False
        self.numberOfPeopleGettingOnRide = 0
        self.mgr = []
        self.totalTicketsReceived = 0
        self.postRide = False
        self.postRideTime = 30

    def StartSetup(self):
        if self.line.GetNumberOfPeople() >= self.capacity:
            self.numberOfPeopleGettingOnRide = self.capacity
            self.setupTime = 120
        else:
            self.numberOfPeopleGettingOnRide = self.line.GetNumberOfPeople()
            self.setupTime = 120
        self.running = True

    def CheckIfReady(self):
        self.setupTime -= 1
        if self.setupTime == 0:
            self.mgr = []
            for i in range(0, self.numberOfPeopleGettingOnRide):
                person = self.line.GetPerson()
                self.line.DecrementLineCount()
                person.UseTickets(8)
                self.totalTicketsReceived += 8
                self.mgr.append(person)
            return True
        else:
            return False

    def CheckIfDone(self):
        self.currentRuntime += 1
        if self.currentRuntime == self.totalRuntime:
            self.running = False
            self.currentRuntime = 0
            self.postRide = True
            return True
        else:
            return False

    def UpdatePostRiders(self):  #riders gather their stuff. 30 seconds
        self.postRideTime -= 1
        if self.postRideTime == 0:
            self.postRideTime = 30
            self.postRide = False
            return True
        else:
            return False

    def GetCurrentWaitTime(self):
        numberOfRides = 0
        if int(self.line.GetNumberOfPeople() /
               self.capacity) == self.line.GetNumberOfPeople() / self.capacity:
            numberOfRides = int(self.line.GetNumberOfPeople() / self.capacity)
        else:
            numberOfRides = int(
                self.line.GetNumberOfPeople() / self.capacity) + 1
        merryGoRoundWaitTime = (numberOfRides * 360)
        if self.running:
            merryGoRoundWaitTime += (240 - self.currentRuntime)
        else:
            merryGoRoundWaitTime += 240 + self.setupTime
        return merryGoRoundWaitTime
示例#57
0
	def readChartFile(self, file_handle):
		'''
		Here we do the heavy lifting of parsing the chart file. Should only be
		called from the constructor, and takes a file handle as argument.
		'''
		# Read the file into memory.
		all_lines = file_handle.readlines()
		# Now create an itteratible array so we know which line we're on.
		line_numbers = range(len(all_lines))
		# Create a line.
		current_line = Line()
		# Variable for tracking data lines.
		data_line = 0
		# Now read the lines.
		for i in line_numbers:
			# Ignore comments.
			if all_lines[i].startswith('#'):
				continue
			# Ignore blank lines.
			elif all_lines[i].isspace():
				continue
			# When we find ! set that line in the pages array.
			elif all_lines[i].startswith('!'):
				self.addPage(data_line)
				continue
			# If we find a Font, set the line font.
			elif all_lines[i].upper().startswith('FONT'):
				line = all_lines[i]
				key, value = line.split('=')
				current_line.setFont(value.strip())
				continue
			# If we find a Linesize spec., set line spacing.
			elif all_lines[i].upper().startswith('LINESIZE'):
				line = all_lines[i]
				key, value = line.split('=')
				current_line.setLineSpacing(value.strip())
				continue
			# If we find a ColumnSize spec., set the column spacing.
			elif all_lines[i].upper().startswith('COLUMNSIZES'):
				line = all_lines[i]
				key, value = line.split('=')
				current_line.setColumnSizes(value)
				continue
			# If we have a data line...
			elif all_lines[i].upper().startswith('20'):
				line = all_lines[i]
				# Increment the number of data lines.
				data_line += 1
				# Set the default character to 0.
				default_chr_pos = 0
				current_line.setDefaultCharacter(default_chr_pos)
				# Check for multiple columns.
				line_sections = line.split('|')
				for each_section in line_sections:
					ratio, text = each_section.split(':')
					ratio = ratio.strip()
					text = text.strip()
					# Check for default character markers.
					for chr in text:
						if chr == '~':
							text = text.replace('~', '', 1)
							# Sanity check for position.
							if default_chr_pos >= len(line):
								default_chr_pos = len(line) - 1
							current_line.setDefaultCharacter(default_chr_pos)
							break
						else:
							default_chr_pos += 1
					# Strip out any quote marks.
					if text.startswith('"') or text.startswith("'"):
						text = text.strip('"\'')
					# Check for blank lines - insert a space in that case.
					if text == '':
						text = ' '
					# Add a section to the current line.
					a_section = Section(ratio, text)
					current_line.addSection(a_section)
				# Done parsing line. Now add it to the chart.
				# Note we do NOT creat a new line, as this would clear the spacing
				# and font and those are only cleared if specified again or a new
				# chart file is loaded. BUT we DO clear the line sections - the
				# text and ratios or else we continue appending and get all sections
				# is all the lines.
				self.addLine(current_line)
				current_line.clearSections()
				continue
			else:
				print "I don't know how to handle this line: \n#%i, %s" %(i, all_lines[i])
				continue
		return True