Example #1
0
def init():
    global theMesh,  theLight, theCamera, \
           theScreen,    resolution
    initializeVAO()
    glEnable(GL_CULL_FACE)
    glEnable(GL_DEPTH_TEST)

    # Add our object
    # LIGHT
    theLight = N.array((-0.577, 0.577, 0.577, 0.0),dtype=N.float32)
    # OBJECT
    phongshader = makeShader("phongshader.vert","phongshader.frag")
    verts, elements = readOBJ("suzanne.obj")
    suzanneVerts = getArrayBuffer(verts)
    suzanneElements = getElementBuffer(elements)
    suzanneNum = len(elements)
    theMesh = coloredMesh(N.array((1.0, 0.5, 1.0, 1.0), dtype=N.float32),
                          suzanneVerts,
                          suzanneElements,
                          suzanneNum,
                          phongshader)

    # CAMERA
    width,height = theScreen.get_size()
    aspectRatio = float(width)/float(height)
    near = 0.01
    far = 100.0
    lens = 4.0  # "longer" lenses mean more telephoto
    theCamera = Camera(lens, near, far, aspectRatio)
    theCamera.moveBack(6)
Example #2
0
def init():
    global theMeshes, theLight, theCamera, theScreen, theShader
    initializeVAO()
    glEnable(GL_CULL_FACE)
    glEnable(GL_DEPTH_TEST)
    # Add our objects
    # LIGHT
    theLight = N.array((0.577, 0.577, 0.577, 0.0),dtype=N.float32)
    # SHADER
    theShader = makeShader("flattextured.vert", "flattextured.frag")
    # OBJECT
    width, height, depth = 3,3,100
    magFilter = GL_NEAREST
    theMeshes = [makeObjects(x,magFilter,width,height,depth,
                             useAniso=y)
                 for y in (False, True)
                 for x in (GL_NEAREST,
                           GL_LINEAR,
                           GL_NEAREST_MIPMAP_NEAREST,
                           GL_LINEAR_MIPMAP_NEAREST,
                           GL_NEAREST_MIPMAP_LINEAR,
                           GL_LINEAR_MIPMAP_LINEAR)
    ]

    # CAMERA
    width, height = theScreen.get_size()
    aspectRatio = float(width)/float(height)
    near = 0.01
    far = 100.0
    lens = 4.0  # "longer" lenses mean more telephoto
    theCamera = Camera(lens, near, far, aspectRatio)
    theCamera.moveBack(depth*0.5)
Example #3
0
class Level:
	def __init__(self, fp, engine):
		self.player = None
		self.game_objects = []
		self.updatable_objects = []
		self.platforms = pygame.sprite.OrderedUpdates()
		width, height = [int(i) for i in fp.readline().strip().split()]
		objs = gol.load_level(fp.readline().strip())
		for obj in objs:
			obj.setup(self)
		self.game_objects.extend(objs)
		for line in fp:
			line = line.strip()
			obj = gol.load(line)
			obj.setup(self)
			if obj.is_updatable():
				self.updatable_objects.append(obj)
			self.game_objects.append(obj)
		self.camera = Camera(engine, self)
		self.updatable_objects.append(self.camera)

	def update(self, delta):
		for obj in self.updatable_objects:
			obj.update(delta)

	def draw(self, screen):
		self.camera.draw(screen)
Example #4
0
def init():
    global theMesh, theLight, theCamera, theScreen
    initializeVAO()
    glEnable(GL_CULL_FACE)
    glEnable(GL_DEPTH_TEST)
    # Add our objects
    # LIGHT
    theLight = N.array((0.577, 0.577, 0.577, 0.0),dtype=N.float32)
    # OBJECT
    verts,elements = torus(10.0, 4.0, 128, 32)
    theMesh = proceduralMesh(N.array((1.0,0.5,0.25,1.0),dtype=N.float32),
                             100.0,
                             getArrayBuffer(verts),
                             getElementBuffer(elements),
                             len(elements),
                             makeShader("worley.vert", "worley.frag")
                             )
    # CAMERA
    width, height = theScreen.get_size()
    aspectRatio = float(width)/float(height)
    near = 0.01
    far = 100.0
    lens = 4.0  # "longer" lenses mean more telephoto
    theCamera = Camera(lens, near, far, aspectRatio)
    theCamera.moveBack(50)
Example #5
0
def prob3(filename="StudentEarthData.npz"):
    """Reconstruct single-pixel camera color data in StudentEarthData.npz
    using 450, 650, and 850 measurements. Seed NumPy's random number generator
    with np.random.seed(1337) before each measurement to obtain consistent
    results.

    Return a list containing the Euclidean distance between each
    reconstruction and the color array.
    """
    measures = [250, 400, 550]
    dist = []
    error = []

    earth = np.load(filename)
    faces, vert, C, V = earth['faces'],earth['vertices'], earth['C'], earth['V']
    camera = Camera(faces, vert, C)

    for m in measures:
        camera.add_lots_pic(m)
        A, B = camera.returnData()
        for col in xrange(B.shape[1]):
            b_hat = B[:,col]
            A_hat = np.dot(A, V)
            c = l1Min(A_hat, b_hat)
            c_hat = np.dot(V, c)
            if col == 0:
                c_stack = c_hat
            else:
                c_stack = np.column_stack((c_stack, c_hat))

        visualizeEarth(faces, vert, c_stack.clip(0,1))
        error.append(la.norm(c_stack - C))
    visualizeEarth(faces, vert, C)
    return error
Example #6
0
	def run(self):
		print "server running..."
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.bind(self.addr)
		s.listen(True)

		conn, addr = s.accept()
		print "connect succeed."

		cap = Camera(0, [480, 320], 60)
		ret, frame = cap.cam.read()

		encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]

		while ret:
			result, imgencode = cv2.imencode(".jpg", frame, encode_param)

			data = numpy.array(imgencode)
			string_data = data.tostring()
			conn.send(str(len(string_data)).ljust(16))
			conn.send(string_data)

			ret, frame = cap.cam.read()

			if cv2.waitKey(1) & 0xFF == ord("q"):
				break

		s.close()
		cap.release()
Example #7
0
def main():
	
	screen = pygame.display.set_mode((WIDTH, HEIGHT))
	pygame.display.set_caption("Engine RPG")

	clock = pygame.time.Clock()
	#rejilla = load_image('resources/graphics/rejilla.png', True)
	
	map_loaded = Map("pruebas.tmx")
	heroe = Actor(map_loaded)
	camara = Camera(map_loaded, heroe)
	inp = Input()
	
	while True:
		time = clock.tick(40)
		inp.update()
		salir(inp.get_key_list())
		
		id = heroe.mover(map_loaded, inp)
		heroe.update(id)
		camara.update(screen, map_loaded, heroe)
		camara.show_fps(screen, clock.get_fps())
		#screen.blit(rejilla, (0, 0))
		
		pygame.display.flip()
	return 0
def main():
  nx = 200
  ny = 100
  ns = 100
  print ("P3\n",nx," ",ny,"\n255")

  world = random_scene()

  lookfrom = Vec3(15,2,5)
  lookat = Vec3(0,0,0)
  dist_to_focus = (lookfrom-lookat).length()
  aperture = 0.125
  cam = Camera(lookfrom,lookat,Vec3(0,1,0),20,nx/ny,aperture,dist_to_focus)
  for j in reversed(range(ny)):
    for i in range(nx):
      col = Vec3(0,0,0)
      for s in range(ns):
        u = (i+random())/nx
        v = (j+random())/ny
        r = cam.get_ray(u,v)
        p = r.point_at_parameter(2.0)
        col += color(r,world,0)

      col /= ns
      col = Vec3(sqrt(col[0]),sqrt(col[1]),sqrt(col[2]))
      ir = int(255.99*col[0])
      ig = int(255.99*col[1])
      ib = int(255.99*col[2])
      print (ir," ",ig," ",ib)
Example #9
0
def init():
    global theMesh, theLight, theCamera, theScreen
    initializeVAO()
    glEnable(GL_CULL_FACE)
    glEnable(GL_DEPTH_TEST)
    # Add our objects
    # LIGHT
    theLight = N.array((0.577, 0.577, 0.577, 0.0),dtype=N.float32)
    # OBJECT
    verts, elements = readOBJ("suzanne.obj")
    print verts[0:4]
    arrayBuffer = getArrayBuffer(verts)
    elementBuffer = getElementBuffer(elements)
    numElements = len(elements)
    phongShader = makeShader("phongshader.vert", "phongshader.frag")
    theMesh = coloredMesh(N.array((0,1,1,1),dtype=N.float32),
                          arrayBuffer,
                          elementBuffer,
                          numElements,
                          phongShader
                          )
    # CAMERA
    width, height = theScreen.get_size()
    aspectRatio = float(width)/float(height)
    near = 0.01
    far = 100.0
    lens = 4.0  # "longer" lenses mean more telephoto
    theCamera = Camera(lens, near, far, aspectRatio)
    theCamera.moveBack(3)
Example #10
0
def run():
    WIDTH = 640
    HEIGHT = 480

    running = True
    clock = pygame.time.Clock()
    screen = pygame.display.set_mode( (WIDTH,HEIGHT) )
    w = World()

    c = Camera(screen, (0,0), 3.0, HEIGHT)
    c.set_world(w)

    b = BallEntity((100,100), {'radius': 10, 'density': 10, 'restitution': 0.1,
                               'static': True, 'line-width': 5})
    w.add_entity(b)

    b2 = BallEntity((100,60), {'radius': 20, 'density': 100, 'restitution': 1.0})
    w.add_entity(b2)
    b2.body.SetLinearVelocity((0,40))

    base = BoxEntity((20,20), {'width': 100, 'height': 10})#, 'static': True})
    w.add_entity(base)

    while running:
        screen.fill((255,255,255))
        c.draw()
        pygame.display.flip()

        w.step(dt)
        clock.tick(hz)
Example #11
0
class MainGameState(object):
    def __init__(self):
        self.background = backgrounds.Cave()
        self.world = World()
        self.player = Player(self.world, (-100, 52.4))
        self.camera = Camera((0, 100.0), tracking=self.player)

    def update(self, delta):
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit(0)
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    raise states.StateChange(states.PauseMenuState(self))

        self.world.center = self.player.pos

        self.background.update(delta)
        self.world.update(delta)
        self.player.update(delta)
        self.camera.update(delta)

    def render(self, screen):
        self.background.render(screen, self.camera)
        self.world.render(screen, self.camera)
        self.player.render(screen, self.camera)
def main():
  nx = 200
  ny = 100
  ns = 100
  print("P3\n",nx," ",ny,"\n255")

  l = []
  l.append(Sphere(Vec3(0,0,-1),0.5,Lambertian(Vec3(0.8,0.3,0.3))))
  l.append(Sphere(Vec3(0,-100.5,-1),100,Lambertian(Vec3(0.8,0.8,0.0))))
  l.append(Sphere(Vec3(1,0,-1),0.5,Metal(Vec3(0.8,0.6,0.2),1.0)))
  l.append(Sphere(Vec3(-1,0,-1),0.5,Metal(Vec3(0.8,0.8,0.8),0.3)))

  world = HitableList(l)
  cam = Camera()
  for j in reversed(range(ny)):
    for i in range(nx):
      col = Vec3(0,0,0)
      for s in range(ns):
        u = (i+random())/nx
        v = (j+random())/ny
        r = cam.get_ray(u,v)
        p = r.point_at_parameter(2.0)
        col += color(r,world,0)

      col /= ns
      col = Vec3(sqrt(col[0]),sqrt(col[1]),sqrt(col[2]))
      ir = int(255.99*col[0])
      ig = int(255.99*col[1])
      ib = int(255.99*col[2])
      print(ir," ",ig," ",ib)
Example #13
0
 def load_from_file(uri):
     """Coordinates instantiation of various classes.
     
     Ensures that related Photograph, Camera, CameraView, and Label are all
     instantiated together.
     """
     photo = Photograph(uri)
     photo.read()
     
     Widgets.empty_camera_list.hide()
     
     camera_id, camera_name = Camera.generate_id(photo.camera_info)
     camera = Camera(camera_id)
     camera.add_photo(photo)
     
     CameraView(camera, camera_name)
     Label(photo)
     
     # If the user has selected the lookup method, then the timestamp
     # was probably calculated incorrectly the first time (before the
     # timezone was discovered). So call it again to get the correct value.
     if camera.timezone_method == 'lookup':
         photo.calculate_timestamp(camera.offset)
     
     Widgets.button_sensitivity()
     
     return photo
