Exemplo n.º 1
0
def List_points(ob, cam):
	ob.arraie()
	points = np.empty((len(ob.points[0]),3))
	for idx, pos in enumerate(ob.points[0]):
		points[idx] = pos
	X = points[:, 0]
	Y = points[:, 1]
	Z = points[:, 2]
	if len(X) == 0 or len(Y) == 0 or len(Z) == 0:
		return []
	xmin = X[0]
	xmax = X[0]
	ymin = Y[0]
	ymax = Y[0]
	zmin = Z[0]
	zmax = Z[0]
	for x in X:
		if xmin > x:
			xmin = x
		if xmax < x:
			xmax = x
	for y in Y:
		if ymin > y:
			ymin = y
		if ymax < y:
			ymax = y
	for z in Z:
		if zmin > z:
			zmin = z
		if zmax < z:
			zmax = z
	x0, y0, z0 = (xmax-xmin)/2, (ymax-ymin)/2, (zmax-zmin)/2
	X -= x0
	Y -= y0
	Z -= z0
	posx = -X*np.sin(cam.phi) + Y*np.cos(cam.phi)
	posy = X*np.cos(cam.theta)*np.cos(cam.phi) + Y*np.cos(cam.theta)*np.sin(cam.phi) - Z*np.sin(cam.theta)
	posy*=-1
	posx*=-1
	list_points = [0]*len(points)
	
	cam.x = cam.r*np.sin(cam.theta)*np.cos(cam.phi)
	cam.y = cam.r*np.sin(cam.theta)*np.sin(cam.phi)
	cam.z = cam.r*np.cos(cam.theta)
	for index in range(len(points)):
		if cam.light:
			list_points[index] = uts.Point((0,0,255-int(np.sqrt((X[index]-cam.x)**2 + (Y[index]-cam.y)**2 + (Z[index]-cam.z)**2))), x = posx[index]*cam.r + uts.middlehight, y = posy[index]*cam.r + uts.middlewheight, size = cam.r)
		else:
			list_points[index] = uts.Point((0,0,255), x = posx[index]*cam.r + uts.middlehight, y = posy[index]*cam.r + uts.middlewheight, size = cam.r)
	return list_points
Exemplo n.º 2
0
    def scan_row(self, start_point: utils.Point):
        """Finds all adjacent shape points of a point and send them to `ShapeDiscovery.__process_row_point`.

        :param start_point: The start point.
        :type start_point: utils.Point
        """
        # logger.debug('sp: ' + str(start_point))

        self.__previous_point_queued = {-1: False, 1: False}

        self.__process_row_point(start_point)
        cursor_offset_dim = self.__row_mode

        for cursor_offset in [-1, 1]:  # Previous, next points.
            cursor_pos = [start_point.x, start_point.y]

            while True:
                cursor_pos[cursor_offset_dim] += cursor_offset

                # Catches IndexError exception in case of matrix edge encounter.
                try:
                    point = utils.Point(cursor_pos[0], cursor_pos[1])

                    if self.__is_point(self.__pixel_matrix[cursor_pos[0],
                                                           cursor_pos[1]]):
                        self.__process_row_point(point)
                    else:
                        self.__queue_adjacent_point_side_rows(point)

                        break
                except IndexError:
                    break
Exemplo n.º 3
0
    def __queue_adjacent_point_side_rows(self, point: utils.Point):
        """Queues the previous and next row's adjacent point.

        :param point:
        :type point: utils.Point
        """
        cursor_offset_dim = abs(self.__row_mode - 1)

        for cursor_offset in [-1, 1]:
            cursor_pos = [point.x, point.y]
            cursor_pos[cursor_offset_dim] += cursor_offset

            # Checks if the row exists.
            if 0 <= cursor_pos[cursor_offset_dim] < \
                    (self.__pixel_matrix.width if self.__row_mode else self.__pixel_matrix.height):
                if self.__is_point(self.__pixel_matrix[cursor_pos[0],
                                                       cursor_pos[1]]):
                    # Queues it only if the previous on the same line haven't already been queued to prevent row
                    # duplicate.
                    if not self.__previous_point_queued[cursor_offset]:
                        self.__row_scan_queue.append(
                            utils.Point(cursor_pos[0], cursor_pos[1]))
                        self.__previous_point_queued[cursor_offset] = True

                        # logger.debug('qp: ' + str(self.__row_scan_queue[-1]))
                else:
                    self.__previous_point_queued[cursor_offset] = False
