def cloudInit(self, cloud): if cloud is None: print("Initialize cloud API") cloud = Cloud(self.conf) cloud.getToken() self.cloud = cloud return cloud
def test_Disk_77_DownloadUpd_offLine(self): self.disk.disconnect() r_path = 'd1/d2/file' path = path_join(self.disk.path, r_path) mt = self.disk.h_data.get(path) with tempFile(delete=False, mode='wt') as f: temp = f.name f.write('file file') Cloud.task(self.disk, 'up', r_path, temp) self.disk.connect() sleep(30) self.assertTrue(self.disk.status == 'idle') self.assertGreater(self.disk.h_data.get(path), mt)
def loadSprites(self): self.all_sprites = pygame.sprite.LayeredUpdates() self.platforms = pygame.sprite.Group() self.finalplatform = pygame.sprite.Group() self.coin = pygame.sprite.Group() self.enemyFly = pygame.sprite.Group() self.clouds = pygame.sprite.Group() self.spikeenemy = pygame.sprite.Group() self.brownmob = pygame.sprite.Group() self.skullmob = pygame.sprite.Group() self.digletmob = pygame.sprite.Group() self.EnemyFlyTimer = 0 from Player import Player self.player = Player(self) self.highscore = HighScores() self.playerDead = False # creates the enemy flys for fly in ENEMYFLY_LIST: EnemyFly(self, *fly) # creates the big grass platform for grassbigplatform in GRASS_BIG_PLATFORM_LIST: GrassBigPlatform(self, *grassbigplatform) # creates the small grass platform for grasssmallplatform in GRASS_SMALL_PLATFORM_LIST: GrassSmallPlatform(self, *grasssmallplatform) # creates the big brown cake platform for bcakebigplatform in BCAKE_BIG_PLATFORM_LIST: BCakeBigPlatform(self, *bcakebigplatform) # creates the small brown cake platform for bcakesmallplatform in BCAKE_SMALL_PLATFORM_LIST: BCakeSmallPlatform(self, *bcakesmallplatform) # creates the big sand platform for sandbigplatform in SAND_BIG_PLATFORM_LIST: SandBigPlatform(self, *sandbigplatform) # creates the small sand platform for sandsmallplatform in SAND_SMALL_PLATFORM_LIST: SandSmallPlatform(self, *sandsmallplatform) # creates the big snow platform for snowbigplatform in SNOW_BIG_PLATFORM_LIST: SnowBigPlatform(self, *snowbigplatform) # creates the small snow platform for snowsmallplatform in SNOW_SMALL_PLATFORM_LIST: SnowSmallPlatform(self, *snowsmallplatform) # creates the big stone platform for stonebigplatform in STONE_BIG_PLATFORM_LIST: StoneBigPlatform(self, *stonebigplatform) # creates the small stone platform for stonesmallplatform in STONE_SMALL_PLATFORM_LIST: StoneSmallPlatform(self, *stonesmallplatform) # final platform here for grassfinalplatform in GRASS_FINAL_PLATFORM_LIST: GrassFinalPlatform(self, *grassfinalplatform) # creates clouds on the map for i in range(8): from Cloud import Cloud cloud = Cloud(self) cloud.rect.y += 500
def __init__(self): # Create the olympe.Drone object from its IP address self.drone = olympe.Drone(DRONE_IP) self.detector = DiseaseDetector.DiseaseDetector() self.cloud = Cloud() self.counter_frames = 0 self.tempd = tempfile.mkdtemp(prefix="olympe_streaming_test_") print("Olympe streaming output dir: {}".format(self.tempd)) self.h264_frame_stats = [] self.h264_stats_file = open( os.path.join(self.tempd, 'h264_stats.csv'), 'w+') self.h264_stats_writer = csv.DictWriter( self.h264_stats_file, ['fps', 'bitrate']) self.h264_stats_writer.writeheader() self.frame_queue = queue.Queue() self.flush_queue_lock = threading.Lock() super().__init__() super().start()
def cloud_service(data_path): #Carrega a classe cloud = Cloud() base_dir = os.path.dirname(os.path.realpath(__file__)) #Load vectoro to data frame pandas data_frame = pd.DataFrame.from_dict(data_path) column_questions = data_frame['response'] #Gera um número aleatório para atribuir ao nome da nuvem name = np.random.randint(1000, 999999) file_path = '%s/clouds/%d.png' % (base_dir, name) #Recebe a nuvem de plavras word_cloud = cloud.get_cloud(column_questions.str.cat(sep=' ')) #Salva a nuvem em um arquivo para ser acessada posteriormente word_cloud.to_file(file_path) #Imprime o nome na tela para o retorno return file_path
def text_instances(self): for world in self.database: if int(world.weight) > 1000: weight = int(world.weight)//1000 elif int(world.weight) > 100 and int(world.weight) < 1000: weight = int(world.weight)//100 else: weight =int(world.weight) worlds = Text(world.name, weight, world.avg_color) self.text_list.append(worlds) h, w = worlds.get_text_size() self.text_size += h * w self.picture = Cloud(math.ceil(math.sqrt(self.text_size) * self.multiplicator_width), math.ceil(math.sqrt(self.text_size)* self.multiplicator_height), (0, 0, 0), self.image) self.img = self.picture.create_cloud()
def run(): cloud = Cloud() flag = True while flag: word = input("请输入搜索词...\n") songs = cloud.search(word) ids = pretty_songs(songs) yn = input("是否需要下载(y/n)\n") if yn == "y": dl = True while dl: index = int(input("请选择下载歌曲(输入id即可)\n")) try: music_file = f"{ids[index]}.mp3" cloud.download_music(ids[index], music_file) yn = input("是否下载歌词(y/n)\n") if yn == 'y': words_file = f"{ids[index]}.txt" cloud.download_words(ids[index], words_file) except: print('输入错误') yn = input("是否继续下载(y/n)\n") if yn == "n": dl = False # 结束 yn = input('是否结束程序(y/n)\n') if yn == 'y': flag = False
def moving_camera(self): # if player reaches top of the screen move the camera if self.player.rect.top <= display_height / 3: from random import randrange if randrange(100) < 10: from Cloud import Cloud Cloud(self) self.player.position.y += max(abs(self.player.velocity.y), 3) # move clouds down half of the player speed for cloud in self.clouds: cloudspeed = randrange(1, 3) cloud.rect.y += max(abs(self.player.velocity.y / cloudspeed), 3) # move EnemyFly down based on player speed for enemyfly in self.enemyFly: enemyfly.rect.y += max(abs(self.player.velocity.y), 3) # move platforms down based on player speed for plat in self.platforms: plat.rect.y += max(abs(self.player.velocity.y), 3) if plat.rect.top >= display_height: plat.kill() self.highscore.score += 10
class Control(): database = [] text_list = [] multiplicator_height = 2 multiplicator_width = 1 image = "" @staticmethod def input_ceck(): if not os.path.isfile("user.txt"): print("Creating user.txt...") with open("user.txt", "w") as f: f.write(input("dbname=")) f.write("\n" + input("user="******"\n" + input("password="******"user.txt created successfully") @classmethod def menu(cls): cls.input_ceck() tag_cloud_1 = """(1) Generates tag cloud that shows the company names: - font size based on number of projects (the more, the bigger) - font color are a mixture of their project colors""" tag_cloud_2 = """(2) Generates tag cloud that shows the project names: - font size based on the budget of the project (the more, the bigger) - font color based on the project colors""" tag_cloud_3 = """(3) Generates tag cloud that shows the project names: - font size based on the due date of the project (the older, the smaller) - font color based on whether the project requires maintenance or not""" tag_cloud_4 = """(4) Generates tag cloud that shows the names of the manager: - font size based on the budget of the project (the older, the smaller) - font color is based on the company they work for""" for i in range(1, 5): print("(%d) Generate tag cloud. Type 'info %d' for more information." % (i, i)) user_input = input("").lower() while True: if user_input == "info 1": print(tag_cloud_1) user_input = input("").lower() if user_input == "info 2": print(tag_cloud_2) user_input = input("").lower() if user_input == "info 3": print(tag_cloud_3) user_input = input("").lower() if user_input == "info 4": print(tag_cloud_4) user_input = input("").lower() if user_input == "1": cls.database = Company.get_companies() cls.multiplicator_height = 1.5 cls.multiplicator_width = 2.7 cls.image = "image.jpg" break if user_input == "2": cls.database = Image2.get_image2() cls.multiplicator_height = 1.5 cls.multiplicator_width = 3 cls.image = "image7.jpg" break if user_input == "3": cls.database = Image3.get_image3() cls.multiplicator_height = 1.8 cls.multiplicator_width = 3.4 cls.image = "image6.jpg" break if user_input == "4": cls.database = Manager.get_all() cls.multiplicator_height = 1.5 cls.multiplicator_width = 3 cls.image = "image.jpg" break else: print("Unavailable, please try again.") def __init__(self): self.text_size = 0 self.picture = 0 self.free_places = [] self.img = 0 def text_instances(self): for world in self.database: if int(world.weight) > 1000: weight = int(world.weight)//1000 elif int(world.weight) > 100 and int(world.weight) < 1000: weight = int(world.weight)//100 else: weight =int(world.weight) worlds = Text(world.name, weight, world.avg_color) self.text_list.append(worlds) h, w = worlds.get_text_size() self.text_size += h * w self.picture = Cloud(math.ceil(math.sqrt(self.text_size) * self.multiplicator_width), math.ceil(math.sqrt(self.text_size)* self.multiplicator_height), (0, 0, 0), self.image) self.img = self.picture.create_cloud() def place_pictures(self): draw = ImageDraw.Draw(self.img) MAX_HEIGHT = self.picture.max_height MAX_WIDTH = self.picture.max_width # .ceil(math.sqrt(text_size))*2 min_fontsize = Text.MIN_FONTSIZE height = 0 width = 0 row_height = [] random.shuffle(self.text_list) for i in self.text_list: text_content = i.name font = ImageFont.truetype("arial.ttf", min_fontsize + (i.weight * 2)) text_size = draw.textsize(text_content, font=font) # draw.text((x, y),text_content,(r,g,b)) print(text_size) if width + text_size[0] > MAX_WIDTH: height += max([i for i in row_height]) row_height = [] width = 0 draw.text((width, height), text_content, i.color, font=font) row_height.append(min_fontsize + (i.weight * 2)) width += text_size[0] def process_method(self): self.input_ceck() self.menu() self.text_instances() self.place_pictures() self.img.show()
# cap = cv2.VideoCapture('../videos/test_kitti984.mp4') # cap = cv2.VideoCapture('../videos/test_kitti984_reverse.mp4') cap = cv2.VideoCapture('../videos/test_freiburgxyz525.mp4') W = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) H = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) F = 300 # focal distance of camera MIRROR = not True # try to recover points mis-triangulated behind the camera REVERSE = False # hack for camera moving backwards SBP_PX = 5 # max euclidian distance to search by projection K = np.array([[F, 0, W/2], [0, F, H/2], [0, 0, 1 ]]) c = Cloud() while(cap.isOpened()): _, img = cap.read() f_new = Frame(img, K) c.addFrame(f_new) if f_new.id == 0: continue print(f"\n*** frame {f_new.id} ***") f_old = c.frames[-2] # old frame kp indices, new frame kp indices, pose delta idx_old, idx_new, Rt = matchFrames(f_old, f_new, REVERSE) f_new.pose = np.dot(Rt, f_old.pose)
def play(self): pygame.mouse.set_visible(False) my_gun = Gun(game) birds = [] clouds = [] donkeys = [] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == pygame.MOUSEMOTION: my_gun.x = pygame.mouse.get_pos()[0] my_gun.y = pygame.mouse.get_pos()[1] if event.type == pygame.MOUSEBUTTONDOWN: if my_gun.fire(birds, donkeys): self.score += 1 if my_gun.bullet == 0: self.game_over() random_number = random.random() if random_number < 0.02: birds.append(Duck(game, self.new_speed)) elif random_number < 0.04: birds.append(Stork(game, self.new_speed)) if random_number < 0.004: clouds.append(Cloud(game)) if random_number < 0.002: donkeys.append(Donkey(game)) for bird in birds: bird.move() self.dsply.blit(self.bg, (0, 0)) my_gun.show() for bird in birds: bird.show() for donkey in donkeys: donkey.show() for cloud in clouds: cloud.show() if cloud.y == 250: clouds.remove(cloud) score_text = self.font.render(f'Score: {self.score}', True, (255, 255, 255)) textRect = score_text.get_rect() textRect.center = (self.width // 2, self.height - 40) bullet_text = self.font.render(f'Bullets: {my_gun.bullet}', True, (255, 255, 255)) bullet_textRect = bullet_text.get_rect() bullet_textRect.center = (100, self.height - 40) self.dsply.blit(bullet_text, bullet_textRect) self.dsply.blit(score_text, textRect) pygame.display.update() self.clock.tick(30)
def test_Cloud00_WrongAuth(self): c = Cloud('WRONG_TOKEN') stat, res = c.task('list', 5, 0) self.assertFalse(stat)
class test_Cloud(unittest.TestCase): '''Local test token have to be store_requestd in file 'OAuth.info' with following format: CLOUD_TOKEN/API_TOKEN: <OAuth token> CircleCi token is in the environment variable CLOUD_TOKEN/API_TOKEN ''' cloud = Cloud( getenv('API_TOKEN') if getenv('CIRCLE_ENV') == 'test' else findall(r'API_TOKEN: (.*)', open('OAuth.info', 'rt').read())[0].strip()) def test_Cloud00_DiskInfo(self): stat, res = self.cloud.task('info') self.assertTrue(stat) self.assertIs(type(res), dict) def test_Cloud00_WrongAuth(self): c = Cloud('WRONG_TOKEN') stat, res = c.task('list', 5, 0) self.assertFalse(stat) def test_Cloud10_Dir_1Create(self): # create new folder stat, res = self.cloud.task('mkdir', 'test dir') self.assertTrue(stat) self.assertTrue(res == ('mkdir', 'test dir')) # create the same new folder again stat, res = self.cloud.task('mkdir', 'test dir') self.assertTrue(stat) # this error should be ignored self.assertTrue(res == ('mkdir', 'test dir')) # try to create new folder within non-existing folder stat, res = self.cloud.task('mkdir', 'not_existing_dir/bla-bla/dir') self.assertFalse(stat) self.assertTrue(res[:2] == ('mkdir', 'not_existing_dir/bla-bla/dir')) self.assertIs(type(res[-1]), dict) def test_Cloud10_Dir_2move(self): # move from existing folder 'test dir' to non-existing folder 'newtestdir' stat, res = self.cloud.task('move', 'newtestdir', 'test dir') self.assertTrue(stat) self.assertTrue(res == ('move', 'newtestdir', 'test dir')) # try to move existing folder to non-existing folder stat, res = self.cloud.task('move', 'not_existing_dir/bla-bla', 'newtestdir') self.assertFalse(stat) self.assertTrue(res[:2] == ('move', 'not_existing_dir/bla-bla')) self.assertIs(type(res[-1]), dict) # try to move from non-existing folder to non-existing one stat, res = self.cloud.task( 'move', 'not_existing_dir/bla-bla', 'test dir', ) self.assertFalse(stat) self.assertTrue(res[:2] == ('move', 'not_existing_dir/bla-bla')) self.assertIs(type(res[-1]), dict) def test_Cloud10_Dir_3copy(self): # copy from existing folder 'newtestdir' to non-existing folder 'test dir' stat, res = self.cloud.task('copy', 'test dir', 'newtestdir') self.assertTrue(stat) self.assertTrue(res == ('copy', 'test dir', 'newtestdir')) # try to copy existing folder to non-existing folder stat, res = self.cloud.task('copy', 'not_existing_dir/bla-bla', 'newtestdir') self.assertFalse(stat) self.assertTrue(res[:2] == ('copy', 'not_existing_dir/bla-bla')) self.assertIs(type(res[-1]), dict) # try to copy from non-existing folder to non-existing one stat, res = self.cloud.task( 'copy', 'not_existing_dir/bla-bla', 'testdir_1', ) self.assertFalse(stat) self.assertTrue(res[:2] == ('copy', 'not_existing_dir/bla-bla')) self.assertIs(type(res[-1]), dict) def test_Cloud10_Dir_4del(self): # remove existing folder stat, res = self.cloud.task('del', 'newtestdir') self.assertTrue(stat) self.assertTrue(res == ('del', 'newtestdir')) # remove another existing folder stat, res = self.cloud.task('del', 'test dir') self.assertTrue(stat) self.assertTrue(res == ('del', 'test dir')) # remove non-existing folder stat, res = self.cloud.task('del', 'not_existing_dir/bla-bla') self.assertFalse(stat) self.assertTrue(res[:2] == ('del', 'not_existing_dir/bla-bla')) self.assertIs(type(res[-1]), dict) def test_Cloud20_bigDir_1copy(self): stat, res = self.cloud.task('copy', 'MusicTest', 'Music') self.assertTrue(stat) self.assertTrue(res == ('copy', 'MusicTest', 'Music')) def test_Cloud20_bigDir_2move(self): stat, res = self.cloud.task('move', 'MusicTestTest', 'MusicTest') self.assertTrue(stat) self.assertTrue(res == ('move', 'MusicTestTest', 'MusicTest')) def test_Cloud20_bigDir_3delete(self): stat, res = self.cloud.task('del', 'MusicTestTest') self.assertTrue(stat) self.assertTrue(res == ('del', 'MusicTestTest')) def test_Cloud30_props_1set(self): stat, res = self.cloud.task('prop', 'Sea.jpg', uid=1000, gid=1000, mode=33204) self.assertTrue(stat) self.assertTrue(res == ('prop', 'Sea.jpg')) def test_Cloud30_props_2get(self): stat, res = self.cloud.task('res', 'Sea.jpg') self.assertTrue(stat) self.assertIs(type(res), dict) props = res.get("custom_properties") self.assertFalse(props is None) self.assertEqual(props.get('uid'), 1000) self.assertEqual(props.get('gid'), 1000) self.assertEqual(props.get('mode'), 33204) def test_Cloud40_wrong_res(self): stat, res = self.cloud.task('res', 'not_existing_file.bla_bla') self.assertIs(type(res), tuple) self.assertFalse(stat) self.assertTrue(res[:2] == ('res', 'not_existing_file.bla_bla')) self.assertIs(type(res[-1]), dict) def _trush(self): # first run can be asynchronous stat, res = self.cloud.task('trash') self.assertTrue(stat) stat, res = self.cloud.task('info') self.assertTrue(stat) self.assertEqual(res.get('trash_size', -1), 0) # first run can be synchronous stat, res = self.cloud.task('info') self.assertTrue(stat) stat, res = self.cloud.task('info') self.assertTrue(stat) self.assertEqual(res.get('trash_size', -1), 0) def test_Cloud50_trush(self): self._trush() self._trush() def test_Cloud60_1up(self): stat, res = self.cloud.task('up', 'README.md', 'README.md') self.assertTrue(stat) def test_Cloud60_2down(self): stat, res = self.cloud.task('down', 'README.md', '/tmp/README.md') self.assertTrue(stat) remove('/tmp/README.md') self.cloud.task('del', 'README.md') def test_Cloud70_last(self): stat, res = self.cloud.task('last') self.assertTrue(stat) self.assertIs(type(res), list) def test_Cloud80_list(self): stat, res = self.cloud.task('list', 5, 0) self.assertTrue(stat) self.assertIs(type(res), list) self.assertEqual(len(res), 5) def test_Cloud80_wrong_list(self): stat, res = self.cloud.task('list', 7777777777, 0) self.assertFalse(stat) def test_Cloud90_wrong_delete(self): stat, res = self.cloud.task('del', 'not_existing_file.bla_bla') self.assertFalse(stat)
help="Uses sample density if True (1)") args = parser.parse_args() D = args.D L = args.L C = args.C N = args.N mat = args.mat lmbd = args.lmbd uniform = args.uniform sample = args.sample name = str(args.D) + str(args.L) + str(args.C) + str(args.N) + str( args.mat) + str(args.lmbd) + str(args.uniform) + str(args.sample) cloud, density = Cloud(D, N, L, C, uniform=uniform, sample=sample).point_array # print(density) #Plotting For the Particles in Space # fig = plt.figure() # ax = fig.add_subplot(111, projection='3d') # # ax.scatter(cloud[:,0], cloud[:,1], cloud[:,2], c='r', marker='.') # r = [0, L] # for s, e in combinations(np.array(list(product(r, r, r))), 2): # if np.sum(np.abs(s-e)) == r[1]-r[0]: # ax.plot3D(*zip(s, e), color="b") # # u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j] # x = L/2*np.cos(u)*np.sin(v) + L/2
import time from std_msgs.msg import String, Float64 from sensor_dist_ros.msg import floatArray as floatArray from sensor_dist_ros.msg import floatArray2 as floatArray2 from sensor_dist_ros.msg import sens as Data from Cloud import Cloud from Sim import Sim from BoundedVoronoi import BoundedVoronoi global bigS, bounding_box, simVoronoi, sim, points, BigC bounding_box = np.array([0, 10, 0, 10]) soft_bounding_box = np.array([0, 10, 0, 10]) simVoronoi = BoundedVoronoi(None, bounding_box) sim = Sim(simVoronoi, bounding_box, soft_bounding_box) points = np.zeros((4, 2)) BigC = Cloud(sim) count = 0 def robot0Callback(data): global points, BigC BigC.updateData([data.x, data.y, data.sensor]) points[0, :] = np.array(([data.x, data.y])) def robot1Callback(data): global points, BigC BigC.updateData([data.x, data.y, data.sensor]) points[1, :] = np.array(([data.x, data.y]))
aws_ip = '-'.join(sys.argv[2].split('.')) elif len(sys.argv) == 4: if sys.argv[3] == 'perf': PERF = True else: usage() aws_ip = '-'.join(sys.argv[2].split('.')) else: usage() FPS = 10 RES = 1080 alpr = None if PERF: FPS = 1 RES = 720 if mode == 'local': alpr = Local(fps=FPS, res=RES) elif mode == 'cloud': alpr = Cloud(fps=FPS, res=RES, ip=aws_ip) elif mode == 'hybrid': alpr = Hybrid(fps=FPS, res=RES, ip=aws_ip) print('\n\nPERFORMANCE\n\n') COPY = PLATES[:] alpr.find(COPY) print('\n\nDONE PERFORMACE\n\n') else: # for video_fps in [1, 5, 10]: for video_fps in [0.1, 0.5]: if mode == 'local': alpr = Local(fps=video_fps, res=RES) elif mode == 'cloud': alpr = Cloud(fps=video_fps, res=RES, ip=aws_ip) elif mode == 'hybrid': alpr = Hybrid(fps=video_fps, res=RES, ip=aws_ip) print('\n\n%d FPS\n\n' % video_fps) COPY = PLATES[:] alpr.find(COPY) print('\n\nDONE FPS\n\n')
class Streaming(threading.Thread): def __init__(self): # Create the olympe.Drone object from its IP address self.drone = olympe.Drone(DRONE_IP) self.detector = DiseaseDetector.DiseaseDetector() self.cloud = Cloud() self.counter_frames = 0 self.tempd = tempfile.mkdtemp(prefix="olympe_streaming_test_") print("Olympe streaming output dir: {}".format(self.tempd)) self.h264_frame_stats = [] self.h264_stats_file = open( os.path.join(self.tempd, 'h264_stats.csv'), 'w+') self.h264_stats_writer = csv.DictWriter( self.h264_stats_file, ['fps', 'bitrate']) self.h264_stats_writer.writeheader() self.frame_queue = queue.Queue() self.flush_queue_lock = threading.Lock() super().__init__() super().start() def start(self): # Connect the the drone self.drone.connect() # You can record the video stream from the drone if you plan to do some # post processing. self.drone.set_streaming_output_files( h264_data_file=os.path.join(self.tempd, 'h264_data.264'), h264_meta_file=os.path.join(self.tempd, 'h264_metadata.json'), # Here, we don't record the (huge) raw YUV video stream # raw_data_file=os.path.join(self.tempd,'raw_data.bin'), # raw_meta_file=os.path.join(self.tempd,'raw_metadata.json'), ) # Setup your callback functions to do some live video processing self.drone.set_streaming_callbacks( raw_cb=self.yuv_frame_cb, h264_cb=self.h264_frame_cb, start_cb=self.start_cb, end_cb=self.end_cb, flush_raw_cb=self.flush_cb, ) # Start video streaming self.drone.start_video_streaming() def stop(self): # Properly stop the video stream and disconnect self.drone.stop_video_streaming() self.drone.disconnect() self.h264_stats_file.close() def yuv_frame_cb(self, yuv_frame): """ This function will be called by Olympe for each decoded YUV frame. :type yuv_frame: olympe.VideoFrame """ yuv_frame.ref() self.frame_queue.put_nowait(yuv_frame) def flush_cb(self): with self.flush_queue_lock: while not self.frame_queue.empty(): self.frame_queue.get_nowait().unref() return True def start_cb(self): pass def end_cb(self): pass def h264_frame_cb(self, h264_frame): """ This function will be called by Olympe for each new h264 frame. :type yuv_frame: olympe.VideoFrame """ # Get a ctypes pointer and size for this h264 frame frame_pointer, frame_size = h264_frame.as_ctypes_pointer() # For this example we will just compute some basic video stream stats # (bitrate and FPS) but we could choose to resend it over an another # interface or to decode it with our preferred hardware decoder.. # Compute some stats and dump them in a csv file info = h264_frame.info() frame_ts = info["ntp_raw_timestamp"] if not bool(info["h264"]["is_sync"]): if len(self.h264_frame_stats) > 0: while True: start_ts, _ = self.h264_frame_stats[0] if (start_ts + 1e6) < frame_ts: self.h264_frame_stats.pop(0) else: break self.h264_frame_stats.append((frame_ts, frame_size)) h264_fps = len(self.h264_frame_stats) h264_bitrate = ( 8 * sum(map(lambda t: t[1], self.h264_frame_stats))) self.h264_stats_writer.writerow( {'fps': h264_fps, 'bitrate': h264_bitrate}) def show_yuv_frame(self, window_name, yuv_frame): # the VideoFrame.info() dictionary contains some useful information # such as the video resolution info = yuv_frame.info() height, width = info["yuv"]["height"], info["yuv"]["width"] # yuv_frame.vmeta() returns a dictionary that contains additional # metadata from the drone (GPS coordinates, battery percentage, ...) # convert pdraw YUV flag to OpenCV YUV flag cv2_cvt_color_flag = { olympe.PDRAW_YUV_FORMAT_I420: cv2.COLOR_YUV2BGR_I420, olympe.PDRAW_YUV_FORMAT_NV12: cv2.COLOR_YUV2BGR_NV12, }[info["yuv"]["format"]] # yuv_frame.as_ndarray() is a 2D numpy array with the proper "shape" # i.e (3 * height / 2, width) because it's a YUV I420 or NV12 frame # Use OpenCV to convert the yuv frame to RGB cv2frame = cv2.cvtColor(yuv_frame.as_ndarray(), cv2_cvt_color_flag) cv2_cvt_color_flag_RGB = { olympe.PDRAW_YUV_FORMAT_I420: cv2.COLOR_YUV2RGB_I420, olympe.PDRAW_YUV_FORMAT_NV12: cv2.COLOR_YUV2RGB_NV12, }[info["yuv"]["format"]] image = cv2.cvtColor(yuv_frame.as_ndarray(), cv2_cvt_color_flag_RGB) # image = cv2.imread(os.getcwd() + "/1224.png") # image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Check if the current frame has a disease self.counter_frames = self.counter_frames + 1 if self.counter_frames%60 == 0 and self.detector.detect(image): print ("\n---------Disease found at:------------") self.cloud.save_ocurrence(self.drone,image) self.counter_frames = 0 # Use OpenCV to show this frame cv2.imshow(window_name, cv2frame) cv2.waitKey(1) # please OpenCV for 1 ms... def run(self): window_name = "Olympe Streaming Example" cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) main_thread = next( filter(lambda t: t.name == "MainThread", threading.enumerate()) ) while main_thread.is_alive(): with self.flush_queue_lock: try: yuv_frame = self.frame_queue.get(timeout=0.01) except queue.Empty: continue try: self.show_yuv_frame(window_name, yuv_frame) except Exception: # We have to continue popping frame from the queue even if # we fail to show one frame traceback.print_exc() finally: # Don't forget to unref the yuv frame. We don't want to # starve the video buffer pool yuv_frame.unref() cv2.destroyWindow(window_name) def move(self,x=0,y=0,z=0,rot=0): self.drone( moveBy(x, y, -z, rot) ).wait() def spiralMove(self,R=6,z_shift=0.2,rot_shift=math.pi/3): sleepTime = 0.1 x_shift = R*(1-math.cos(rot_shift)) y_shift = R*math.sin(rot_shift) print ("Spiral movement going up...") for i in range(0,6): self.move(x_shift,y_shift,z_shift,-rot_shift) time.sleep(sleepTime) print ("Spiral movement going down...") for i in range(0,6): self.move(x_shift,y_shift,-z_shift,-rot_shift) def autonomousFlight(self): self.move(1) self.spiralMove(R=6,z_shift=1) # go for the healthy plant self.move(0,0,0,math.pi) self.move(2) self.spiralMove(R=6,z_shift=1) # go for the sick plant self.move(-1) def takeOff(self): print("Takeoff if necessary...") self.drone( FlyingStateChanged(state="hovering", _policy="check") | FlyingStateChanged(state="flying", _policy="check") | ( GPSFixStateChanged(fixed=1, _timeout=10, _policy="check_wait") >> ( TakeOff(_no_expect=True) & FlyingStateChanged( state="hovering", _timeout=10, _policy="check_wait") ) ) ).wait() self.drone(MaxTilt(40)).wait().success() def land(self): print("Landing...") self.drone( Landing() >> FlyingStateChanged(state="landed", _timeout=5) ).wait() print("Landed\n") def fly(self): # Takeoff self.takeOff() # Autonomous Flight self.autonomousFlight() # Land self.land() # Close Flight Report self.cloud.close_report() def postprocessing(self): # Convert the raw .264 file into an .mp4 file h264_filepath = os.path.join(self.tempd, 'h264_data.264') mp4_filepath = os.path.join(self.tempd, 'h264_data.mp4') subprocess.run( shlex.split('ffmpeg -i {} -c:v copy -y {}'.format( h264_filepath, mp4_filepath)), check=True ) # Replay this MP4 video file using the default video viewer (VLC?) subprocess.run( shlex.split('xdg-open {}'.format(mp4_filepath)), check=True )
def getClouds(self, cloudlist, img): clouds = [ Cloud(self.label_To_index(label, img)) for label, size in cloudlist ] return clouds
__maintainer__ = "Samuel de Oliveira Gamito" __email__ = "*****@*****.**" __status__ = "Production" from Cloud import Cloud import pandas as pd import numpy as np import sys import json if __name__ == "__main__": sys.stderr.close() #Close error output #Carrega a classe cloud = Cloud() if (not sys.argv[1] or sys.argv[1] == ""): print("erro") #Carrega o argumento 1 contendo o caminho para o arquivp de log data_path = sys.argv[1] #Load vectoro to data frame pandas data_frame = pd.read_json(data_path, orient='records') column_questions = data_frame['resposta'] #Gera um número aleatório para atribuir ao nome da nuvem name = np.random.randint(1000, 999999) #Recebe a nuvem de plavras
# Add a new enemy? elif event.type == ADDENEMY: # scale velocities with score ls = 0 hs = 10 + scoreCounter // 50 pp = player.rect.centery # Create the new enemy and add it to sprite groups new_enemy = Enemy(ls, hs, pp) enemies.add(new_enemy) all_sprites.add(new_enemy) # Add a new cloud? elif event.type == ADDCLOUD: # Create the new cloud and add it to sprite groups new_cloud = Cloud() clouds.add(new_cloud) all_sprites.add(new_cloud) # # # UPDATE PLAYER POSITION # Get the set of keys pressed and check for user input pressed_keys = pygame.key.get_pressed() # # # UPDATE HARMLESS CLOUDS clouds.update() # # # UPDATE ENEMIES enemies.update() # Update the player sprite based on user keypresses player.update(pressed_keys)
def __init__(self): pygame.init() #Sets Up Screen screen = pygame.display.set_mode((1080, 540)) pygame.display.set_caption('Kangaroo Run') white = (255, 255, 255) score = 0 highscore = 0 scorefile = open("../assets/scores.txt", "r") highscore = int(scorefile.read()) scorefile.close() '''Fonts''' myfont = pygame.font.SysFont("../assets/font.ttf", 18) titlefont = pygame.font.SysFont("../assets/font.ttf", 40) '''Text''' textstart = myfont.render("Press S to Start", 0, (0, 0, 0)) texttitle = titlefont.render("Kangaroo Run", 0, (0, 0, 0)) textre = myfont.render("Press R to Restart", 0, (0, 0, 0)) textqu = myfont.render("Press Q to Quit", 0, (0, 0, 0)) textps = myfont.render("Press P To Pause/Resume", 0, (0, 0, 0)) textgo = myfont.render("Game Over", 0, (0, 0, 0)) '''Background''' background = pygame.Surface(screen.get_size()) background = background.convert() background.fill(white) backGround = Background('../assets/background.png') screen.blit(background, (0, 0)) pygame.display.flip() screen.blit(backGround.image, backGround.rect) kang = Kangaroo() kangSprite = pygame.sprite.RenderPlain(kang) cact = Cactus() cactSprite = pygame.sprite.RenderPlain(cact) cact2 = Cactus() cact2Sprite = pygame.sprite.RenderPlain(cact2) cloud = Cloud() cloudSprite = pygame.sprite.RenderPlain(cloud) cloud2 = Cloud() cloud2Sprite = pygame.sprite.RenderPlain(cloud) '''Music''' pygame.mixer.init(22050, -16, 2, 4096) pygame.mixer.music.load("../assets/song.mp3") pygame.mixer.music.set_volume(.5) pygame.mixer.music.play(-1) clock = pygame.time.Clock() done = False start = False game_over = False pause = False pauseCount = 1 while not done: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: '''Jump''' if event.key == pygame.K_UP and pause == False: kang.jump() '''Restart''' if event.key == pygame.K_r: kang.reinit() cact.reinit() cact2.reinit() cloud.reinit() cloud2.reinit() score = 0 pause = False pauseCount = 1 game_over = False '''Quit''' if event.key == pygame.K_q: done = True '''Pause''' if event.key == pygame.K_p and start: pauseCount += 1 if pauseCount % 2 == 0: kang.freezeKang() cact.freezeCact() cact2.freezeCact() pause = True elif pauseCount % 2 == 1: kang.resumeKang() cact.resumeCact() cact2.resumeCact() pause = False '''Start''' if event.key == pygame.K_s: start = True screen.blit(backGround.image, (0, 0)) screen.blit(backGround.image, backGround.rect) '''Title Screen''' if not start: screen.blit(textstart, (510, 120)) screen.blit(texttitle, (460, 75)) screen.blit(textre, (500, 170)) screen.blit(textqu, (510, 200)) screen.blit(textps, (480, 230)) '''Collision''' if kang.rect.colliderect(cact.rect) or kang.rect.colliderect( cact2.rect): kang.collide() game_over = True '''Game Over Screen''' if game_over: screen.blit(textgo, (500, 150)) screen.blit(textre, (480, 180)) screen.blit(textqu, (490, 210)) kang.freezeKang() cact.freezeCact() cact2.freezeCact() '''Sets new highscore''' if score > highscore: highscore = score scorefile = open("../assets/scores.txt", "w") scorefile.write(str(highscore)) scorefile.close() '''Pause Screen''' if pause and start: screen.blit(textps, (425, 10)) '''Displays Score''' if start: label = myfont.render("Score: {0}".format(score), 0, (0, 0, 0)) texths = myfont.render("High Score: {0}".format(highscore), 0, (0, 0, 0)) screen.blit(label, (950, 10)) screen.blit(texths, (950, 40)) if not game_over and not pause and start: score += 1 '''Loads cactus and kangaroo after start''' kang.draw(screen) kangSprite.update() cact.draw(screen) cactSprite.update() if score > 1000: cact2.v = cact.v cact2.draw(screen) cact2Sprite.update() cloud.draw(screen) cloudSprite.update() cloud2.draw(screen) cloud2Sprite.update() pygame.display.update() pygame.display.flip()