Example #14
0
    def __init__(self, *args, **kwargs):
        """Takes arguments of serial port number (0-n) and camera
        number on daisy chain (1-9), a daisychain of 0 will send commands to
	all cameras on the port."""
	

        Camera.__init__(self, *args, **kwargs)

        # Some global values for the rs232 commands
        self._header = struct.pack('B',0xFF)
        self._footer = struct.pack('B',0xEF)

        self.sport = serial.Serial(self.port,                      #  port numbering starts at 0
                                   baudrate = 9600,                #
                                   bytesize = serial.EIGHTBITS,    #
                                   parity = serial.PARITY_NONE,    #
                                   stopbits = serial.STOPBITS_ONE, #
                                   timeout = 0.1,                  #
                                   xonxoff = 0,                    #  disablesoftware flow control
                                   rtscts = 1)                     # enable hardware flow control
	
        self.port = self._toParm(self.port,1)
        
	self.daisychain  = self._toParm(int(self.daisychain),1)
        self._dev  = struct.pack('2B',
                                 0x30,
                                 0x30+int(self.daisychain,16))
	
        self.movement_quanta=10
	

	if self.daisychain ==  "1": 
	    # if we're the first camera on the chain:
	    self._startup()  # comment out for speedier testing
Example #15
0
class Scene(object):
    def __init__(self):
        self.camera = Camera()
        self.entities = []

    def render(self):
        """Draw the scene."""
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()

        # Adjust the scene to match current camera settings.
        self.camera.adjust()
        
        # Set up lighting.
        light_diffuse = (1, 1, 1, 1)
        light_position = (0, 5, 0, 1)
        glLightfv(GL_LIGHT0, GL_AMBIENT, light_diffuse)
        glLightfv(GL_LIGHT0, GL_POSITION, light_position)

        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)

        for entity in self.entities:
            entity.render()
        glFlush()

    def add(self, entity):
        """Add a new entity to scene."""
        self.entities.append(entity)
Example #16
0
def video_registration_fixed():

    template = cv2.imread('template.jpg')
    src = template.copy()

    markers, bw = find_markers(template)
    if len(markers) is not 4:
        print 'cannot find 4 markers in template image'
        return

    # open camera
    cam = Camera(0)
    if not cam.is_open():
        return

    cv2.namedWindow('demo', cv2.CV_WINDOW_AUTOSIZE)
    while True:
        dst = cam.read()
        merged = img_registration(src, dst, markers)
        cv2.imshow('demo', merged)
        key = cv2.waitKey(20)
        if key == 27:
            break

    cv2.destroyAllWindows()
Example #17
0
class Level(GameState): 
  def __init__(self,game_ref,delegator_ref):
    super(Level,self).__init__(game_ref,delegator_ref)
    self.camera = Camera()
    self.GAME_STATE = 1 # Refs to GAME_STATES in GameDataIFace
    self.level_to_load = 1
    self.load(1)

  def load(self,level_to_load):
    self.tile_loader = TileLoader(level_to_load) # Returns a reference to a display surface
    self.set_internal_state(1) # Level has finished loading
    self.camera.register_map_surface(self.tile_loader.get_map_surface(),self.tile_loader.get_map_surface_dims())

  def tick(self,game_data_object): 
    self.canvas.fill((0, 255, 0))
    if self.internal_state == 0:
      self.canvas.fill((0, 255, 0))
    elif self.internal_state == 1:
      self.canvas.fill((0, 0, 255))
      self.canvas.blit(self.camera.calc_view(),(0,0))
      print game_data_object
    elif self.internal_state == 2:
      pass
    else:
      raise Exception("Unhandled internal_state")
def startMonitor():
  camera = Camera()
  actionDict = ActionDict(camera)
  config = Config(
    actionDict,
    getButtons().keys(),
    getClickTypes())
  camera.setConfig(config)

  config.checkConfigFile()

  app = QApplication([])
  camera.initCamera()
  keys = QmKeys()
  buttonTimers = dict()
  for b in getButtons().values():
    buttonTimers[b] = ClickTimer(b, config)
  keys.keyEvent.connect(lambda k, s:
    (k in buttonTimers and buttonTimers[k].keyEvent(s)))
  config.dbusButton.setHandler(
    lambda button: dbusBtnClicked(config, button))
  config.dbusButton.connectButtonDbus()
  config.proximityButton.setHandler(
    lambda state: prxBtnClicked(config, state))
  config.proximityButton.connectProximityButton()
  app.exec_()
Example #19
0
def main(arg):
    print BANNER
    model_file_pathname = arg
    image_file_pathname = model_file_pathname + ".ppm"
    model_file = open(model_file_pathname, "r")
    if model_file.next().strip() != MODEL_FORMAT_ID:
        raise "invalid model file"
    for line in model_file:
        if not line.isspace():
            iterations = int(line)
            break
    image = Image(model_file)
    camera = Camera(model_file)
    scene = Scene(model_file, camera.view_position)
    model_file.close()
    last_time = time() - (SAVE_PERIOD + 1)
    try:
        for frame_no in range(1, iterations + 1):
            camera.get_frame(scene, image)
            if SAVE_PERIOD < time() - last_time or frame_no == iterations:
                last_time = time()
                save_image(image_file_pathname, image, frame_no)
            stdout.write("\b" * ((int(log10(frame_no - 1)) if frame_no > 1 else -1) + 12) + "iteration: %u" % frame_no)
            stdout.flush()
        print "\nfinished"
    except KeyboardInterrupt:
        save_image(image_file_pathname, image, frame_no)
        print "\ninterupted"
Example #20
0
def main():
    """Run the ray trace."""

#    nx = 1200
#    ny = 800
    nx = 100
    ny = 100
    ns = 10

    print('P3\n%d %d 255' % (nx, ny))

    world = random_scene()

    lookfrom = Vec3(13, 2, 3)
    lookat = Vec3(0, 0, 0)
    dist_to_focus = 10.0
    aperture = 0.1

    cam = Camera(lookfrom, lookat, Vec3(0,1,0), 20, float(nx)/float(ny), aperture, dist_to_focus)

    for j in range(ny-1, -1, -1):
        for i in range(nx):
            col = Vec3(0, 0, 0)
            for s in range(ns):
                u = float(i + random()) / float(nx)
                v = float(j + random()) / float(ny)
                r = cam.get_ray(u, v)
                p = r.point_at_parameter(2.0)
                col += color(r, world, 0)
            col /= float(ns)
            col = Vec3(sqrt(col.r), sqrt(col.g), sqrt(col.b))
            ir = int(255.99*col.r)
            ig = int(255.99*col.g)
            ib = int(255.99*col.b)
            print('%d %d %d' % (ir, ig, ib))
 def load_from_file(uri):
     """Determine the correct subclass to instantiate.
     
     Also time everything and report how long it took. Raises IOError if
     the file extension is unknown, or no track points were found.
     """
     start_time = clock()
     
     try:
         gpx = globals()[uri[-3:].upper() + 'File'](uri)
     except KeyError:
         raise IOError
     
     Widgets.status_message(_('%d points loaded in %.2fs.') %
         (len(gpx.tracks), clock() - start_time), True)
     
     if len(gpx.tracks) < 2:
         return
     
     TrackFile.instances.add(gpx)
     MapView.emit('realize')
     MapView.set_zoom_level(MapView.get_max_zoom_level())
     MapView.ensure_visible(TrackFile.get_bounding_box(), False)
     
     TrackFile.update_range()
     Camera.set_all_found_timezone(gpx.start.geotimezone)
Example #22
0
class ViewController:
  def __init__(self):
    self.camera = Camera(position=Vector3(0,0,-3))
    #self.camera = Camera(position=Vector3(0,0,0))
    self.meshes = []
    self.bored = False
  
  def reset_camera(self):
    self.camera.target_position.x = DEFAULT_CAMERA_POSITION.x
    self.camera.target_position.y = DEFAULT_CAMERA_POSITION.y
    self.camera.target_position.z = DEFAULT_CAMERA_POSITION.z
    
    self.camera.target_rotation.x = DEFAULT_CAMERA_ROTATION.x
    self.camera.target_rotation.y = DEFAULT_CAMERA_ROTATION.y
    self.camera.target_rotation.z = DEFAULT_CAMERA_ROTATION.z
  
  def rotate_camera_to(self, x, y):
    self.camera.rotate_to(x, y)

  def rotate_camera_by(self, x, y):
    self.camera.rotate_by(x, y)
  
  def zoom_camera_by(self, z):
    self.camera.zoom_by(z)
  
  def zoom_camera_to(self, z):
    self.camera.zoom_to(z)
  
  def step_camera_to_target(self):
    self.camera.step_to_target()
Example #23
0
def video_feed():
    global dataFeed
    if not dataFeed:                                            # we have to create it during the call, otherwise the list that syncs between threads (cients) doesn't get synced correctly between threads (bummer).
        dataFeed = Camera()
    client = CameraClient()
    dataFeed.add_client(client)
    return Response(gen(client),                  # all video streams use the same camera object -> the same input stream.
                    mimetype='multipart/x-mixed-replace; boundary=frame')
Example #24
0
    def __init__(self, name, measureUnit, measureIface, writerUnit = None):
        '''constructor
        '''
        TotalStation.__init__(self, name, measureUnit, measureIface, writerUnit)
        Camera.__init__(self, name, measureUnit, measureIface, writerUnit)
        #StepperMotor.__init__(self, stepperMotorUnit, speed, halfSteps)


        self._affinParams = None
Example #25
0
 def __init__(self, ideal_grid, units_per_cell=10):
     self.gridworld = GridWorld(ideal_grid.width, ideal_grid.height, ideal_grid.gridsize)
     self.gridworld.set_ideal_grid(ideal_grid)
     self.printer = Printer(10, 10, 9, 1, self.gridworld, units_per_cell) #TODO: shouldn't be giving location values here when it's determined somewhere else. that smells a lot
     self.camera = Camera(self.gridworld.grid, self.printer, self.camera_size)
     self.ideal_grid = self.gridworld.ideal_grid
     self.ideal_camera = Camera(self.gridworld.ideal_grid, self.printer, self.camera_size)
     width = self.gridworld.width() * self.gridworld.gridsize()
     height = self.gridworld.height() * self.gridworld.gridsize()
Example #26
0
def main():
   
   #sys.argv=["C:\Users\Adil\Desktop\camera\main.py",'C:\Users\Adil\Desktop\img',"C:\Program Files (x86)\opencv\data\lbpcascades\lbpcascade_frontalface.xml"]
   #sys.argv=["","D:\utilisateurs\tlelepvr\Desktop", "D:\utilisateurs\tlelepvr\Downloads\opencv\sources\data\lbpcascades\lbpcascade_frontalface.xml"]
   sys.argv=["","../../../../test", "../../../../Downloads/opencv/sources/data/lbpcascades/lbpcascade_frontalface.xml"]
   imagePath=sys.argv[1]
   cascadePath=sys.argv[2]
   camera = Camera(imagePath, cascadePath)
   camera._runCaptureLoop()
Example #27
0
class FadeOut(State):
    def __init__(self, window, *args, **kwargs):
        print "++++ new fade state"
        State.__init__(self, window, "fade", *args, **kwargs)
        self.old_state_batch = kwargs["old_state"]
        self.duration = kwargs["duration"]
        self.next_state = kwargs["next_state"]
        self.next_state_args = kwargs["next_state_args"]
        self.build_scene()
        self.alpha = 0.0

    def build_scene(self):
        self.quad = batch.get_batch().add(4, GL_QUADS, GRP_BLEND_ONE_MINUS, ("v3f", fade_quad), ("c4f", fade_color * 4))
        self.camera = Camera((3.8, -18.0, 1.0), (3.8, 0, 1.0))
        self.attaboy = MsgQueue()

    def destroy_scene(self):
        pass

    def on_draw(self):
        set3D(self.window)
        self.window.clear()
        glLoadIdentity()
        self.camera.focus()
        batch.get_batch(self.old_state_batch).draw()
        batch.get_batch().draw()
        set2D(self.window)
        return pyglet.event.EVENT_HANDLED

    def on_key_press(self, k, args):
        if k == key.F11:
            if self.window.fullscreen:
                self.window.set_fullscreen(False)
            else:
                self.window.set_fullscreen(True)
        return pyglet.event.EVENT_HANDLED

    def on_lose_focus(self):
        pyglet.clock.unschedule(self.on_update)
        self.destroy_scene()
        return pyglet.event.EVENT_HANDLED

    def on_gain_focus(self):
        pyglet.clock.schedule_interval(self.on_update, 1.0 / 60.0)
        return pyglet.event.EVENT_HANDLED

    def on_update(self, dt):
        self.attaboy.update(dt)
        if self.alpha > 1:
            self.window.replace_state(self.next_state, **self.next_state_args)
        else:
            color = fade_color
            color[3] = self.alpha
            self.quad.colors = color * 4
            self.alpha += self.duration * dt
        return pyglet.event.EVENT_HANDLED