Exemplo n.º 4
0
    def derive(self, index, hardened=False):
        # TODO Is index Valid?

        if index < HARDENED_START and hardened:
            index += HARDENED_START

        if hardened:
            raise ValueError(
                "Hardened derivation is not posible on HDPublicKey")
        else:
            key = self.to_public_key().to_bytes()

        signed64 = hmac.new(self.chain, key + to_bytes(self.index, length=4),
                            hashlib.sha512).digest()

        x, y = self.pubkey.pair
        curve = utils.generator_secp256k1
        point = int_from_bytes(signed64[:32]) * curve + utils.Point(
            curve.curve(), x, y, curve.order())
        pubkey = PublicKey((point.x(), point.y()), self.network)

        chain = signed64[32:]
        depth = self.depth + 1

        return HDPublicKey(pubkey, chain, depth, index, self.fingerprint,
                           self.network)
Exemplo n.º 5
0
 def run(self):
     self.__is_alive = True
     for point in [
             utils.Point(i, math.sin(i / 10.0)) for i in xrange(-100, 101)
     ]:
         if not self.__is_alive:
             return
         self.new_point.emit(point)
         self.msleep(100)
Exemplo n.º 6
0
    def __init__(self, **kwargs):

        for k in kwargs.keys():
            if k in [
                    'method', 'gsize', 'gsig', 'window', 'MAXONEFRAME',
                    'REFPING', 'MAXREF', 'captureSize', 'cropRegion',
                    'decisionBoundary', 'color', 'motorsOn'
            ]:
                self.__setattr__(k, kwargs[k])

        self.trackerConnected = False

        ### Timing ###
        self.lastRefTime = time.time()
        self.pauseFrame = 0  #cropping wise
        self.nPauseFrames = 20  #cropping wise

        self.breakDuration = 3  # motor wise
        self.breakStart = time.time()

        ### Worm Finding
        ## points
        self.wormLocation = utils.Point(-1, -1)
        self.wormLocationPrevious = utils.Point(-1, -1)
        self.frameCenter = utils.Point(self.captureSize.ncols / 2,
                                       self.captureSize.nrows / 2)

        ## images
        self.refImg = None
        self.subImg = None
        self.croppedImg = None

        ### Cropping ###
        self.cmin = 0
        self.cmax = self.captureSize.ncols
        self.rmin = 0
        self.rmax = self.captureSize.nrows

        ### Logging ###
        logger.debug('Debug level: %s' % logger.getEffectiveLevel())
        logger.debug('is Debug?: %s' % str(self.isDebug()))

        if self.initializeMotors:
            self.servos = easyEBB()
Exemplo n.º 7
0
 def create_jobs(self, amount):
     padding = 40
     job_cache = []
     while len(self.jobs) < amount:
         rx = random.randint(padding, self.game_area.width - padding)
         ry = random.randint(padding, self.game_area.height - padding)
         if (rx, ry) not in job_cache:
             new_job = Job(utils.Point(rx, ry))
             self.jobs.append(new_job)
             job_cache.append((rx, ry))
Exemplo n.º 8
0
    def drawTest(self, img):
        #BRG
        p = utils.Point(200, 300)
        if self.color:
            self.frameCenter.draw(img, BLUE)
            p.draw(img, RED)

        else:
            self.frameCenter.draw(img, GRAY)
            p.draw(img, GRAY)
Exemplo n.º 9
0
 def _turn_to(self, origin_h, target_h):
     dummy_point = utils.Point(x=-1, y=-1)
     assert self.action_scheduler.runner_thread.isAlive(
     ), "ActionScheduler runner is not alive - check for previous errors"
     name = "Turn_To"
     function = lambda: self.coms.goxy(x_from=dummy_point.x,
                                       y_from=dummy_point.y,
                                       h_from=origin_h,
                                       x_to=dummy_point.x,
                                       y_to=dummy_point.y,
                                       h_to=target_h)
     logger.debug('{} added to ActionScheduler.'.format(name))
     _ = self.action_scheduler.add_action_to_queue(
         Action(name=name, function=function))
