示例#1
0
	def test_calibration_transformation_matrix(self):
		test_matrix = numpy.zeros((200, 200))
		corners = {
			'top_left': V(0, 0),
			'top_right': V(199, 0),
			'bottom_left': V(0, 199),
			'bottom_right': V(199, 199)
		}
		trans = calibration.calibration_transformation_matrix(200, 200, corners)
		self.assertEquals(trans[90][90], V(90, 90))
		self.assertEquals(trans[0][0], V(0, 0))
		self.assertEquals(trans[199][199], V(199, 199))

		test_matrix = numpy.zeros((200, 200))
		corners = {
			'top_left': V(100, 0),
			'top_right': V(199, 0),
			'bottom_left': V(100, 199),
			'bottom_right': V(199, 199)
		}
		trans = calibration.calibration_transformation_matrix(200, 200, corners)
		self.assertEquals(trans[100][100], V(0, 100))
		self.assertEquals(trans[1][1], V(-199, 1))
		self.assertEquals(trans[199][199], V(199, 199))
示例#2
0
    def _calibrate(self, white_frame, black_frame):
        """ Fill gui with white, capture a frame, fill with black, capture another frame.
            Substract the images and calculate a threshold, generate a gradient to get the borders.
            Calculate a transformation matrix that converts from the coordinates on the frame to screen coordinates.
        """
        height, width = white_frame.shape
        # Calculate threshold and gradient to end up with an image with just the border of the screen as white pixels
        diff_frame = cv2.subtract(white_frame, black_frame)
        threshold_frame = cv2.threshold(diff_frame, settings.CALIBRATION_THRESHOLD, 255, cv2.THRESH_BINARY)[1]
        gradient_frame = cv2.Laplacian(threshold_frame, cv2.CV_64F)
        gradient_frame = self.threshold(gradient_frame, 255, 256, 255.0)
        cv2.imwrite("white.jpg", white_frame)
        cv2.imwrite("black.jpg", black_frame)
        cv2.imwrite("diff.jpg", diff_frame)
        cv2.imwrite("threshold.jpg", threshold_frame)
        cv2.imwrite("gradient.jpg", gradient_frame)

        self.gui.fill(Color(1, 1, 1))
        self.gui.update()

        # Get list of all white pixels in the gradient as [(y,x), (y,x), ...]
        border_candidate_points = numpy.transpose(gradient_frame.nonzero())
        if not border_candidate_points.any():
            return
        borders = {}
        for border in ['left', 'right', 'top', 'bottom']:
            borders[border] = {
                'count': 0,
                'mean': V(0,0),
                'vectors': []
            }

        for x in range(0, 500):
            raw_y, raw_x = random.choice(border_candidate_points)
            can = V(raw_x, raw_y)
            up = down = left = right = None
            # Walk along a 13x13 square path around the point and look for other border points
            try:
                for x in range(-6, 7):
                    for y in [-6, 7]:
                        if gradient_frame[can.y+y][can.x+x] == 255:
                            if y < 0:
                                down = can + (x,y)
                            else:
                                up = can + (x,y)

                for y in range(-6, 7):
                    for x in [-6, 7]:
                        if gradient_frame[can.y+y][can.x+x] == 255:
                            if x < 0:
                                left = can + (x,y)
                            else:
                                right = can + (x,y)
            except IndexError:
                continue

            # If two opposing sides of the square have border points, and all three points are roughly on a line
            # then assume this is an actual proper point on the screen border
            point_found = False
            if up and down and not left and not right:
                p = up - can
                q = V(down.x - can.x, can.y - down.y)
                point_found = True
            elif left and right and not up and not down:
                p = V(can.x-left.x, left.y-can.y)
                q = V(right.x-can.x, can.y-right.y)
                point_found = True

            if point_found:
                # Test if the three points are roughly on one line
                if p*q/(p.abs()*q.abs()) > 0.95:
                    # For now, we will simply assume that the image is roughly centered,
                    # i.e. that the left edge is on the left half of the screen, etc
                    if up and down:
                        if can.x < width/2:
                            border = 'left'
                        else:
                            border = 'right'
                    else:
                        if can.y < height/2:
                            border = 'top'
                        else:
                            border = 'bottom'
                    borders[border]['count'] += 1
                    borders[border]['mean'] += can
                    borders[border]['vectors'].append(can)

                    # Paint discovered border point on original black frame for debugging
                    black_frame[can.y][can.x] = 255
                else:
                    black_frame[can.y][can.x] = 128

        cv2.imwrite("debug.jpg", black_frame)
        # Go through list of discovered border points and calculate vectors for the borders
        self.gui.draw_image_slow(black_frame)

        for (border_name, border) in borders.items():
            if not border['count']:
                self.gui.update()
                return
            # Divide mean vector by number of vectors to get actual mean for this border
            real_mean = border['real_mean'] = border['mean']/border['count']

            # Calculate mean direction of border
            direction_mean = V(0,0)
            direction_count = 0
            for vector in border['vectors']:
                if not vector:
                    continue
                direction_vector = real_mean - vector
                if (direction_vector+direction_mean).abs() < direction_mean.abs():
                    direction_vector = -direction_vector
                direction_mean += direction_vector
                direction_count += 1
            border['direction_mean'] = direction_mean = direction_mean/direction_count
            added = real_mean + direction_mean
            colors = {
                'left': Color(255, 0, 0),
                'right': Color(0, 255, 0),
                'top': Color(255, 255, 0),
                'bottom': Color(0, 0, 255)
            }
            self.gui.draw_line(real_mean.x, real_mean.y, added.x, added.y, stroke_color = colors[border_name])
            self.gui.draw_circle((real_mean.x, real_mean.y), 5, stroke_color = colors[border_name])

        corners = {}
        # Calculate corners from border intersections
        for border1, border2 in [('top', 'left'), ('top', 'right'), ('bottom', 'left'), ('bottom', 'right')]:
            o1 = borders[border1]['real_mean']
            d1 = borders[border1]['direction_mean']
            o2 = borders[border2]['real_mean']
            d2 = borders[border2]['direction_mean']
            corner = V.intersection(o1, d1, o2, d2)
            if not corner:
                self.gui.update()
                return
            print corner
            corners[border1+"_"+border2] = corner
            self.gui.draw_circle((corner.x, corner.y), 10, Color(255, 0, 255))
        print corners

        # Calculate transformation matrix
        self.gui.calibration_matrix = calibration.calibration_transformation_matrix(width, height, self.gui.width, self.gui.height, corners)
        m = self.gui.calibration_matrix
        b = corners['top_left']
        p = m[b.y+10][b.x+10]
        self.gui.draw_circle((p.x, p.y), 3, stroke_color = Color(0,1,0))
        b = corners['top_right']
        p = m[b.y+10][b.x-10]
        self.gui.draw_circle((p.x, p.y), 3, stroke_color = Color(0,1,0))
        b = corners['bottom_left']
        p = m[b.y-10][b.x+10]
        self.gui.draw_circle((p.x, p.y), 3, stroke_color = Color(0,1,0))
        b = corners['bottom_right']
        p = m[b.y-10][b.x-10]
        self.gui.draw_circle((p.x, p.y), 3, stroke_color = Color(0,1,0))

        self.gui.update()

        print "Calibration successful."