Example #28
0
 def test_cells_in_view_independent_of_camera_size(self):
     local_camera = Camera(self.grid, self.printer, 4)
     self.printer.position = Vector(30, 30)
     self.assertEqual(local_camera.num_cells_in_view(Vector(1, 1)), 1)
     #two cell
     self.printer.position = Vector(30, 32)
     self.assertEqual(local_camera.num_cells_in_view(Vector(1, 1)), 2)
     #red cell
     self.printer.position = Vector(32, 32)
     self.assertEqual(local_camera.num_cells_in_view(Vector(1, 1)), 4)
Example #29
0
class Camera_Dialog:
    def __init__(self, profile_dialog, resolution, got_photo_cb):
        self.cb = got_photo_cb
        self.dialog = gtk.Dialog('Camera', profile_dialog,
            gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL)
        self.dialog.set_has_separator(False)
        self.image = gtk.DrawingArea()
        self.image.set_size_request(resolution[0], resolution[1])
        self.help_text = gtk.Label('Click to take picture')

        try:
            self.camera = Camera(resolution, self.image)
        except Camera_Exception:
            debug('profile dialog: Unable to initialize camera\n')
            self.camera = None
            self.help_text.set_label('No camera found')

        self.image_hbox = gtk.HBox()
        self.image_hbox.pack_start(gtk.HBox())
        self.image_hbox.pack_start(self.image, False, False)
        self.image_hbox.pack_start(gtk.HBox())
        if self.camera != None:
            self.dialog.vbox.pack_start(self.image_hbox)
        self.dialog.vbox.pack_start(self.help_text, False, True)
        self.close_button = gtk.Button('Close')
        self.dialog.vbox.pack_start(self.close_button, False, True)
        self.close_button.connect('clicked', self.close_clicked)
        self.dialog.connect('response', self.dialog_response)


        self.image.add_events(gtk.gdk.BUTTON_PRESS_MASK)
        self.image.connect('button-press-event', self.image_clicked)
        self.dialog.show_all()

    def close_clicked(self, widget):
        self.close()

    def dialog_response(self, widget, response_id):
        self.close()

    def close(self):
        if self.camera:
            self.camera.stop()
            if self.camera.buffer:
                pixbuf = gtk.gdk.pixbuf_new_from_data(self.camera.buffer,
                    gtk.gdk.COLORSPACE_RGB, False, 8, self.camera.width,
                    self.camera.height, 3*self.camera.width)
                self.cb(pixbuf)
            else:
                self.cb(None)
        self.dialog.destroy()

    def image_clicked(self, widget, data=None):
        if self.camera:
            self.camera.take_photo()
 def test_invalid_isospeed(self):
     cams = self.l.enumerate_cameras()
     c = Camera(self.l, cams[0]['guid'], isospeed=12393)
     c.start()
     c.shot()
     c.stop()
     c.close()
Example #31
0
def main():
    if len(argv) != 2 or argv[1] == '--help':
        print("""Usage: run.py MODEL
Use MODEL to classify camera frames and play sounds when class 0 is recognised.""")
        exit(1)

    model_file = argv[1]

    # We use the same MobileNet as during recording to turn images into features
    print('Loading feature extractor')
    extractor = PiNet()

    # Here we load our trained classifier that turns features into categories
    print('Loading classifier')
    classifier = keras.models.load_model(model_file)

    # Initialize the camera and sound systems
    camera = Camera(training_mode=False)
    random_sound = RandomSound()


    # Create a preview window so we can see if we are in frame or not
    if SHOW_UI:
        pygame.display.init()
        pygame.display.set_caption('Loading')
        screen = pygame.display.set_mode((512, 512))

    # Smooth the predictions to avoid interruptions to audio
    smoothed = np.ones(classifier.output_shape[1:])
    smoothed /= len(smoothed)

    print('Now running!')
    #while True:
    for stream_frame in camera.stream:
        stream_frame.truncate()
        stream_frame.seek(0)
        raw_frame = stream_frame.array
        #raw_frame = camera.next_frame()

        # Use MobileNet to get the features for this frame
        z = extractor.features(raw_frame)

        # With these features we can predict a 'normal' / 'yeah' class (0 or 1)
        # Keras expects an array of inputs and produces an array of outputs
        classes = classifier.predict(np.array([z]))[0]

        # smooth the outputs - this adds latency but reduces interruptions
        smoothed = smoothed * SMOOTH_FACTOR + classes * (1.0 - SMOOTH_FACTOR)
        selected = np.argmax(smoothed) # The selected class is the one with highest probability

        # Show the class probabilities and selected class
        summary = 'Class %d [%s]' % (selected, ' '.join('%02.0f%%' % (99 * p) for p in smoothed))
        stderr.write('\r' + summary)

        # Perform actions for selected class. In this case, play a sound from the sounds/ dir
        if selected == 0:
            random_sound.play_from('sounds/')
        else:
            random_sound.stop()

        # Show the image in a preview window so you can tell if you are in frame
        if SHOW_UI:
            pygame.display.set_caption(summary)
            surface = pygame.surfarray.make_surface(raw_frame)
            screen.blit(pygame.transform.smoothscale(surface, (512, 512)), (0, 0))
            pygame.display.flip()

            for evt in pygame.event.get():
                if evt.type == pygame.QUIT:
                    pygame.quit()
                    break
Example #32
0
    action = msg["action"]

    if action == "move":
        servo_msg = {camera[index].info()[0]: msg["angle"]}
        servo_pub.publish(servo_msg)
    elif action == "start":
        camera[index].start()
    elif action == "pause":
        camera[index].pause()
    elif action == "stop":
        camera[index].stop()
    return


if __name__ == "__main__":
    rospy.init_node("camera")
    rospy.Subscriber("QT", String, camera_callback)
    servo_pub = rospy.Publisher("camera_servo", String, queue_size=5)

    host = "192.168.1.4"
    port1 = 5000
    port2 = 5001
    port3 = 5002

    camera = []
    camera.append(Camera("Main_Cam", 0, host, port1))
    camera.append(Camera("Back_Cam", 1, host, port2))
    camera.append(Camera("Third_Cam", 3, host, port3))

    rospy.spin()
Example #33
0
    return ((diffX**2)+(diffY**2))**(0.5)

#COMPLETE THIS PART
def spawn_cells(numOfCells):
    """add the first line of the for loop
       to run as many times as numOfCells"""
    #The line should go here
        cell = Cell(surface)
        cell_list.append(cell)

def draw_grid():
    for i in range(0,2001,25):
        pygame.draw.line(surface,(230,240,240),(0+camera.x,i*camera.zoom+camera.y),(2001*camera.zoom+camera.x,i*camera.zoom+camera.y),3)
        pygame.draw.line(surface,(230,240,240),(i*camera.zoom+camera.x,0+camera.y),(i*camera.zoom+camera.x,2001*camera.zoom+camera.y),3)

camera = Camera()
blob = Player(surface,"Viliami")
spawn_cells(2000)

def draw_HUD():
    w,h = font.size("Score: "+str(int(blob.mass*2))+" ")
    surface.blit(pygame.transform.scale(t_surface,(w,h)),(8,screen_height-30))
    surface.blit(t_lb_surface,(screen_width-160,15))
    drawText("Score: " + str(int(blob.mass*2)),(10,screen_height-30))
    surface.blit(big_font.render("Leaderboard",0,(255,255,255)),(screen_width-157,20))
    drawText("1. G #1",(screen_width-157,20+25))
    drawText("2. G #2",(screen_width-157,20+25*2))
    drawText("3. ISIS",(screen_width-157,20+25*3))
    drawText("4. ur mom",(screen_width-157,20+25*4))
    drawText("5. w = pro team",(screen_width-157,20+25*5))
    drawText("6. jumbo",(screen_width-157,20+25*6))
Example #34
0
    value_serializer=lambda v: json.dumps(v).encode('utf-8'),
    bootstrap_servers=statusKafka)
statusProducer.send(statusTopic, {
    "status": "starting",
    "client": "imagesfromopencv",
    "language": "python"
})

imagesService = env.get_service(name='raw-images-topic')
if imagesService is None:
    imagesKafka = "localhost:9092"
    imagesTopic = "opencv-kafka-demo-raw-images"
else:
    imagesKafka = imagesService.credentials.get("hostname")
    imagesTopic = imagesService.credentials.get("topicName")

imagesProducer = KafkaProducer(bootstrap_servers=imagesKafka)

# import camera driver
if os.environ.get('CAMERA'):
    Camera = import_module('camera_' + os.environ['CAMERA']).Camera
else:
    from camera import Camera

camerastream = Camera()
while True:
    frame = camerastream.get_frame()
    # print("frame")
    imagesProducer.send(imagesTopic, frame)
    # statusProducer.send(statusTopic, {"status":"image-sent", "client": "imagesfromopencv", "camera": camerastream.__class__.__name__})