Exemplo n.º 10
0
    def fetch(self) -> utils.graphics.Shape:
        """Iterates over the pixel matrix to find a shape's point and processes it to find all the shape's points.

        The next call will process the next found shape. The ShapeDiscovery object can be iterated to execute `fetch(
        )` until all shapes have been found.

        Point processing
        ----------------

        When a point has to be processed, it is added to the scan queue (`ShapeDiscovery.__row_scan_queue()`).
        The queue starts with the first detected point and will be processed by `ShapeDiscovery.scan_row()` until it is
        empty. A row is a set of the horizontally or vertically adjacent shape points of a point (depending of
        `ShapeDiscovery.__row_mode`, see `ShapeDiscovery.__init__() for more info`). See `ShapeDiscovery.scan_row()`
        for more information on the row scan.

        :return A Shape with all the detected Points.
        :rtype utils.graphics.Shape
        """
        # Resets data from previous fetch.
        self.__current_shape = None
        self.__row_scan_queue.clear()

        # Goes on the cursor position of the last fetch.
        while self.__fetch_cursor_y < self.__pixel_matrix.height:
            while self.__fetch_cursor_x < self.__pixel_matrix.width:
                # Checks if pixel is part of a shape.
                if self.__is_point(self.__pixel_matrix[self.__fetch_cursor_x,
                                                       self.__fetch_cursor_y]):
                    start_point = utils.Point(self.__fetch_cursor_x,
                                              self.__fetch_cursor_y)

                    # Initialises shape.
                    self.__current_shape = utils.graphics.Shape(
                        start_point.x, start_point.y)

                    # Queues the shape pixel for row scan.
                    self.__row_scan_queue.append(start_point)

                    # Processes row scan queue.
                    while len(self.__row_scan_queue):
                        start_point = self.__row_scan_queue.popleft()
                        self.scan_row(start_point)

                    return self.__current_shape

                self.__fetch_cursor_x += 1

            self.__fetch_cursor_x = 0
            self.__fetch_cursor_y += 1
Exemplo n.º 11
0
def ecdsa(A, B, p, P, n, m, a):
    k = 5

    # Public key
    H = utils.double_and_add(A, B, p, P, a)

    # K
    K = utils.Point(P.x, P.y, 1)
    K = utils.double_and_add(A, B, p, K, k)
    t = K.x % n
    print('t => {}'.format(t))

    # message Hash
    b = m.encode('utf-8')
    hash = SHA256.new()
    hash.update(b)

    # Signature
    s = ((bytes_to_long(hash.digest()) + (a * t)) * number.inverse(k, n)) % n
    print('s => {}'.format(s))

    return t, s, H, hash
Exemplo n.º 12
0
    def to_relative_point_positioning(self):
        """
        Creates a new Shape object with all it's points' position relative to the shape's position.
        :return The shape in relative point positioning.
        :rtype Shape
        :raise RuntimeError: RuntimeError is raised if the shape is already in relative point positioning.
        """
        if self.relative_point_positioning:
            raise RuntimeError('Shape already in relative point positioning')

        shape = self.__class__(True)

        shape.position_x = self.position_x
        shape.position_y = self.position_y
        shape.width = self.width
        shape.height = self.height

        for point in self:
            relative_point = utils.Point(point.x - self.position_x,
                                         point.y - self.position_y)
            shape.add_point(relative_point)

        return shape
Exemplo n.º 13
0
        max_latt = np.max(latts)

        unix_times = animals.loc[animal]["UnixTime"]

        vertices = list(zip(longs, latts))
        num_coordinates = len(vertices)

        print("\nAnimal : ", animal)
        print("Number coordinates : ", num_coordinates)

        # Compute min distance between 2 position by algorithm has O(nlogn) complexity

        # Build points
        points = []
        for i in range(num_coordinates):
            point = utils.Point(vertices[i][0], vertices[i][1], unix_times[i])
            points.append(point)

        point1, point2 = utils.find_closet_pair(points)
        min_distance = utils.calc_euclidean_distance(point1, point2)

        # ================================

        print("Min distance : ", min_distance)
        print("long1 : {}, latt1 = {}".format(point1.x, point1.y))
        print("long2 : {}, latt2 = {}".format(point2.x, point2.y))
        print("Time1 : ", point1.timestamp)
        print("Time2 : ", point2.timestamp)

        result_map.update({animal: (point1, point2)})
Exemplo n.º 14
0
from Crypto.Hash import SHA256
import math
import random
import utils
from Crypto.Util.number import bytes_to_long

# P256 Elliptic Curve defined in FIPS 186-4
p = 115792089210356248762697446949407573530086143415290314195533631308867097853951
n = 115792089210356248762697446949407573529996955224135760342422259061068512044369
A = -3
B = int('5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b', 16)
Gx = int('6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296',
         16)
Gy = int('4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5',
         16)
G = utils.Point(Gx, Gy, 1)


def test_hasse(n, p):
    print(p)
    borneInf = p + 1 - math.sqrt(p)
    print(borneInf)
    borneSup = p + 1 + math.sqrt(p)
    print(borneSup)
    print(n)
    return borneInf <= n <= borneSup


def ecdh(A, B, p, P):
    a = random.randint(1, n)
    b = random.randint(1, n)
Exemplo n.º 15
0
    def __init__(self, method, src):
        self.color = True
        self.motorsOn = False

        ### Sensitivity of tracker params
        self._sampleFreq = 0.1  #in sec

        ### Set Camera params
        #self.resolution = (640, 480 )
        self.resolution = (1280, 960)
        source = {
            0: 0,
            1: 1,
            2: 'led_move1.avi',
            3: 'screencast.avi',
            4: 'screencast 1.avi',
            5: 'shortNoBox.avi',
            6: 'longNoBox.avi',
            7: 'H299.avi',
            8: 'testRec.avi',
            9: 'longDemo.avi'
        }
        self.captureSource = source[int(src)]

        ### Timing initialization
        self._startTime = time.time()
        self._lastCheck = self._startTime - self._sampleFreq

        ### Display params
        self.mirroredPreview = False

        ### Initialize Objects

        ##### Windows

        self._rawWindow = WindowManager('RawFeed', self.onKeypress)

        ### Capture -- resolution set here
        self._cap = CaptureManager(cv2.VideoCapture(self.captureSource),
                                   self._rawWindow, self.mirroredPreview,
                                   self.resolution)

        actualCols, actualRows = self._cap.getResolution()
        self.centerPt = utils.Point(actualCols / 2, actualRows / 2)

        ## from here on out use this resolution
        boundCols = 600
        boundRows = 600
        ### Arguments for finder
        # --> Pairs are always COLS, ROWS !!!!!!!
        self.finderArgs = {
            'method': method,
            'gsize': 45,
            'gsig': 9,
            'window': 3,
            'MAXONEFRAME': 500,
            'REFPING': 600000,
            'MAXREF': 1000,
            'captureSize': utils.Rect(actualCols, actualRows, self.centerPt),
            'cropRegion': utils.Rect(100, 100, self.centerPt),
            'decisionBoundary': utils.Rect(boundCols, boundRows,
                                           self.centerPt),
            'color': self.color,
            'motorsOn': self.motorsOn
        }

        self._wormFinder = WormFinder(**self.finderArgs)

        ##### Debugging
        #        self._gaussianWindow = WindowManager('Gaussian', self.onKeypress)
        self._overlayWindow = WindowManager('Overlay', self.onKeypress)
Exemplo n.º 16
0
        def get_points(surveytype):
            """
            Return a list of calculated points for the full run.
            :param surveytype:
            :return:
            """
            vlist = []
            vlist.append(utils.Point(X0, Y0, Z0))
            # convert segment list to set of vertice
            for i in range(self.pluginGui.table_segmentList.rowCount()):
                az = str(self.pluginGui.table_segmentList.item(i, 0).text())
                dis = float(
                    str(self.pluginGui.table_segmentList.item(i, 1).text()))
                zen = str(self.pluginGui.table_segmentList.item(i, 2).text())
                direction = str(
                    self.pluginGui.table_segmentList.item(i, 4).text())
                direction = utils.Direction.resolve(direction)

                try:
                    radius = float(
                        self.pluginGui.table_segmentList.item(i, 3).text())
                except ValueError:
                    radius = None

                if (self.pluginGui.radioButton_englishUnits.isChecked()):
                    # adjust for input in feet, not meters
                    dis = float(dis) / 3.281

                #checking degree input
                if (self.pluginGui.radioButton_azimuthAngle.isChecked()):
                    az = float(self.dmsToDd(az))
                    zen = float(self.dmsToDd(zen))
                elif (self.pluginGui.radioButton_bearingAngle.isChecked()):
                    az = float(self.bearingToDd(az))
                    zen = float(self.bearingToDd(zen))

                #correct for magnetic compass headings if necessary
                if (self.pluginGui.radioButton_defaultNorth.isChecked()):
                    self.magDev = 0.0
                elif (self.pluginGui.radioButton_magNorth.isChecked()):
                    self.magDev = float(
                        self.dmsToDd(
                            str(self.pluginGui.lineEdit_magNorth.text())))
                az = float(az) + float(self.magDev)

                #correct for angles outside of 0.0-360.0
                while (az > 360.0):
                    az = az - 360.0
                while (az < 0.0):
                    az = az + 360.0

                # checking survey type
                if surveytype == 'radial':
                    reference_point = vlist[0]  # reference first vertex

                if surveytype == 'polygonal':
                    reference_point = vlist[-1]  #reference previous vertex

                nextpoint = utils.nextvertex(reference_point, dis, az, zen)
                log(nextpoint)
                log(reference_point)

                if radius:
                    # If there is a radius then we are drawing a arc.
                    # Calculate the arc points.
                    points = list(
                        utils.arc_points(reference_point,
                                         nextpoint,
                                         dis,
                                         radius,
                                         point_count=arcpoint_count,
                                         direction=direction))

                    if direction == utils.Direction.ANTICLOCKWISE:
                        points = reversed(points)

                    # Append them to the final points list.
                    vlist.extend(points)

                vlist.append(nextpoint)

            return vlist