Example #35
0
class GLDrawer(object):
    boundary = None
    boundary_grid_size = 30
    sphere_slices = 10

    camera = None
    clip_near = 0.1
    clip_far = 10000

    prev_time = None
    simu_time = None
    fps = 0
    frame_cnt = 0
    cur_frame = None
    stop_flag = False

    win_width = None
    win_height = None

    move_accel = 0.5
    """acceleration"""
    move_velo = 0
    """current velocity"""
    move_accel_dt = 0.1
    """keypress within this time is treated as one long press"""
    prev_move_time = 0
    """previous move keypress time"""
    prev_move_key = None
    """previous moving key code"""

    mouse_left_state = GLUT_UP
    mouse_right_state = GLUT_UP
    mouse_x = 0
    mouse_y = 0
    rotate_factor = 0.00001
    x_rotate_speed = 0
    y_rotate_speed = 0
    wheel_speed = 5
    model_rot_agl_x = 0
    model_rot_agl_y = 0

    _in_fullscreen = False

    def __init__(self, win_title, boundary, win_width=640, win_height=480):
        """:param boundary: list<(min, max) * 3> for x, y, z; or None if no
                boundary"""
        self.boundary = boundary
        self.camera = Camera([10, 10, 180],
                             [sum(boundary[i]) / 2 for i in range(3)],
                             [0, 1, 0])
        self.win_width = win_width
        self.win_height = win_height

        def init_glut():
            glutInit(sys.argv)
            glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH)
            glutInitWindowSize(win_width, win_height)
            glutCreateWindow(win_title)

            glutDisplayFunc(self._gl_drawscene)

            def visible(vis):
                if vis == GLUT_VISIBLE:
                    glutIdleFunc(self._gl_drawscene)
                else:
                    glutIdleFunc(None)

            glutKeyboardFunc(self._on_keyboard)
            glutMouseFunc(self._on_mouse)
            glutMotionFunc(self._on_mouse_motion)
            glutReshapeFunc(self._on_reshape)
            glutVisibilityFunc(visible)
            glutIdleFunc(self._gl_drawscene)

        def init_gl():
            glClearColor(0.0, 0.0, 0.0,
                         0.0)  # This Will Clear The Background Color To Black
            glClearDepth(1.0)  # Enables Clearing Of The Depth Buffer
            glDepthFunc(GL_LESS)  # The Type Of Depth Test To Do
            glEnable(GL_DEPTH_TEST)  # Enables Depth Testing
            glShadeModel(GL_SMOOTH)  # Enables Smooth Color Shading

            glMatrixMode(GL_PROJECTION)
            glLoadIdentity()  # Reset The Projection Matrix
            gluPerspective(45.0,
                           float(win_width) / float(win_height),
                           self.clip_near, self.clip_far)

            glMatrixMode(GL_MODELVIEW)

        def init_light():
            glLightfv(GL_LIGHT0, GL_AMBIENT, GLfloat_4(0.5, 0.5, 0.5, 1.0))
            glLightfv(GL_LIGHT0, GL_DIFFUSE, GLfloat_4(1.0, 1.0, 1.0, 1.0))
            glLightfv(GL_LIGHT0, GL_SPECULAR, GLfloat_4(1.0, 1.0, 1.0, 1.0))
            glLightfv(GL_LIGHT0, GL_POSITION, GLfloat_4(1.0, 1.0, 1.0, 0.0))
            glLightModelfv(GL_LIGHT_MODEL_AMBIENT,
                           GLfloat_4(0.2, 0.2, 0.2, 1.0))
            glEnable(GL_LIGHTING)
            glEnable(GL_LIGHT0)

        init_glut()
        init_gl()
        self._quadric = gluNewQuadric()
        #init_light()

    def start(self):
        self.prev_time = time()

        def mainloop():
            glutMainLoop()

        t = threading.Thread(target=mainloop)
        t.daemon = True
        t.start()

    def _on_keyboard(self, key, x, y):
        if key == 'q':
            self.stop_flag = True
            thread.exit()
        if key == 'f':
            if not self._in_fullscreen:
                self._orig_w = self.win_width
                self._orig_h = self.win_height
                glutFullScreen()
                self._in_fullscreen = True
            else:
                glutReshapeWindow(self._orig_w, self._orig_h)
                self._in_fullscreen = False
        if key in ('w', 's', 'a', 'd'):
            if time() - self.prev_move_time > self.move_accel_dt or \
                    key != self.prev_move_key:
                self.move_velo = 0
            self.prev_move_time = time()
            self.prev_move_key = key
            self.move_velo += self.move_accel
            if key == 'w':
                self.camera.move_forawrd(self.move_velo)
            elif key == 's':
                self.camera.move_forawrd(-self.move_velo)
            elif key == 'a':
                self.camera.move_right(-self.move_velo)
            else:
                self.camera.move_right(self.move_velo)

    def _on_mouse(self, button, state, x, y):
        self.mouse_x = x
        self.mouse_y = y
        if button == GLUT_LEFT_BUTTON:
            self.mouse_left_state = state
        elif button == GLUT_RIGHT_BUTTON:
            self.mouse_right_state = state
        if state == GLUT_UP:
            self.x_rotate_speed = 0
            self.y_rotate_speed = 0
            if button == 3:
                self.camera.move_forawrd(self.wheel_speed)
            elif button == 4:
                self.camera.move_forawrd(-self.wheel_speed)

    def _on_mouse_motion(self, x, y):
        def getv(v):
            s = False
            if v < 0:
                s = True
                v = -v
            r = self.rotate_factor * pow(v, 1.5)
            if s:
                r = -r
            return r
        if self.mouse_left_state == GLUT_DOWN or \
                self.mouse_right_state == GLUT_DOWN:
            x -= self.mouse_x
            y -= self.mouse_y
            self.x_rotate_speed = getv(y)
            self.y_rotate_speed = getv(x)

    def _on_reshape(self, w, h):
        self.win_width = w
        self.win_height = h
        glViewport(0, 0, w, h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0,
                       float(w) / float(h), self.clip_near, self.clip_far)
        glMatrixMode(GL_MODELVIEW)

    def draw_callback(self, frame, time):
        self.cur_frame = frame
        self.simu_time = time
        return not self.stop_flag

    def _gl_drawscene(self):
        frame = self.cur_frame
        if not frame:
            return
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # apply rotate
        if self.mouse_right_state == GLUT_DOWN:
            self.camera.rotate_right(-self.x_rotate_speed)
            self.camera.rotate_up(self.y_rotate_speed)
        self.camera.setGL()
        if self.mouse_left_state == GLUT_DOWN:
            self.model_rot_agl_x += self.x_rotate_speed * 180 / math.pi
            self.model_rot_agl_y += self.y_rotate_speed * 180 / math.pi
        glRotatef(self.model_rot_agl_x, 1, 0, 0)
        glRotatef(self.model_rot_agl_y, 0, 1, 0)
        self._draw_boundary()

        # draw bodies
        self._draw_frame(frame)

        # draw info text
        glColor3f(1, 1, 1)
        self._print_str('fps={0} time={1}'.format(self.fps, self.simu_time))

        # update fps
        cur_time = time()
        if cur_time - self.prev_time > 0.2:
            self.fps = int(self.frame_cnt / (cur_time - self.prev_time))
            self.prev_time = cur_time
            self.frame_cnt = 0
        self.frame_cnt += 1

        glutSwapBuffers()

    def _draw_frame(self, frame):
        for sph in frame.sphlist:
            glPushMatrix()
            glColor3f(*sph.color)
            glTranslatef(sph.pos[0], sph.pos[1], sph.pos[2])
            glutSolidSphere(sph.radius, self.sphere_slices, self.sphere_slices)
            glPopMatrix()

        for cyl in frame.cyllist:
            p1, p2 = cyl.p1, cyl.p2
            vec = p2 - p1
            vlen = float(np.sqrt(np.square(vec).sum()))
            angle = np.arccos(vec[2] / vlen) * 180.0 / np.pi
            if vec[2] < 0:
                angle = -angle
            glPushMatrix()
            glColor3f(*cyl.color)
            glTranslatef(p1[0], p1[1], p1[2])
            glRotatef(angle, -vec[1] * vec[2], vec[0] * vec[2], 0.0)
            gluCylinder(self._quadric, 3.0, 3.0, vlen, 10, 10)
            glPopMatrix()

    def _draw_boundary(self):
        bd = self.boundary
        if not bd:
            return
        o = Vector(*[bd[i][0] for i in range(3)])
        dx = bd[0][1] - bd[0][0]
        dy = bd[1][1] - bd[1][0]
        dz = bd[2][1] - bd[2][0]
        dxv = Vector(dx, 0, 0)
        dyv = Vector(0, dy, 0)
        dzv = Vector(0, 0, dz)

        glBegin(GL_LINES)
        self._draw_lines(o, o + dxv, dyv, (0.7, 0, 0))
        self._draw_lines(o, o + dyv, dxv, (0.7, 0, 0))
        self._draw_lines(o, o + dxv, dzv, (0, 0.7, 0))
        self._draw_lines(o, o + dzv, dxv, (0, 0.7, 0))
        self._draw_lines(o, o + dyv, dzv, (0, 0, 0.7))
        self._draw_lines(o, o + dzv, dyv, (0, 0, 0.7))
        glEnd()

    def _draw_lines(self, p0, p1, dist, color):
        """:param p0 and p1: Vector, initial line
        :param dist: Vector, total dist
        :param n: int, number of lines"""

        glColor3f(*color)
        dv = dist / self.boundary_grid_size
        for i in range(self.boundary_grid_size):
            glVertex3f(p0.x, p0.y, p0.z)
            glVertex3f(p1.x, p1.y, p1.z)
            p0 += dv
            p1 += dv

    def _print_str(self, s):
        glDisable(GL_DEPTH_TEST)
        glMatrixMode(GL_PROJECTION)
        glPushMatrix()
        glLoadIdentity()
        glOrtho(0, self.win_width, self.win_height, 0, -1, 1)
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()
        glRasterPos2f(10, 20)
        for i in s:
            glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(i))

        glPopMatrix()
        glMatrixMode(GL_PROJECTION)
        glPopMatrix()
        glMatrixMode(GL_MODELVIEW)
        glEnable(GL_DEPTH_TEST)
Example #36
0
from PyQt5 import QtGui, QtCore, QtWidgets
import numpy as np
from ctypes import c_float, c_uint, sizeof
import time

from camera import CameraMovement, Camera

GLfloat = c_float
GLuint = c_uint

WIDTH = 800
HEIGHT = 600

# camera
camera = Camera(position=QtGui.QVector3D(0., 0., 3.),
                up=QtGui.QVector3D(0., 1., 0.))

firstMouse = True
lastX = WIDTH / 2.0
lastY = HEIGHT / 2.0

# timing
dateTime = 0.  # time between current frame and last frame
lastFrame = 0.

lightPos = QtGui.QVector3D(1.2, 1., 2.)


class Window(QtGui.QOpenGLWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
Example #37
0
    ns = 100

    lower_left = Vec3(-2, -1, -1)
    horizontal = Vec3(4, 0, 0)
    vertical = Vec3(0, 2, 0)
    origin = Vec3(0, 0, 0)
    world = HitableList()
    world.append(Sphere(Vec3(0, 0, -1), 0.5, Lambertian(Vec3(0.8, 0.3, 0.3))))
    world.append(
        Sphere(Vec3(0, -100.5, -1), 100, Lambertian(Vec3(0.8, 0.8, 0.0))))
    world.append(
        Sphere(Vec3(1, 0, -1), 0.5, Metal(Vec3(0.8, 0.6, 0.2), fuzz=0.3)))
    world.append(
        Sphere(Vec3(-1, 0, -1), 0.5, Metal(Vec3(0.8, 0.8, 0.8), fuzz=1.0)))

    cam = Camera()
    pbar = ProgressBar(
        widgets=['Percentage ',
                 Percentage(), ' ',
                 ETA(), ' ',
                 Bar()],
        maxval=nx * ny).start()

    with open('image.ppm', 'w') as f:
        f.write('P3\n{} {}\n255\n'.format(nx, ny))
        for y, j in enumerate(xrange(ny - 1, -1, -1)):
            for i in xrange(nx):
                col = Vec3(0, 0, 0)
                for _ in xrange(ns):
                    u = float(i + random()) / nx
                    v = float(j + random()) / ny
Example #38
0
                        '--logfile',
                        action='store',
                        help="save stats to file")
    parser.add_argument('-w',
                        '--wristband',
                        action='store_true',
                        help="enable bluetooth wristband")
    args = parser.parse_args()

    if args.wristband:
        wrist = Wristband()
        wrist.start()

    if args.camera:
        neural = Neural(parameters)
        camera = Camera(parameters, neural)
        camera.start()
        print("* Camera loop started")
        _socketHandler = (r"/websocket", SocketHandler, {'camera': camera})

    _statusHandler = (r"/status", StatusHandler, {
        'io': hardware,
        'wristband': wrist
    })

    _staticHandler = (r"/(.*)", tornado.web.StaticFileHandler, {
        'path': os.path.dirname(os.path.realpath(__file__)) + '/web/',
        'default_filename': 'index.html'
    })

    if args.stream and args.camera:
Example #39
0
    Texture_Check(6, Colour(0, 0, 0), Colour(0.5, 0.5, 0.5)))

scene = Scene([
    Sphere(Point3(0.35, 0.6, 0.5), 0.25, SHINY_BLUE),
    #Difference([
    Intersection([  # Cube
        #Plane(Point3(0.2,0.0,0.5), Vector3(0,-1,0), CHECK_FLOOR),
        Plane(Point3(0.1, 0.175, 0.8), Vector3(0.5, 1, 0.1), SHINY_BLUE),
        #Plane(Point3(0.1,0.1,0.5), Vector3(-1,0,0), CHECK_FLOOR),
        #Plane(Point3(0.4,0.1,0.5), Vector3( 1,0,0), CHECK_FLOOR),
        #Plane(Point3(0.5,0.1,0.8), Vector3(0,0, 1), CHECK_FLOOR),
        #Plane(Point3(0.5,0.1,0.5), Vector3(0,0,-1), CHECK_FLOOR),
        Sphere(Point3(0.1, 0.175, 0.8), 0.175, SHINY_BLUE),
    ]),
    #Sphere(Point3(0.1,0.175,0.8), 0.165, SHINY_BLUE)]),
    #Sphere(Point3(0.75,0.15,.2), 0.15, SHINY_RED),
    Plane(Point3(0, 0, 0), Vector3(0, 1, 0), CHECK_FLOOR)
])

scene.lights = [
    #Light(scene, unit(Vector3(2,5,3)), Colour(0.6, 0.6, 0.6)),
    #Light(scene, unit(Vector3(-4,3,0)), Colour(0.7, 0.7, 0.7)),
    PointLight(scene, Point3(.5, 1.1, 1.2), Colour(0.9, 0.9, 0.9)),
]
scene.background = Colour(0, 0, 0)
scene.ambient = Colour(0.4, 0.4, 0.4)

camera = Camera(scene, Point3(0.5, 0.2, 1.6), WIN_SIZE)
camera.lookAt(Point3(0.5, 0.2, 0.3))
#camera.lookAt(Point3(0.1,0.1, 0.9))
Example #40
0
class World(pyglet.window.Window):
    def __init__(self, *args, **kwargs):
        super(World, self).__init__(*args, **kwargs)
        self.scale = 1.0
        self.pos = (0, 0, 0)
        self.fov = 65
        self.render_distance = 100.0
        self.window_x = 1080
        self.window_y = 720
        self.on_resize(self.window_x, self.window_y)

        glClearColor(1.0, 1.0, 1.0, 0.0)
        glEnable(GL_DEPTH_TEST)

        self.file_path = resource_path('textureImages')
        self.textures = self.load_textures()

        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        self.shape = terrainShape.TerrainShape(seed=11,
                                               island_location=(0, 0),
                                               size=15,
                                               height=1)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        self.camera = FpsCamera(self)
        self.draw_number = 0  # the first rendered frame is 1

        pyglet.clock.schedule_interval(self.update, 1 / 60.0)

    def load_textures(self):
        img_dir = self.file_path
        textures = []
        img_paths = os.listdir(img_dir)
        print img_paths
        img_paths.sort()
        for image in img_paths:
            try:
                if not image == '.DS_Store':
                    image = pyglet.image.load(os.path.join(img_dir, image))
                else:
                    continue
            except pyglet.image.codecs.dds.DDSException:
                print '"%s" is not a valid image file' % image
                continue
            textures.append(image.get_texture())

            glEnable(textures[-1].target)
            glBindTexture(textures[-1].target, textures[-1].id)
            glTexImage2D(
                GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0,
                GL_RGBA, GL_UNSIGNED_BYTE,
                image.get_image_data().get_data('RGBA', image.width * 4))
        if len(textures) == 0:
            print 'Found no textures to load. Exiting'
            sys.exit(0)
        return textures

    def update(self, delta_time):

        self.camera.update(delta_time)

    def on_draw(self):

        self.draw_number += 1

        glLoadIdentity()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        self.camera.draw()

        shape = self.shape
        terrain = Terrain(self.textures[0], shape)
        mat = terrain.get_example_mat(20, 20)

        import matTerrian
        matTerrian.draw(texture=terrain.sand_texture, mat=mat)

    def on_resize(self, width, height):
        self.window_x = width
        self.window_y = height
        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(65.0, width / float(height), 0.1, self.render_distance)
        glMatrixMode(GL_MODELVIEW)
Example #41
0

if __name__ == '__main__':

    #classe que cria os alvos
    tempo = time.time()
    alvo = drawObj.Alvo()
    # conta quadros para desenhar novo alvo
    alvoQuadrosCount = 0
    # classe detecta fluxo optico
    fluxo = fluxo.Fluxo()
    # guarda estado atual da aplicacao
    estado = 0
    salvo = 'user.png'
    user1 = cv2.imread(salvo, 0)
    cam = Camera(1)
    faceTracker = roi.Detect()
    recon = FaceRecognition()
    contador = 0
    while True:
        #print 'estdo = ', estado
        # captura frame
        frame = cam.preprocessa()
        # detecta faces
        frame = faceTracker.detectar(**frame)
        #if 'gray' in frame.keys():
        #    cv2.imshow('gray', frame['gray'])
        #if 'roi_face' in frame.keys():
        #    cv2.imshow('roi_face', frame['roi_face'])
        if 'roi_eyes' in frame.keys():
            #cv2.imshow('roi_eyes', frame['roi_eyes'])
Example #42
0
from car import Car
from vision import Vision
from camera import Camera
import cv2
import numpy as np

if __name__ == '__main__':
    #car = Car(18,12)
    vision = Vision(0.1)
    camera = Camera()
    
    #car.reset()

    while True:
        img ,depth = camera.getImages()
        img2 = img.copy()
        if depth is None:
            #car.stop()
            #car.reset()
            break

        ret = vision.processFrame(depth)
        print(ret)
        font = cv2.FONT_HERSHEY_SIMPLEX
        print(img.shape)
        if ret == 1:
            cv2.putText(img2,"BREAK",(90,120),font,1.5,(0,0,255),5)
        elif ret == 3:
            cv2.putText(img2,"STEER LEFT",(30,120),font,1.5,(0,0,255),5)
        elif ret == 2:
            cv2.putText(img2,"STEER RIGHT",(30,120),font,1.5,(0,0,255),5)
Example #43
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.camera = Camera(fps=25)
Example #44
0
def main():
	# Parse command line
	if len(sys.argv) < 2:
		print("python main.py mode <query_image_path> [ <train_video_path> ]")
		return 1

	# Extract features and descriptors from query image
	query_image_path = sys.argv[1]
	print("Query Image Path: {}".format(query_image_path))
	marker = Marker() #class maker
	ret = marker.query_marker(query_image_path) #method from class; query is scan of card
	if ret == -1:
		print("Unable to get query image...terminating...")
		return

	cap = None
	if len(sys.argv) == 3:
		train_image_path = sys.argv[2] #live scene
		print("Using video file...Training Image Path: {}".format(train_image_path))
		cap = cv2.VideoCapture(train_image_path)
	else:
		print("Using web cam")
		cap = cv2.VideoCapture(0)

	# For loading and saving videos
	id_ = 3
	start_frame = 0
	# Get metadata from input movie
	cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
	fps = cap.get(cv2.CAP_PROP_FPS)
	frame_width = int(cap.get(3))
	frame_height = int(cap.get(4))
	fourcc = cv2.VideoWriter_fourcc(*'MJPG')
	# Create video writer
	video_writer = cv2.VideoWriter('videos/output_{}.avi'.format(id_), fourcc, fps,
									(frame_width, frame_height))

	i = 0
	while True:
		ret, frame = cap.read()
		i+=1
		# Display every 5 frames
		if i % 5 == 0:
			continue
		if ret == False:
			break
		if ret == -1:
			print("Unable to get frame...terminating...")
			return
		ret, outlined_frame, matches_image = marker.find_marker(frame) #drawn on webcam frame (blue outline)
		if ret != -1: #if no error
			frame = outlined_frame
			marker.estimate_pose(outlined_frame,Camera()) #get pose from drawn image
			cv2.imshow('Matches',matches_image)

		cv2.imshow('AR Frame',frame)
		key = cv2.waitKey(1)
		print(key)
		if key & 0xFF == ord('q'):
			break
		video_writer.write(frame)

	cv2.destroyAllWindows()
Example #45
0
    def __init__(self):
        # composition stuff

        #: list of (int, child-reference) where int is the z-order, sorted by ascending z (back to front order)
        self.children = []

        #: dictionary that maps children names with children references
        self.children_names = {}

        self._parent = None

        # drawing stuff

        #: x-position of the object relative to its parent's children_anchor_x value.
        #: Default: 0
        self._x = 0

        #: y-position of the object relative to its parent's children_anchor_y value.
        #: Default: 0
        self._y = 0

        #: a float, alters the scale of this node and its children.
        #: Default: 1.0
        self._scale = 1.0

        #: a float, in degrees, alters the rotation of this node and its children.
        #: Default: 0.0
        self._rotation = 0.0

        #: eye, center and up vector for the `Camera`.
        #: gluLookAt() is used with these values.
        #: Default: FOV 60, center of the screen.
        #: IMPORTANT: The camera can perform exactly the same
        #: transformation as ``scale``, ``rotation`` and the
        #: ``x``, ``y`` attributes (with the exception that the
        #: camera can modify also the z-coordinate)
        #: In fact, they all transform the same matrix, so
        #: use either the camera or the other attributes, but not both
        #: since the camera will be overridden by the transformations done
        #: by the other attributes.
        #: You can change the camera manually or by using the `Camera3DAction`
        #: action.
        self.camera = Camera()


        #: offset from (x,0) from where rotation and scale will be applied.
        #: Default: 0
        self.transform_anchor_x = 0

        #: offset from (0,y) from where rotation and scale will be applied.
        #: Default: 0
        self.transform_anchor_y = 0

        #: whether of not the object and his childrens are visible.
        #: Default: True
        self.visible = True

        #: the grid object for the grid actions.
        #: This can be a `Grid3D` or a `TiledGrid3D` object depending
        #: on the action.
        self.grid = None

        # actions stuff
        #: list of `Action` objects that are running
        self.actions = []

        #: list of `Action` objects to be removed
        self.to_remove = []

        #: whether or not the next frame will be skipped
        self.skip_frame = False

        # schedule stuff
        self.scheduled = False          # deprecated, soon to be removed
        self.scheduled_calls = []       #: list of scheduled callbacks
        self.scheduled_interval_calls = []  #: list of scheduled interval callbacks
        self.is_running = False         #: whether of not the object is running

        # matrix stuff
        self.is_transform_dirty = False
        self.transform_matrix = euclid.Matrix3().identity()
        self.is_inverse_transform_dirty = False
        self.inverse_transform_matrix = euclid.Matrix3().identity()
Example #46
0
class CameraTest(unittest.TestCase):
    def setUp(self):
        self.camera = Camera(800, 800, 10, 10)

    def test_apply(self):
        self.assertEqual(self.camera.apply((10, 10)), (10, 10))
        self.assertEqual(self.camera.apply(Vector((10, 10))), Vector(10, 10))
        self.assertEqual(self.camera.apply([Vector((10, 10)), Vector((5, 5))]),
                         [Vector((10, 10)), Vector((5, 5))])

    def test_update(self):
        self.camera.update((50, 50))
        self.assertEqual(self.camera.state.x, -45.0)
        self.camera.update(Vector((100, 100)))
        self.assertEqual(self.camera.state.x, -95.0)

    def test_reverse_apply(self):
        self.assertEqual(self.camera.reverse_apply((10, 10)), (10, 10))
        self.assertEqual(self.camera.reverse_apply(Vector((10, 10))),
                         Vector(10, 10))
        self.assertEqual(self.camera.reverse_apply([Vector((10, 10)),
                                                    Vector((5, 5))]),
                         [Vector((10, 10)), Vector((5, 5))])

    def test_functionality(self):
        self.assertEqual(self.camera.functionality((50, 50)).x, -45.0)
        self.assertEqual(self.camera.functionality((50, 50)).y, -45.0)
Example #47
0
 def get_image(self):
     from camera import Camera
     camera = Camera()
     camera.capture_mobject(self)
     return Image.fromarray(camera.get_image())
Example #48
0
 def setUp(self):
     self.camera = Camera(800, 800, 10, 10)
Example #49
0
    match_cams = set()
    for filename in os.listdir('./match_test_data'):
        if re.match(r'^match_[0-9]\-[0-9].txt$', filename):
            nums = [int(x) for x in re.findall(r'\d+', filename)]
            match_cams.add(nums[0])
            match_cams.add(nums[1])

    imgs = {}
    for filename in sorted(os.listdir('../data/carmel_all')):
        img = cv.imread(os.path.join('../data/carmel_all', filename))
        if img is not None:
            imgs[filename] = img

    cams = [
        Camera(
            Image(imgs['carmel-0' + str(x) + '.png'],
                  'carmel-0' + str(x) + '.png')) for x in match_cams
    ]

    matches = []  # (H, [[[x,y], [x',y']], ...])
    for filename in os.listdir('./match_test_data'):
        if re.match(r'^match_[0-9]\-[0-9].txt$', filename):
            match_nums = [int(x) for x in re.findall(r'\d+', filename)]
            nums = [int(x) for x in re.findall(r'\d+', filename)]
            cam_from_idx = nums[0]
            cam_to_idx = nums[1]

            # Extract match parameters
            contents = open('./match_test_data/' + filename, 'r').read()
            # print(contents.split())
            # words = re.compile("\s*").split(contents)
Example #50
0
    df_solar = pd.read_csv("data/solar.csv", delimiter=";", skiprows=1)
    S = interp1d(df_solar["Wavelength (nm)"],
                 df_solar["Extraterrestrial W*m-2*nm-1"],
                 fill_value="extrapolate")
    # W per meter squared per nanometer
    return S


if __name__ == "__main__":
    M = get_mirror()
    Q = get_detector()
    S = get_solar()

    print(snr(27000))

    CoCa = Camera()

    def integrand(w, alpha=0):
        return w * M(w) * Q(w) * ref_rock(w, alpha).T * S(w)

    phase_angle = np.arange(1, 90, 10)

    snr_vals = []
    snr_vals_80 = []
    signals = []
    signals_80 = []
    centers = range(450, 1000, 50)
    t_exp = 0.005
    t = []
    t_sat = []
    df = pd.read_csv("data/texp.csv")
Example #51
0
def video_feed():
    return Response(gen(Camera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
Example #52
0
class App(object):

    def __init__(self):
        vsync = config.IS_VSYNC
        
        if config.IS_FULLSCREEN:
            self.__window = window.Window( fullscreen=True, vsync=vsync )
        else:
            width,height = config.WIN_SIZE
            self.__window = window.Window( width=width, height=height, fullscreen=False, vsync=vsync )

        self.__winSize = winSize = ( self.__window.width, self.__window.height )

        self.__camera = Camera( winSize )
        self.__hud    = HUD( winSize )

        self.__inputManager = InputManager()
        self.__window.on_key_press   = self.__inputManager.key_pressed
        self.__window.on_key_release = self.__inputManager.key_released

        if config.IS_FPS_LIMIT:
            clock.set_fps_limit( FPS_LIMIT )
        
        glDepthFunc( GL_LEQUAL )
        glEnable( GL_DEPTH_TEST )
        self.__world = GameWorld(self)        # to musi być na końcu

        
    def get_window_coords(self):
        ''' Zwraca współrzędne czworokąta, w którym można rysować. '''
        return self.__camera.windowCoords

    def register_input_observer(self, obj):
        self.__inputManager.register_observer(obj)

    def get_window_dim(self):
        ''' Zwraca wymiary okna (szerokość, wysokość) '''
        return (float(self.__window.width), float(self.__window.height))

    def get_window_draw_dim(self):
        ''' Zwraca współrzędne, w których należy rysować (szerokość, wysokość). '''
        return (1000.0, 750.0)
        # return (800.0, 600.0)    

    def main_loop(self):
        ''' Pętla główna gry. '''

        self.__timeElapsed = 0.0     # czas jaki upłynął od początku gry
        splash = Splash(self, self.__camera, config.SPLASH_DISPLAY_TIME)

        while not self.__window.has_exit:
            self.__window.dispatch_events()

            # update świata i HUDa
            dt = clock.tick() * config.DTIME_MULTIPLY
            self.__timeElapsed += dt

            if config.PRINT_FPS and dt>0.001:
                print "FPS:", 1.0/dt

            # ustaw kamerÄ™
            self.__camera.set3d()

            # narysuj splash screen albo grÄ™
            if self.__timeElapsed < config.SPLASH_DISPLAY_TIME:
                splash.update(dt)
                splash.draw()
            else:
                self.__world.update( dt )
#                 self.__hud.update( dt )

                # narysuj świat
                self.__camera.set3d()
                self.__world.draw()

#                 # narysuj HUD
#                 self.__camera.set2d()
#                 self.__hud.draw()

            self.__window.flip()
Example #53
0
class Hub:
    """ Hub class, provides a central module to hold all the properties that are constantly being accessed """

    def __init__(self):
        """ Initialize default values """
        self.CLOCK = pygame.time.Clock()
        self.WINDOW_WIDTH = 1080
        self.WINDOW_HEIGHT = 720
        self.WINDOW_TITLE = "Legend of Peach"
        self.WINDOW_ICON = pygame.image.load('imgs/WINDOW_ICON.png')
        self.BG_COLOR = (0, 0, 0)
        self.FRAMERATE = 30
        self.speed = 0

        # PHYSICS VALUES
        self.GRAVITY = 10
        self.velocityAI = 5
        self.velocityMushroom = 5
        self.velocityStar = 10

        # DEBUG MODE
        self.modeFreeze = False
        self.modePlace = False

        # Load mario levels from mario level
        self.game_levels = self.get_levels()

        self.gamemode = GameMode(self)
        self.controller = Controller(self)
        self.camera = Camera(self)

        # Screen selector chooses what screen to display
        self.screen_selector = 1
        self.level_name = ''

        # STATES
        self.WALK = 'WALK'
        self.LEFT = 'LEFT'
        self.RIGHT = 'RIGHT'
        self.STOMPED = 'STOMPED'
        self.STAND = 'STAND'
        self.SHELL = 'SHELL'
        self.SLIDE = 'SLIDE'
        self.HIT = 'HIT'
        self.DEATHFALL = 'DEATHFALL'
        self.RISE = "RISE"
        self.FALL = "FALL"
        # Brick States
        self.RESTING = 'RESTING'
        self.BUMPED = 'BUMPED'
        self.OPENED = 'OPENED'

        """ Initialize the type of screen possible to display
        game_screen is the only one that will probably be reinstance everytime a new level
        opens. """
        self.sound_board = SoundBoard()
        self.main_screen = pygame.display.set_mode((self.WINDOW_WIDTH, self.WINDOW_HEIGHT))
        self.hud_screen = HudScreen(self)
        self.main_menu_screen = MainMenuScreen(self)
        self.level_screen = LevelSelectionScreen(self)
        self.game_screen = GameScreen(self)

    def display_screen(self):
        if self.screen_selector is 1:
            self.main_menu_screen.run()
        elif self.screen_selector is 2:
            self.level_screen.run()
        elif self.screen_selector is 3:
            # display gameover screen
            pass
        elif self.screen_selector is 0:
            # runs the game screen
            self.game_screen.run()
            if self.gamemode.mario_is_dead:
                if self.gamemode.lives == 0:
                    # When mario has no more lives
                    self.gamemode.reset_gamemode()
                    self.sound_board.gameover.play()
                    self.screen_selector = 1
                else:
                    self.open_level(self.level_name)
                    self.gamemode.mario_is_dead = False

        self.hud_screen.run()

    @staticmethod
    def exit_game():
        pygame.quit()
        sys.exit()

    @staticmethod
    def get_levels():
        """ Grab the level data from the JSON file"""
        filename = 'levels.json'
        with open(filename, 'r') as read_file:
            data = json.load(read_file)
            return data

    def open_level(self, level_name, world_offset=0):
        """ Opens new gamee_screen and level"""
        print('new game_screen instantiated')
        self.game_screen = GameScreen(self, level_name)
        self.level_name = level_name
        theme = self.game_levels[level_name]["theme"]
        self.camera.reset_camera()
        self.camera.world_offset_x = world_offset

        if theme is "0":
            self.sound_board.play_main_theme_overworld()
        elif theme is "1":
            self.sound_board.play_underworld()
        elif theme is "2":
            self.sound_board.play_castle()
        else:
            self.sound_board.play_main_theme_overworld()
Example #54
0
import cv2
import pickle
import os
import numpy as np

# All this to include camera.py
from os.path import dirname, abspath
import sys
sys.path.insert(0, dirname(dirname(abspath(__file__))))
from camera import Camera

path = "./calibration/chessboard_imgs/"
imgs = os.listdir(path)
cam = Camera(disable_video=True)
for fname in imgs:
    img = cv2.imread(path + fname)
    if img is not None:
        img = cam.undistort(img)
        small = cv2.resize(img, (0, 0), fx=0.6, fy=0.6)
        cv2.imshow(fname, small)
        cv2.waitKey(0)
Example #55
0
    class __impl:
        """This implementation hides the singleton interface\
        in an inner class and creates exactly one instance of\
        the inner class. The outer class is a handle to the inner\
        class and delegates any requests to it. While the id() of\
        the handle objects changes, the id() of the inner class which\
        implements the singleton behaviour is constant."""

        #------------------------------------------------------------------------------#
        #                                                                              #
        #                              Class  Attributes                               #
        #                                                                              #
        #------------------------------------------------------------------------------#

        #reference to our game singletons
        __game = GameController()
        __camera = Camera()
        __hud = HUD()

        #reference to game timers
        timers = {}

        #------------------------------------------------------------------------------#
        #                                  Accessors                                   #
        #------------------------------------------------------------------------------#

        #get the game controller instance
        def getGame(this):
            return this.__game

        #get the camera instance
        def getCamera(this):
            return this.__camera

        #get the hud instance
        def getHud(this):
            return this.__hud

#------------------------------------------------------------------------------#
#                                  Mutators                                    #
#------------------------------------------------------------------------------#

#no mutators in here

#------------------------------------------------------------------------------#
#                                                                              #
#                               Class  Methods                                 #
#                                                                              #
#------------------------------------------------------------------------------#
#------------------------------------------------------------------------------#
#                               Initilization                                  #
#------------------------------------------------------------------------------#

#Initlize our single instance

        def __init__(this):
            #Ninja Game constructor methods
            this.initGame()
            this.runGame()

        #loads any pygame functions or objects before the user gets a chance to act
        def initGame(this):
            #initilize pygame's sound component
            #frequency, size, channels, buffersize
            pygame.mixer.pre_init(44100, 16, 2, 4096)
            #boot up pygame and print boot info
            message = pygame.init()
            print("Successes, Failures\n", message)
            #set the resolution of the game display
            this.getGame().setDisplay(
                pygame.display.set_mode(this.getGame().getResolution()))
            #set the name of the game
            pygame.display.set_caption(this.getGame().getGameName())
            this.getGame().setTimer(this, "quitTimer", 10)
            this.getGame().setTimer(this, "spaceTimer", 5)

#------------------------------------------------------------------------------#
#                              Game Processes                                  #
#------------------------------------------------------------------------------#

        def runGame(this):
            #the game loop to keep the game running
            while this.getGame().getGameRunning():
                #If we are in the menu
                if this.getGame().getAtMainMenu():
                    this.runMainMenu()
                #If we are in the options menu
                elif this.getGame().getAtOptionsMenu():
                    this.runOptionsMenu()
                #If we are in the game...
                elif this.getGame().getAtGame():
                    this.startGameplay()

            #if we manage to break out of the loop without quitting...
            #automatically call the quit method
            this.quitGame()

        #this is where the actual game gets played
        def startGameplay(this):
            pygame.mixer.music.load('sounds/music/level.wav')
            pygame.mixer.music.play(-1)
            #load the map and all of the objects
            this.loadMap()
            this.getHud().initGameHUD()
            #reset the game over flag so this does not repeat
            this.getGame().setGameOver(False)
            this.getGame().setVictory(False)
            this.getGame().setGameOverPlayed(False)

            #------------------ Game Loop Begin -------------------

            #setup the event timer so that the game does not freeze by itself
            #set the event ID to be Uservent + 1 (25)
            timer_event = pygame.USEREVENT + 1
            #set up the timer event to occur every set of miliseconds determined by the second argument
            pygame.time.set_timer(timer_event, 1)

            #while we are considered in the game
            while (this.getGame().getAtGame()):

                #------------ Event Processes ------------
                #check to see if the player has a game over and if has been played yet
                if this.getGame().getGameOver()\
                   and not this.getGame().getGameOverPlayed():
                    #use the game over method if this is the case
                    this.gameOver()

                #checks to see if the player is trying to use input and assigns the action
                #takes the pygame event argument that was created from the for loop
                command = this.processInput()

                #as long as the game isnt over...
                #player selects the new action and the player procces it
                if not this.getGame().getGameOver():
                    this.getGame().getPlayer().recieveCommand(command)
                else:
                    this.getGame().getPlayer().recieveCommand("idle")

                #AI selects the new action and the AI processes it
                this.checkAIStates(this.getGame().getNPCSprites())

                #check to see if all characters are in the middle of an action
                #finishes the action if the chracters are in the middle of one
                this.checkStates(this.getGame().getNPCSprites())
                this.checkStates(this.getGame().getPlayer())

                #add forces (including gravity) to all object lists, then the player
                this.addForces(this.getGame().getTerrainSprites())
                this.addForces(this.getGame().getItemSprites())
                this.addForces(this.getGame().getNPCSprites())
                this.addForces(this.getGame().getPlayer())

                #check to see if any triggers have been activated
                this.checkTriggers()

                #---------- Camera Update ----------------

                #check to see if the camera needs to move
                this.getCamera().checkMove()

                #update the position of all sprites according to how the camera is shifting
                this.getCamera().update(this.getGame().getTerrainSprites())
                this.getCamera().update(this.getGame().getItemSprites())
                this.getCamera().update(this.getGame().getNPCSprites())
                this.getCamera().update(this.getGame().getTriggerSprites())
                this.getCamera().update(this.getHud().getMovingHUDSprites())
                """
                #update the position of all sprite buffers
                this.getCamera().update(this.getGame().terrainSpriteBuffer)
                this.getCamera().update(this.getGame().itemSpriteBuffer)
                this.getCamera().update(this.getGame().NPCSpriteBuffer)
                this.getCamera().update(this.getGame().triggerSpriteBuffer)
                """

                this.getCamera().update(this.getGame().getPlayer())

                #----------- Graphics Rendering -----------

                #run the render graphics method
                this.renderGraphics()

                #----------- Graphics Update Process --------------

                #updates all sprites to their proper positions
                this.getGame().getTerrainSprites().update()
                this.getGame().getItemSprites().update()
                this.getGame().getNPCSprites().update()
                this.getGame().getTriggerSprites().update()
                this.getGame().getPlayer().update()
                this.getHud().getHUDSprites().update()

                #update the display outside of the update loop to reflect any changes
                pygame.display.update()
                """
                buffering methods to be added in at a later date
                #---------- Appearing and Vanishing ----------
                
                #a method that removes all sprites out of view
                this.vanish(this.getGame().getTerrainSprites())
                this.vanish(this.getGame().getItemSprites())
                this.vanish(this.getGame().getNPCSprites())
                this.vanish(this.getGame().getTriggerSprites())
                this.vanish(this.getHud().getMovingHUDSprites())

                this.appear(this.getGame().terrainSpriteBuffer)
                this.appear(this.getGame().itemSpriteBuffer)
                this.appear(this.getGame().NPCSpriteBuffer)
                this.appear(this.getGame().triggerSpriteBuffer)
                """
                #---------- Game Timers ----------------

                this.getGame().countdownTimers(this)

                #---------- Update Process ---------------

                #update frames per second outside fo the update loop and set the delta time to the variable
                this.getGame().deltaTime = (
                    this.getGame().clock.tick(this.getGame().gameFPS) / 4)

                #ensure the pygame event system is still working properly
                pygame.event.pump()

            #-------------------- Game Loop End ------------------------

        def loadMap(this):
            this.loadMapLayer('map1/', 'terrain.txt', "terrain")
            this.loadMapLayer('map1/', 'character.txt', "character")
            this.loadMapLayer('map1/', 'item.txt', "item")
            this.loadMapLayer('map1/', 'triggers.txt', "trigger")

        def loadMapLayer(this, mapPath, filename, objectType):
            path1 = 'maps/'
            filepath = path1 + mapPath + filename
            mapfile = open(filepath, 'r')
            idxX = 0
            idxY = 1

            #loop through the map file to find the dimmensions of the map
            with open(filepath, 'r') as mapfile:
                while True:
                    block = mapfile.read(1)
                    if not block:
                        break
                    elif block == '\n':
                        idxY += 1
                        idxX = 0
                    else:
                        idxX += 1
            mapfile.close()

            #reset the coordinate index values
            idxX = 0
            idxY = 0
            #loop through the map file to turn the character array into an objects array
            with open(filepath, 'r') as mapfile:
                while True:
                    block = mapfile.read(1)
                    if not block:
                        break
                    elif block == '\n':
                        idxY += 1
                        idxX = 0
                    else:
                        this.loadObject(block, objectType, idxX, idxY)
                        idxX += 1
            mapfile.close()

        def loadObject(this, block, objectType, idxX, idxY):
            blockScale = this.getGame().getBlockScale()
            tBuffer = this.getGame().terrainSpriteBuffer
            iBuffer = this.getGame().itemSpriteBuffer
            nBuffer = this.getGame().NPCSpriteBuffer

            if objectType == "terrain":
                #match the character with the object and add it to the map array
                if block == 'b':
                    tBuffer[str(idxX) + "," + str(idxY)] = Brick(
                        (idxX * blockScale), (idxY * blockScale))
                elif block == 'w':
                    tBuffer[str(idxX) + "," + str(idxY)] = Wall(
                        (idxX * blockScale), (idxY * blockScale))
                elif block == 's':
                    tBuffer[str(idxX) + "," + str(idxY)] = Sky(
                        (idxX * blockScale), (idxY * blockScale))
                elif block == 'd':
                    tBuffer[str(idxX) + "," + str(idxY)] = Door(
                        (idxX * blockScale), (idxY * blockScale))
                elif block == 'g':
                    tBuffer[str(idxX) + "," + str(idxY)] = Ground(
                        (idxX * blockScale), (idxY * blockScale))
            #if it is a character type object
            elif objectType == "character":
                #match the character with the object and add it to the map array
                if block == 'r':
                    nBuffer[str(idxX) + "," + str(idxY)] = Gaurd(
                        "Standing Gaurd", (idxX * blockScale),
                        (idxY * blockScale))
                elif block == 'p':
                    Player((idxX * blockScale), (idxY * blockScale))
            #if it is an item type object
            elif objectType == "item":
                pass
            #if it is a trigger type object
            elif objectType == "trigger":
                #match the character with the object and add it to the map array
                if block == 'm':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "howToMoveMessage", (idxX * blockScale),
                        (idxY * blockScale), blockScale, (blockScale * 2))
                elif block == 'a':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "howToAttackMessage", (idxX * blockScale),
                        (idxY * blockScale), blockScale, (blockScale * 2))
                elif block == 'e':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "enemyInfoMessage", (idxX * blockScale),
                        (idxY * blockScale), blockScale, (blockScale * 2))
                elif block == 'r':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "enemyBroadcastMessage", (idxX * blockScale),
                        (idxY * blockScale), blockScale, (blockScale * 2))
                elif block == 'v':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "victory", (idxX * blockScale), (idxY * blockScale),
                        blockScale, (blockScale * 2))
                elif block == 'c':
                    tBuffer[str(idxX) + "," + str(idxY)] = Trigger(
                        "clearMessages", (idxX * blockScale),
                        (idxY * blockScale), blockScale, (blockScale * 2))

        def renderGraphics(this):
            """ The way this works, is that it builds the display
            in layers based on what comes first and the last thing
            that gets drawn is the sprite/shape on the bottom of the
            graphics rendering code block """

            #wipe the slate clean
            this.getGame().getDisplay().fill(this.getGame().getColor("black"))

            #add all sprites to the game display
            this.getGame().getTerrainSprites().draw(
                this.getGame().getDisplay())
            this.getGame().getItemSprites().draw(this.getGame().getDisplay())
            this.customDraw(this.getGame().getNPCSprites())
            this.customDraw(this.getGame().getPlayer())
            this.getHud().getHUDSprites().draw(this.getGame().getDisplay())

        #function for using the custome draw function for a sprite group
        def customDraw(this, sObject):
            #if the object instance is a single sprite
            if isinstance(sObject, pygame.sprite.Sprite):
                #use the custom-made draw function
                sObject.draw(this.getGame().getDisplay())

            #if the object instance is a sprite group
            if isinstance(sObject, pygame.sprite.Group):
                #loop through the sprite group
                for sprite in sObject:
                    #use the custom-made draw function
                    sprite.draw(this.getGame().getDisplay())

        """
        functions to be added in at a later date

        def vanish(this, spriteGroup):
            block = this.getGame().getBlockScale()
            vanishRect = pygame.Rect((0,0),(this.getGame().getResolution()))
            #expand the rect to account for the loading buffer
            vanishRect.inflate_ip(block * this.getGame().loadingBuffer,\
                                block * this.getGame().loadingBuffer)
            
            #loop through the sprite group
            for sprite in spriteGroup:
                #if the sprite is not within the load rect...
                if not vanishRect.contains(sprite.getRect()):
                    #remove the sprite
                    sprite.remove()

        def appear(this, spriteList):
            block = this.getGame().getBlockScale()
            vanishRect = pygame.Rect((0,0),(this.getGame().getResolution()))
            #expand the rect to account for the loading buffer
            loadRect = vanishRect.inflate(block * (this.getGame().loadingBuffer + 2),\
                                block * (this.getGame().loadingBuffer + 2))
            #expand the vanishing buffer
            vanishRect.inflate_ip(block * (this.getGame().loadingBuffer + 2),\
                                block * (this.getGame().loadingBuffer))

            #loop through each sprite in the sprite buffer
            for key, value in spriteList.items():
                #if the sprite is not within the vanish rect
                #but is within the load rect....
                if not vanishRect.contains(value.getRect())\
                   and loadRect.contains(value.getRect()):
                    #ensure the item gets added to the correct list
                    if isinstance(value, Block):
                        this.getGame().getTerrainSprites().add(value)
                    elif isinstance(value, Item):
                        this.getGame().getItemSprites().add(value)
                    elif isinstance(value, NPC):
                        this.getGame().getNPCSprites().add(value)                        
                    elif isinstance(value, Trigger):
                        this.getGame().getTriggerSprites().add(value)
        """

        def processInput(this):
            """Will go back and change jump to a MOD key to try to fix jumping issue"""

            #assign the reference to the game keys list
            keys = this.getGame().keys
            mods = pygame.key.get_mods()

            #keysPressed = this.getGame().noKeysPressed
            keysPressed = pygame.key.get_pressed()

            #reset all the keys that are pressed
            for idx in range(0, len(keys)):
                keys[idx] = False

            #if the keys that are pressed = the boolean tuple
            if keysPressed == this.getGame().wPressed:
                keys[0] = True
            elif keysPressed == this.getGame().sPressed:
                keys[1] = True
            elif keysPressed == this.getGame().aPressed:
                keys[2] = True
            elif keysPressed == this.getGame().dPressed:
                keys[3] = True
            elif keysPressed == this.getGame().upPressed:
                keys[4] = True
            elif keysPressed == this.getGame().downPressed:
                keys[5] = True
            elif keysPressed == this.getGame().leftPressed:
                keys[6] = True
            elif keysPressed == this.getGame().rightPressed:
                keys[7] = True
            elif keysPressed == this.getGame().spacePressed:
                keys[8] = True
            elif keysPressed == this.getGame().escPressed:
                keys[9] = True

            #if the mods are pressed = one number for a specific key
            if mods == this.getGame().rCtrlPressed:
                keys[10] = True

            #print(keysPressed)
            #print(keys)
            #print (mods)

            if keysPressed == this.getGame().noKeysPressed:
                return "idle"
            #return a command based on which keys are pressed
            if keys[8]:
                if this.getGame().checkTimer(this, "spaceTimer"):
                    #ensure we dont press the button twice
                    this.getGame().setTimer(this, "spaceTimer", 5)
                    return "jump"
            elif keys[9]:
                if this.getGame().checkTimer(this, "quitTimer"):
                    if not this.getGame().getAtMainMenu():
                        this.quitLevel()
                        #ensure we dont press the button twice
                        this.getGame().setTimer(this, "quitTimer", 10)
                    else:
                        return this.quitGame()
            elif keys[10]:
                return "attack"
            elif keys[0] or keys[4]:
                return "goUp"
            elif keys[1] or keys[5]:
                return "goDown"
            elif keys[2] or keys[6]:
                return "goLeft"
            elif keys[3] or keys[7]:
                return "goRight"

            #if no actions are being taken or no keys are being pressed... return idle
            return "idle"

        #function for using the check AI state function for a group of sprites
        def checkAIStates(this, sObject):
            #loop through the sprite group
            for sprite in sObject:
                #use the checkState function
                sprite.checkAIState()

        #function for using the check state function for a sprite or group
        def checkStates(this, sObject):
            #if the object instance is a single sprite
            if isinstance(sObject, pygame.sprite.Sprite):
                #use the checkState function
                sObject.checkState()

            #if the object instance is a sprite group
            if isinstance(sObject, pygame.sprite.Group):
                #loop through the sprite group
                for sprite in sObject:
                    #use the checkState function
                    sprite.checkState()

        #add gravity to an object array or just the player
        def addForces(this, sObject):

            #if the object instance is a single sprite
            if isinstance(sObject, pygame.sprite.Sprite):
                #add force to a single object
                this.addSingleForce(sObject)

            #if the object instance is a sprite group
            elif isinstance(sObject, pygame.sprite.Group):
                #loop through the sprite group
                for sprite in sObject:
                    #add force to a single object
                    this.addSingleForce(sprite)

        def addSingleForce(this, sObject):
            #if the object instance is a character or NPC sprite
            if isinstance(sObject, Character)\
               or isinstance(sObject, NPC):
                #have gravity affect the object if they are in the air
                if sObject.mass > 0:
                    sObject.addForce(0, (this.getGame().gravity / 2))

                #implement speed loss over time
                if sObject.getState("isIdle"):
                    if not sObject.speedX == 0:
                        if sObject.speedX > 0:
                            sObject.addForce(-this.getGame().speedLoss, 0)
                        elif sObject.speedX < 0:
                            sObject.addForce(this.getGame().speedLoss, 0)
                        #if there is less than 1 unit of force
                        if abs(sObject.speedX) < 1:
                            #set the speed to 0
                            sObject.speedX = 0

                # if the object is in the middle of moving left or right...
                if sObject.speedX > 0 or sObject.speedX < 0:
                    #move the object and see if they collides with another object
                    if not sObject.move(
                            sObject.speedX * this.getGame().deltaTime, 0):
                        if not sObject.getState("isJumping"):
                            #if they collide, then set the x speed to 0
                            sObject.speedX = 0

                #if the object is in the air
                if sObject.speedY > 0 or sObject.speedY < 0:
                    #move the object and see if he collides with another object
                    if not sObject.move(
                            0, (sObject.speedY * this.getGame().deltaTime)):
                        #if they collides, set the y speed to 0
                        sObject.speedY = 0

            #if the object is not a character sprite
            else:
                #if the object has mass
                if sObject.mass > 0:
                    #make the object fall
                    sObject.move(0, (this.getGame().deltaTime / 2) *
                                 this.getGame().gravity)

        def checkTriggers(this):
            #loop through each trigger
            for trigger in this.getGame().getTriggerSprites():
                #check to see if the trigger is colliding with the player
                if this.getGame().getPlayer().getRect().colliderect(
                        trigger.getRect()):
                    #trigger the event
                    trigger.event()

            #countdown the timers on the triggers
            Trigger.game.countdownTimers(Trigger)

        #a method to run if the player has a game over
        def gameOver(this):
            #if it is not a victorious game over
            if not this.getGame().getVictory():
                pygame.mixer.music.load('sounds/music/gameOver.wav')
                pygame.mixer.music.play(-1)
                #remove any text box elements (if there is any)
                this.getHud().removeTextBox()
                #Create a text box with a message
                this.getHud().createBoxWithMessage(  "*-----------------------------------------------*"\
                                                    +"|     _____                 ____                |"\
                                                    +"|    / ___/__ ___ _  ___   / __ \_  _____ ____  |"\
                                                    +"|   / (_ / _ `/  ` \/ -_) / /_/ / |/ / -_) __/  |"\
                                                    +"|   \___/\_,_/_/_/_/\__/  \____/|___/\__/_/     |"\
                                                    +"|                                               |"\
                                                    +"|                                               |"\
                                                    +"|   Press ESC key to go back to the main menu   |"\
                                                    +"*-----------------------------------------------*",\
                           this.getHud().getTextBoxLocX(), this.getHud().getTextBoxLocY(),\
                           this.getHud().getTextBoxSizeX(), this.getHud().getTextBoxSizeY() + 2,\
                           False)
            #if it is a victorious game over
            elif this.getGame().getVictory():
                pygame.mixer.music.load('sounds/music/victory.wav')
                pygame.mixer.music.play(-1)
                #remove any text box elements (if there is any)
                this.getHud().removeTextBox()
                #Create a text box with a message
                this.getHud().createBoxWithMessage("   _    ___      __                     "\
                                                  +"  | |  / (_)____/ /_____  _______  __   "\
                                                  +"  | | / / / ___/ __/ __ \/ ___/ / / /   "\
                                                  +"  | |/ / / /__/ /_/ /_/ / /  / /_/ /    "\
                                                  +"  |___/_/\___/\__/\____/_/   \__, /     "\
                                                  +"                            /____/      "\
                                                  +"                                        "\
                                                  +"                                        "\
                                                  +"  Press ESC to return to the main menu  ",\
                                                   128,212,43,13, False)
            #reset the game over flag so this does not repeat
            this.getGame().setGameOverPlayed(True)

    #----------------------------- Main Menu Method -------------------------

        def runMainMenu(this):
            pygame.mixer.music.load('sounds/music/title.wav')
            pygame.mixer.music.play(-1)
            #Create a main menu and while bool to store selection
            this.getHud().createBoxWithMessage("*-----------------------------------------------------*"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|               P r e s s     S P A C E               |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|         S  T  A  R  T          G  A  M  E           |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"*-----------------------------------------------------*",\
                                               8,8,58,18, False)
            this.getHud().createBoxWithMessage("*-----------------------------------------------------*"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|            Q  U  I  T          G  A  M  E           |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"|                P r e s s    E S C                   |"\
                                              +"|                                                     |"\
                                              +"|                                                     |"\
                                              +"*-----------------------------------------------------*",\
                                               8,328,58,18, False)
            this.getHud().createBoxWithMessage("        ______   _           __   _     "\
                                              +"       / __/ /  (_)__  ___  / /  (_)    "\
                                              +"      _\ \/ _ \/ / _ \/ _ \/ _ \/ /     "\
                                              +"     /___/_//_/_/_//_/\___/_.__/_/      "\
                                              +"                                        "\
                                              +"     ___                        _       "\
                                              +"    / _ | ___ ___ ___ ____ ___ (_)__    "\
                                              +"   / __ |(_-<(_-</ _ `(_-<(_-</ / _ \   "\
                                              +"  /_/ |_/___/___/\_,_/___/___/_/_//_/   ",\
                                               128,212,43,13, False)
            mainMenu = Menu("Main")
            mainMenu.addMenuItem("Start",
                                 this.getGame().imgBlank, 0, 0, 960, 320)
            #mainMenu.addMenuItem("Start", this.getGame().startImage, 0,0,480,320)
            #mainMenu.addMenuItem("Options", this.getGame().optionsImage, 480,0,480,320)
            mainMenu.addMenuItem("Quit",
                                 this.getGame().imgBlank, 0, 320, 960, 320)

            #------------------ Main Menu Loop Begin -------------------

            #while we are considered in the main menu
            while (this.getGame().getAtMainMenu()):
                #for event in pygame.event.get():

                #------------ Event Processes ------------

                #a method that checks to see if a menu item get pressed
                #and assigns the process name to a process variable
                #process = mainMenu.selectOption(this.getGame().getDisplay(), event)

                process = this.processInput()

                this.runSelectedProcess(process)
                #----------- Graphics Rendering -----------
                """ The way this works, is that it builds the display
                in layers based on what comes first and the last thing
                that gets drawn is the sprite/shape on the bottom of the
                graphics rendering code block """

                #draw the HUD sprites on the screen
                this.getHud().getHUDSprites().update()

                #run the render graphics method
                this.renderGraphics()

                #update the screen
                pygame.display.update()

                #Run the display menu items method
                #mainMenu.displayMenuItems(this.getGame().getDisplay())

                #------------ Game Timers ----------------

                this.getGame().countdownTimers(this)

                #----------- Update Process --------------

                #update the display outside of the event loop to reflect any changes
                pygame.display.update()

                #update frames per second outside fo the update loop and set the delta time to the variable
                this.getGame().deltaTime = (
                    this.getGame().clock.tick(this.getGame().gameFPS) / 4)

                #ensure the pygame event system is still working properly
                pygame.event.pump()

            #-------------------- Main Menu Loop End ------------------------

        def runOptionsMenu(this):
            print("You are in the options menu, nothing here yet...")
            this.runSelectedProcess("Main Menu")

        def runSelectedProcess(this, process):
            if process == "jump":
                print("Starting Start Process...")
                this.getGame().setAtMainMenu(False)
                this.getGame().setAtOptionsMenu(False)
                this.getGame().setAtGame(True)

            elif process == "Main Menu":
                print("Returning to the Main Menu...")
                this.getGame().setAtMainMenu(True)
                this.getGame().setAtOptionsMenu(False)
                this.getGame().setAtGame(False)

            elif process == "Options":
                print("Starting Options Process...")
                this.getGame().setAtMainMenu(False)
                this.getGame().setAtOptionsMenu(True)
                this.getGame().setAtGame(False)

            elif process == "Quit":
                print("Continuing Quit Process...")
                this.getGame().setGameRunning(False)
                this.getGame().setAtMainMenu(False)
                this.getGame().setAtOptionsMenu(False)
                this.getGame().setAtGame(False)
                this.quitGame()

            elif process == "Invalid":
                print(
                    "You have selected an invalid proceess... please try again"
                )

            else:
                pass

        def quitLevel(this):
            #Clear out all sprite groups
            this.getGame().getTerrainSprites().empty()
            this.getGame().getItemSprites().empty()
            this.getGame().getNPCSprites().empty()
            this.getGame().getTriggerSprites().empty()
            this.getHud().getHUDSprites().empty()
            #Remove the player
            this.getGame().getPlayer().kill()
            #reset the camera
            this.getCamera().reset()
            #reset the game over flag
            this.getGame().setGameOver(False)
            #reset the victory flag
            this.getGame().setVictory(False)
            #remove the game over text Box
            this.getHud().removeTextBox()
            #run the main menu process
            this.runSelectedProcess("Main Menu")

        def quitGame(this):
            pygame.quit()
            quit()
Example #56
0
    dict_list = []
    keys = [sheet.cell(0, col_index).value for col_index in range(sheet.ncols)]
    for row_index in range(1, sheet.nrows):
        d = {
            keys[col_index]: sheet.cell(row_index, col_index).value
            for col_index in range(sheet.ncols)
        }
        dict_list.append(d)

    camerasArray = []

    for index in range(len(dict_list)):

        camerasArray.append(
            Camera(ip=dict_list[index]['ip'],
                   port=int(dict_list[index]['port']),
                   login=dict_list[index]['login'],
                   password=dict_list[index]['password']))

    #result = open(config_ini['DEFAULT']['path_to_save_file'], "w", encoding='utf8')

    log = open(config_ini['DEFAULT']['log_file'], 'w')

    for camer in camerasArray:
        print(camer)

        status = changeLogTries(camer.ip, camer.port, camer.login,
                                camer.password,
                                int(config_ini['DEFAULT']['mode']))
        log.write("{}:{}\t{}\n".format(camer.ip, camer.port, status))
Example #57
0
def generate_camera():
    """
    Generates camera
    """
    config.CAMERA = Camera(config.MAP_INFO)
Example #58
0
def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--unit-config', type=str, required=True)
    parser.add_argument('-a', '--app-config', type=str, required=True)
    args = parser.parse_args()

    with open(args.app_config, 'r') as f:
        sim_config = json.load(f)["simulation"]
    with open(args.unit_config, 'r') as f:
        unit_config = json.load(f)

    robots = list()
    robots.append(
        Robot(0,
              pose=np.array([[0], [0], [0]], dtype=np.float64),
              world_size=np.array([
                  sim_config["world"]["length_m"],
                  sim_config["world"]["width_m"]
              ])))
    robots.append(
        Robot(1,
              pose=np.array([[0], [0], [pi / 4]], dtype=np.float64),
              world_size=np.array([
                  sim_config["world"]["length_m"],
                  sim_config["world"]["width_m"]
              ])))
    robots.append(
        Robot(2,
              pose=np.array([[0], [0], [pi / 2]], dtype=np.float64),
              world_size=np.array([
                  sim_config["world"]["length_m"],
                  sim_config["world"]["width_m"]
              ])))
    robots.append(
        Robot(3,
              pose=np.array([[0], [0], [3 * pi / 4]], dtype=np.float64),
              world_size=np.array([
                  sim_config["world"]["length_m"],
                  sim_config["world"]["width_m"]
              ])))
    robots.append(
        Robot(4,
              pose=np.array([[0], [0], [pi]], dtype=np.float64),
              world_size=np.array([
                  sim_config["world"]["length_m"],
                  sim_config["world"]["width_m"]
              ])))
    robots.append(
        Robot(5,
              pose=np.array([[0], [0], [5 * pi / 4]], dtype=np.float64),
              world_size=np.array([
                  sim_config["world"]["length_m"],
                  sim_config["world"]["width_m"]
              ])))
    robots.append(
        Robot(6,
              pose=np.array([[0], [0], [3 * pi / 2]], dtype=np.float64),
              world_size=np.array([
                  sim_config["world"]["length_m"],
                  sim_config["world"]["width_m"]
              ])))
    robots.append(
        Robot(7,
              pose=np.array([[0], [0], [7 * pi / 4]], dtype=np.float64),
              world_size=np.array([
                  sim_config["world"]["length_m"],
                  sim_config["world"]["width_m"]
              ])))
    robots.append(
        Robot(8,
              pose=np.array([[-1], [1], [0]], dtype=np.float64),
              world_size=np.array([
                  sim_config["world"]["length_m"],
                  sim_config["world"]["width_m"]
              ])))
    robots.append(
        Robot(9,
              pose=np.array([[-1], [1], [pi / 4]], dtype=np.float64),
              world_size=np.array([
                  sim_config["world"]["length_m"],
                  sim_config["world"]["width_m"]
              ])))

    for robot in robots:
        # create, initialize, and attach camera to robot
        camera = Camera(intrinsics=unit_config["camera"]["0"]["intrinsics"],
                        extrinsics=unit_config["camera"]["0"]["extrinsics"])
        robot.attach_camera(camera)

    # generate 10 fiducials and place them
    fiducials = []
    '''
    for i in range(0,10):
        fiducial = Fiducial(np.array([[random.randrange(0, world_length),
                                       random.randrange(0, world_width),
                                       random.randrange(0, world_height)]],
                                     dtype=np.float64), i)
        fiducials.append(fiducial)
    '''
    fiducials.append(
        Fiducial(
            np.array([[1, 1, 1, 1], [0, 0.1, 0.1, 0], [1, 1, 0.9, 0.9]],
                     dtype=np.float64), 0))
    fiducials.append(Fiducial(np.array([[1], [1], [1]], dtype=np.float64), 1))
    fiducials.append(Fiducial(np.array([[0], [1], [1]], dtype=np.float64), 2))
    fiducials.append(Fiducial(np.array([[-1], [1], [1]], dtype=np.float64), 3))
    fiducials.append(Fiducial(np.array([[-1], [0], [1]], dtype=np.float64), 4))
    fiducials.append(Fiducial(np.array([[-1], [-1], [1]], dtype=np.float64),
                              5))
    fiducials.append(Fiducial(np.array([[0], [-1], [1]], dtype=np.float64), 6))
    fiducials.append(Fiducial(np.array([[1], [-1], [1]], dtype=np.float64), 7))

    seen = Simulator(robots,
                     fiducials,
                     world_size=np.array([
                         sim_config["world"]["length_m"],
                         sim_config["world"]["width_m"]
                     ])).run()  # run the simulation
Example #59
0
from camera import Camera, CameraModels

import cv2
import numpy as np
import os

from tqdm import tqdm

camera_model = CameraModels.FISHEYE
retval, K, d, rvecs, tvecs, obj_points_temp, img_points_temp, not_used = np.load(
    'calibration_file.npy', allow_pickle=True)

cam = Camera(camera_matrix=K,
             distortion_coefficients=d,
             camera_model=camera_model)

image_size = (640, 480)
image_fov = (150, 120)

show_image = False

path = 'images'

path_in = os.path.join(path, 'in/')
path_out = os.path.join(path, 'out/')

files = os.listdir(path_in)
files = [file for file in files]

#print(f'Searching: {}')
Example #60
0
 def __init__(self):
     self.image = None
     self.motor_step = 0
     self.theta = 0
     self.is_scanning = False
     self.camera = Camera()