Beispiel #1
0
 def __init__(self, game):
     """
     Initializes the player ship parameters.
     """
     pygame.sprite.Sprite.__init__(self)
     
     self.game = game
     
     self.unmasked_image, self.rect = utilities.load_image(data.filepath(settings.UNMASKED_BG_IMAGE_PATH))
     self.masked_image, _= utilities.load_image(data.filepath(settings.MASKED_BG_IMAGE_PATH))
     
     self.image = self.masked_image.copy()
     self.image.set_colorkey((255, 255,0))
     
     self.last_brighten = (0, 0)
     
     #Load music and ambient sound:
     self.tracks = []
     self.cur_track = 0
     for track in settings.MUSIC_TRACKS:
         sound = pygame.mixer.Sound(data.filepath(track))
         self.tracks.append(sound)
         
     self.start_music()
     
     self.ambient_sounds = []
     for i in settings.AMBIENT_SOUNDS:
         self.ambient_sounds.append(pygame.mixer.Sound(data.filepath(i)))
     #Schedule an ambient event about every two minutes:
     pygame.time.set_timer(settings.SCHEDULE_AMBIENT_EVENT, 2 * 60 * 1000)
Beispiel #2
0
    def __init__(self, top):
        # Call the parent class (Sprite) constructor
        Enemy.__init__(self, top)
        self.pop_sound = utilities.load_sound('balloon_pop.wav')

        info = pygame.display.Info()
        screenWidth = info.current_w

        choice = np.random.choice([0, 0, 0, 1, 1, 2])

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        if choice == 0:
            self.image = utilities.load_image('green_balloon.png')
            self.floatspeed = 1
            self.AWARD = 5
        elif choice == 1:
            self.image = utilities.load_image('blue_balloon.png')
            self.floatspeed = 1.5
            self.AWARD = 7
        elif choice == 2:
            self.image = utilities.load_image('red_balloon.png')
            self.floatspeed = 2
            self.AWARD = 10
        self.image = pygame.transform.scale(self.image, (15, 30))
        self.image.set_colorkey(colors.WHITE)

        # Fetch the rectangle object that has the dimensions of the image
        # Update the position of this object by setting the values of rect.x and rect.y
        self.rect = self.image.get_rect()
        self.rect.y = top
        self.rect.x = screenWidth
        self.lives = 1
def main(args: Optional[argparse.Namespace] = None):
    if args is None:
        args = parse_arguments()

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # load model & data
    target_image = utilities.preprocess_image(
        utilities.load_image(args.img_path))
    net = model.Model(args.model_path, device, target_image)

    # synthesize
    optimizer = optimize.Optimizer(net, args)
    result = optimizer.optimize()

    # save result
    final_image = utilities.postprocess_image(
        result, utilities.load_image(args.img_path))
    final_image.save(os.path.join(args.out_dir, 'output.png'))

    # plot loss
    x = list(
        range(args.checkpoint_every - 1,
              len(optimizer.losses) * args.checkpoint_every,
              args.checkpoint_every))
    plt.plot(x, optimizer.losses)
    plt.savefig(os.path.join(args.out_dir, 'loss_plot.png'))
    plt.close()

    # save intermediate images
    for i, image in enumerate(optimizer.opt_images):
        image.save(
            os.path.join(
                args.out_dir,
                'intermediate_image_{}.png'.format(i * args.checkpoint_every)))
Beispiel #4
0
    def draw(self):
        # self.drawing_surf.fill(pygame.SRCALPHA)
        # pygame.draw.circle(self.drawing_surf,(0,0,200), (3,3),2)


        if self.num_airplane == 0:
            self.drawing_surf.blit(load_image('bullet_blue.png',alpha_cannel=1),(0,0))
        elif self.num_airplane == 1:
            self.drawing_surf.blit(load_image('bullet_yellow.png',alpha_cannel=1),(0,0))
Beispiel #5
0
 def mover(self, keys, time, objetos):
     # Mueve para arriba
     if self.rect.top >= 0: 
         if keys[K_UP]:
             self.rect.centery -= self.speed * time
             if self.imgItem == 4: self.imgItem = 0
             self.image = utilities.load_image(self.backImages[self.imgItem], True)
             self.imgItem += 1
             
     # Mueve para abajo
     if self.rect.bottom <= utilities.HEIGHT: 
         if keys[K_DOWN]:
             self.rect.centery += self.speed * time
             if self.imgItem == 4: self.imgItem = 0
             self.image = utilities.load_image(self.frontImages[self.imgItem], True)
             self.imgItem += 1
     # Mueve para la derecha
     if self.rect.right <= utilities.WIDTH:
         if keys[K_RIGHT]:
             self.rect.centerx += self.speed * time
             if self.imgItem == 4: self.imgItem = 0
             self.image = utilities.load_image(self.rightImages[self.imgItem], True)
             self.imgItem += 1
     # Mueve para la izquierda        
     if self.rect.left >= 0:
         if keys[K_LEFT]:
             self.rect.centerx -= self.speed * time
             if self.imgItem == 4: self.imgItem = 0
             self.image = utilities.load_image(self.leftImages[self.imgItem], True)
             self.imgItem += 1
             
     lista_impactos = pygame.sprite.spritecollide(self, objetos, False)
     
     for c in lista_impactos:
         #Si nos estamos desplazando hacia la derecha, hacemos que nuestro lado derecho sea el lado izquierdo del objeto que hemos tocado-
         if keys[K_RIGHT]:
             self.rect.right = c.rect.left
             continue
         elif keys[K_LEFT]:
             # En caso contrario, si nos desplazamos hacia la izquierda, hacemos lo opuesto.
             self.rect.left = c.rect.right
             continue
         if keys[K_UP]:
             self.rect.top = c.rect.bottom
             continue 
         elif keys[K_DOWN]:
             self.rect.bottom = c.rect.top
             continue   
    
     
     # Reseteamos nuestra posicion basandonos en la parte superior/inferior del objeto.
         
           
          
             
    def test_activations_source_image(self):
        important_layers = ['relu1_1', 'pool1', 'pool2', 'pool3', 'pool4']

        synthesis_model = utilities.load_model(PYTORCH_MODEL_PATH)

        # register hooks to extract the important activations
        hook = ActivationsHook()
        for name, layer in synthesis_model.named_children():
            if name in important_layers:
                layer.register_forward_hook(hook)

        # load an image and pass it through the synthesis model
        source_image = utilities.preprocess_image(
            utilities.load_image(SOURCE_IMG_PATH))

        synthesis_model(source_image)

        # check if they are correct
        with h5py.File(REF_VALS_PATH, 'r') as f:
            for i, layer_name in enumerate(important_layers):
                if layer_name == 'relu1_1':
                    layer_name = 'conv1_1'

                actual_activations = hook.activations[i]
                expected_activations = torch.from_numpy(
                    f['source_img_activations_{}'.format(layer_name)][()])

                assert torch.allclose(actual_activations,
                                      expected_activations,
                                      atol=1e-05)
Beispiel #7
0
 def initGraphics(self, pos):
     self.img = utilities.load_image('ball.png')
     self.img = pygame.transform.scale(self.img, (5, 5))
     self.img.set_colorkey((255, 255, 255))
     self.rect = self.img.get_rect()
     self.rect.center = pos
     self.sound = utilities.load_sound('explosion.wav')
Beispiel #8
0
 def initGraphics(self, pos):
     self.image = utilities.load_image('ball.png')
     self.image = pygame.transform.scale(self.image, (5, 5))
     self.image.set_colorkey(colors.WHITE)
     self.rect = self.image.get_rect()
     self.rect.center = pos
     self.sound = utilities.load_sound('bullet.wav')
Beispiel #9
0
 def loadAction(self,action,fileroot,headings,frames,suffix):
     self.actions[action] = {}
     for h in headings:
         self.actions[action][h] = []
         for f in frames:
             filename = fileroot + action + h + f + '.' + suffix
             self.actions[action][h].append(utilities.load_image(filename))
    def predict(self, images):
        image_batch = []
        for i in images:
            img = utilities.load_image(i)
            img = img.reshape((IMG_HEIGHT, IMG_WIDTH, 3))
            image_batch.append(img)


        feed_dict = {self.input_: image_batch}
        with tf.Session() as sess:
            code = sess.run(self.vgg.relu6, feed_dict=feed_dict)


        feed = {self.inputs_: code}
        prediction = self.sess.run(self.predicted, feed_dict=feed).squeeze()

        import matplotlib.pyplot as plt
        from scipy.ndimage import imread

        for i in range(len(images)):
            test_img = imread(images[i])

            plt.subplot(121)
            plt.imshow(test_img)
            plt.subplot(122)
            plt.barh(np.arange(5), prediction[i])
            _ = plt.yticks(np.arange(5), self.lb.classes_)
            plt.show()
Beispiel #11
0
	def fromFile(self,datapath,filename):
		if not os.path.exists(os.path.join(datapath, filename)): debug.debugMessage(3,"   Style file not located, using null style!")
		else:
			FILE=open(os.path.join(datapath, filename),"r")
			full=FILE.read()+chr(10)
			FILE.close()
			mode=0
			script=""
			cchar=''
			current=''
			numbers  =['0','1','2','3','4','5','6','7','8','9']
			letters  =[' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
			legitchars=letters+numbers+['_','.']
			funcchars=['#','=','-',':','+',';']
			endl     =[chr(10)]
			for cchar in full:
				current+=cchar
				if   mode==0:
					if   cchar in legitchars:
						current+=cchar
					elif cchar == chr(10):
						self.image=utilities.load_image(os.path.join(datapath,filename))
						current=''
				elif mode==1:
					if   cchar in numbers:
						current+=cchar
					else:
						current=''
Beispiel #12
0
 def change_image(self,status):  #меняет картинка на картинку с тайлом прозрачности и обратно
     if status=='on' and not self.transparent:  #status - если 'on', то картинка делается невидимой, и если тайл еще не невидимый
         self.image.blit(self.transparent_image,(0,0))
         self.transparent = True
     elif status=='off':
         self.image = load_image(self.image_name,path='Images/Tiles', alpha_channel=True)
         self.transparent = False
Beispiel #13
0
    def __init__(self, server):
        pygame.init()
        self.screen = pygame.display.set_mode((RESX, RESY), 0, 32)
        pygame.display.set_caption("BlackJack beta")
        self.myFont = pygame.font.SysFont("None", 16, bold=False, italic=False)
        self.run = True
        self.deck_image = load_image(path=os.path.join("images", "cards"), name="back.png")
        self.deck_pos = (600, 50)
        self.server = server

        # buttons form
        self.buttons_form = ButtonsForm((300, 550), self.screen, self.server)

        # connect form
        self.connect_form = ConnectForm((0, 0), self.screen, self.server)

        # login form
        self.login_form = LoginForm((0, 0), self.screen, self.server)

        # Игроки, Диллер
        self.players_position = [(275, 400), (25, 400), (525, 400)]
        self.dealer_position = (250, 75)
        self.current_player = None
        self.dealer = Dealer(self.dealer_position)
        self.other_players = []
        self.server = Server()
        self.current_id = None
Beispiel #14
0
def start_game():
    button_start = Button(pos=(478, 240), path='images/buttons',
                          image_names=('start_off.png', 'start_hover.png', 'start_click.png'),
                          function=run, w=144, h=35)
    button_players = Button(pos=(478, 320), path='images/buttons',
                            image_names=('best_players_off.png', 'best_players_hover.png', 'best_players_click.png'),
                            function=run, w=144, h=35)
    button_settings = Button(pos=(478, 400), path='images/buttons',
                             image_names=('settings_off.png', 'settings_hover.png', 'settings_click.png'),
                             function=run, w=144, h=35)
    button_exit = Button(pos=(478, 480), path='images/buttons',
                         image_names=('exit_off.png', 'exit_hover.png', 'exit_click.png'),
                         function=sys.exit, w=144, h=35)

    buttons = (button_start, button_players, button_settings, button_exit)

    while True:
        screen.blit(load_image('main_background.png', alpha_cannel=0), (0, 0))

        for event in pygame.event.get():
            for button in buttons:
                # Пересылаем все события кнопке
                button.event(event)
                if event.type == pygame.QUIT:
                    sys.exit()

                    # Обновляем и отрисовываем кнопку на экране
        for button in buttons:
            button.update(0)
            button.render(screen)

        pygame.display.flip()
Beispiel #15
0
def random_batch(samples,
                 dataset_path,
                 batch_size,
                 img_size,
                 random_seed=None,
                 include_angles=True,
                 include_speed=True,
                 nof_outputs=2):
    images = np.zeros((batch_size, img_size[0], img_size[1], 3))
    steers = np.zeros((batch_size, nof_outputs))
    image_names = []

    np.random.seed(random_seed)
    for i, index in enumerate(np.random.choice(samples.shape[0], batch_size)):
        speed = samples.iloc[index, 0]
        angle = samples.iloc[index, 1]
        image_name = samples.iloc[index, 2]

        image_path = samples.iloc[index, 2]
        image = utilities.load_image(dataset_path, image_path)

        images[i] = preprocess(image, img_size)
        steers[i] = [angle, speed] if (include_angles and include_speed) \
            else ([speed] if include_speed else [angle])
        image_names.append(image_name)

    np.random.seed(None)
    return {"images": images, "steers": steers, "image_names": image_names}
def main(
    img_path, dimension, shave, batch_size, scale, print_result, device, model_name
):
    """
    Takes an image path and model name and produce the high resolution version
    of that image with the help of that model
    """
    if model_name == "EDSR":
        input_image = ut.load_image(img_path)
    elif model_name == "RRDB":
        # input_image = ut.load_grayscale_image(img_path)
        input_image = ut.npz_loader(img_path)
        # print(input_image.shape)
    else:
        raise Exception("{} : Unknown model...".format(model_name))

    output_image = bpfc.patch_batch_forward_chop(
        input_image,
        dimension,
        shave,
        scale,
        batch_size,
        model_type=model_name,
        print_timer=True,
    )
    if print_result:
        np.savez("results/outputx4.npz", output_image)
        np.save("results/outputx4", output_image)
    def test_activations_two_consecutive_runs(self):
        important_layers = ['relu1_1', 'pool1', 'pool2', 'pool3', 'pool4']

        # load an image
        source_image = utilities.preprocess_image(
            utilities.load_image(SOURCE_IMG_PATH))

        activations = []
        for j in range(2):
            # load a model and pass the image through it
            synthesis_model = utilities.load_model(PYTORCH_MODEL_PATH)

            # register hooks to extract the important activations
            hook = ActivationsHook()
            for name, layer in synthesis_model.named_children():
                if name in important_layers:
                    layer.register_forward_hook(hook)

            synthesis_model(source_image)

            # save activations from the last important layer
            activations.append(hook.activations[-1])

        assert torch.equal(activations[0], activations[1]), \
            'mean error: {}'.format(
                (activations[0] - activations[1]).abs().mean()
            )
Beispiel #18
0
def trt_helper_upsampler_piterative_experiment(model_name,
                                               trt_engine_path,
                                               img_path,
                                               patch_dimension,
                                               shave=10,
                                               use_fp16=False):
    """
    Driver function to run a trtengine

    Parameters
    ----------
    model_name : str
        name of the model (i.e. "EDSR", "RRDB")
    trt_engine_path : str
        path of the trt engine.
    img_path : str
        path of the image file.
    patch_dimension : int
        patch_size.
    shave : int, optional
        patch overlapping size. The default is 10.

    Returns
    -------
    None.

    """
    # Loading model and image
    if model_name in ['EDSR']:
        img = ut.load_image(img_path)
        input_image = img.unsqueeze(0)
    elif model_name in ["RRDB"]:
        img = ut.npz_loader(img_path)
        input_image = img.unsqueeze(0)
    else:
        print('Unknown model!')
        return

    b, c, h, w = input_image.shape

    total_time = ut.timer()
    out_tuple = trt_forward_chop_iterative_v2(
        input_image,
        trt_engine_path=trt_engine_path,
        shave=shave,
        min_size=patch_dimension * patch_dimension,
        device="cuda",
        use_fp16=use_fp16,
        print_result=True,
    )
    output_image = out_tuple[0]
    total_time = total_time.toc()

    # =============================================================================
    #     for i in out_tuple[1:]:
    #         print(i)
    # =============================================================================
    print('Total executing time: ', total_time)
    return output_image
    def __init__(self, target_dynamic_path, target_static_path, config):
        Optimizer.__init__(self, tf.Graph(), 256, 8, target_dynamic_path,
                           target_static_path, config)

        with self.graph.as_default():
            with tf.device('/gpu:' + str(self.user_config['gpu'])):
                # load dynamic texture
                imgs = load_images(target_dynamic_path,
                                   size=(self.input_frame_count,
                                         self.input_dimension,
                                         self.input_dimension))
                self.target_dynamic_texture = [
                    tf.to_float(
                        tf.constant(
                            img.reshape(1, self.input_dimension,
                                        self.input_dimension, 3)))
                    for img in imgs
                ]

                # load static texture (for dynamics style transfer)
                img = load_image(target_static_path,
                                 size=(self.input_dimension,
                                       self.input_dimension))
                self.target_static_texture = tf.to_float(
                    tf.constant(
                        img.reshape(1, self.input_dimension,
                                    self.input_dimension, 3)))

                # TODO: check for b/w input
                # initialize noise
                initial_noise = tf.random_normal([
                    self.user_config['batch_size'], self.input_frame_count,
                    self.input_dimension, self.input_dimension, 3
                ])
                self.output = tf.Variable(initial_noise, name='output')

                # TODO: let weight be user-definable
                # build appearance descriptors (one for each frame)
                self.appearance_loss = \
                    self.build_appearance_descriptors(
                        'appearance_descriptors', 1e9)

                # TODO: let weight be user-definable
                # build dynamics descriptors (one for each pair of
                # frames)
                self.dynamics_loss = \
                    self.build_dynamics_descriptors('dynamics_descriptors',
                                                    1e15)

                # evaluate dynamic texture loss
                self.dyntex_loss = tf.add(self.appearance_loss,
                                          self.dynamics_loss)

                # averaging loss over batch
                self.dyntex_loss = tf.div(self.dyntex_loss,
                                          self.user_config['batch_size'])

                # attach summaries
                self.attach_summaries('summaries')
Beispiel #20
0
def load_training_data(batch):
    """
    in: data frame batch with {0: 'Center', 1: 'Left', 2: 'Right', 3: 'Steering Angle'}
    out: for this batch a list of all images (training data) and steering angles (labels)
    function: 
        1. load images based on the paths in the data frame batch file
        2. adjust steering angle for right or left shifted/recorded images
        3. do image augmentation and preprocessing for the nn model
        4. output all images and steering anles in 2 lists
    """
    
    left_cf = utilities.left_cf     # correction factor for steering angle for left image 
    right_cf = utilities.right_cf   # correction factor for steering angle for right image 
    list_images = []            # empty list for output
    list_steering_angle = []    # empty list for output
    
    for index, row in batch.iterrows():
        # load path for images
        path_left = utilities.get_rel_path(row['Left'])
        path_right = utilities.get_rel_path(row['Right'])
        path_center = utilities.get_rel_path(row['Center'])
        center_angle = float(row['Steering Angle'])
        # load Images
        left_img = utilities.load_image(path_left)
        center_img = utilities.load_image(path_right)
        right_img = utilities.load_image(path_center)
        # For the shifted richt and left images: adjust the steering angle
        lenft_angle = center_angle + left_cf
        right_angle = center_angle - right_cf
        # Augment the Image
        left_img_aug, lenft_angle = pipeline_augment(left_img, lenft_angle)
        center_img_aug, center_angle = pipeline_augment(center_img, center_angle)
        right_img_aug, right_angle = pipeline_augment(right_img, right_angle)
        # Preprocess (Cropping, resizing, transformation in YUV-Colorspace) the augmented images
        left_img_aug_prepro = utilities.preprocess_image(left_img_aug)
        center_img_aug_prepro = utilities.preprocess_image(center_img_aug)
        right_img_aug_prepro = utilities.preprocess_image(right_img_aug)
        # append Images and steering angles to lists for output
        list_images.append(left_img_aug_prepro)
        list_steering_angle.append(lenft_angle)
        list_images.append(center_img_aug_prepro)
        list_steering_angle.append(center_angle)
        list_images.append(right_img_aug_prepro)
        list_steering_angle.append(right_angle)
        
    return list_images, list_steering_angle
Beispiel #21
0
 def __init__(self, pos, image=PU_IMAGE, time=PU_TIME):
     pygame.sprite.Sprite.__init__(self) #call Sprite initializer
     imagePath = os.path.join(SOURCE_DIR, IMAGE_DIR, image)
     self.image, self.rect = load_image(imagePath)
     self.time = time*FRAMES_PER_SECOND
     self.rect.center = pos
     self.mask = pygame.mask.from_surface(self.image)
     self.activated = False
     self.ball = None
Beispiel #22
0
def get_x(folder_path):
    listdir = os.listdir(folder_path)
    x = np.ndarray((len(listdir), 50, 50))
    for i, image in enumerate(listdir):
        print(image)

        x[i, :, :] = utilities.load_image(folder_path + "/" + image)
    print(utilities.flatten_input(x).shape)
    return utilities.flatten_input(x)
    def test_original_values(self):
        source_img = utilities.load_image(SOURCE_IMG_PATH)
        transform = torchvision.transforms.ToTensor()
        actual_source_img = transform(source_img).permute(1, 2, 0)

        with h5py.File(REF_VALS_PATH, 'r') as f:
            expected_source_img = torch.from_numpy(f['source_img'][()])

            assert torch.equal(actual_source_img, expected_source_img)
def test(image, vgg16_npy_path):
    import matplotlib.pyplot as plt
    from scipy.ndimage import imread
    import csv
    with open("labels", "r") as f:
        reader = csv.reader(f, delimiter='\n')
        labels = np.array([x  for x in reader if len(x) > 0]).squeeze()

    from sklearn.preprocessing import LabelBinarizer
    lb = LabelBinarizer()
    lb.fit(labels)
    #labels_vec = lb.transform(labels)



    test_img = imread(image)
    input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])
    with tf.Session() as sess:
        vgg = VGG16(vgg16_npy_path)
        vgg.build_network(input_)

        img = utilities.load_image(image)
        img = img.reshape((1, IMG_HEIGHT, IMG_WIDTH, 3))

        feed_dict = {input_: img}
        code = sess.run(vgg.relu6, feed_dict=feed_dict)



    inputs_ = tf.placeholder(tf.float32, shape=[None, code.shape[1]])
    labels_ = tf.placeholder(tf.int64, shape=[None, 5])

    fc = tf.contrib.layers.fully_connected(inputs_, 256)

    logits = tf.contrib.layers.fully_connected(fc, 5, activation_fn=None)
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=labels_, logits=logits)
    cost = tf.reduce_mean(cross_entropy)

    optimizer = tf.train.AdamOptimizer().minimize(cost)

    predicted = tf.nn.softmax(logits)
    correct_pred = tf.equal(tf.argmax(predicted, 1), tf.argmax(labels_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

    saver = tf.train.Saver()
    with tf.Session() as sess:
        saver.restore(sess, tf.train.latest_checkpoint("checkpoints"))
        feed = {inputs_: code}
        prediction = sess.run(predicted, feed_dict=feed).squeeze()

    plt.subplot(121)
    plt.imshow(test_img)
    plt.subplot(122)
    plt.barh(np.arange(5), prediction)
    _ = plt.yticks(np.arange(5), lb.classes_)
    plt.show()
def main(img_path, model_name, patch_dimension):
    """
    Driver for recursive forward chop. Takes an image path and model name to upsample the image.
    """

    # Loading model and image
    img = None
    model = None
    print("\nLoading model and image... \n")
    if model_name in ["EDSR"]:
        img = ut.load_image(img_path)
        img = img.unsqueeze(0)
        model = md.load_edsr(device="cuda")
    else:
        img = ut.npz_loader(img_path)
        img = img.unsqueeze(0)
        model = md.load_rrdb(device="cuda")

    # Timers for saving stats
    timer = [0, 0, 0, 0, 0]

    print("Processing...")

    # Shfiting input image to CUDA
    total_time = ut.timer()
    cpu2gpu_time = ut.timer()
    img = img.to("cuda")
    cpu2gpu_time = cpu2gpu_time.toc()

    # Forward chopping and upsampling
    output = forward_chop(
        img, model, timer=timer, min_size=patch_dimension * patch_dimension
    )

    # Shifting output image to CPU
    gpu2cpu_time = ut.timer()
    output = output.to("cpu")
    gpu2cpu_time = gpu2cpu_time.toc()
    if model_name in ["EDSR"]:
        output = output.int()
    total_time = total_time.toc()

    timer[0] = cpu2gpu_time
    timer[-2] = gpu2cpu_time
    timer[-1] = total_time

    # Saving output
    np.savez("results/recursive_outputx4.npz", output)
    np.save("results/recursive_outputx4", output)

    # Printing processing times
    print("\nCPU 2 GPU time: ", timer[0])
    print("\nUpsampling time: ", timer[1])
    print("\nMerging time: ", timer[2])
    print("\nGPU 2 CPU time", timer[3])
    print("\nTotal execution time: ", timer[4])
Beispiel #26
0
def load_lit_image(image_path, width, height, mode='vgg19'):
    nat_image = load_image(image_path, cast=tf.uint8)
    nat_size = nat_image.shape[:-1]
    image = tf.image.resize(tf.cast(nat_image, tf.float32), [width, height])
    if mode == 'vgg19':
        image = vgg19_process_image(image)
    else:
        raise NotImplementedError('Other Network Formats not Supported')
    image = tf.expand_dims(image, axis=0)
    return image, nat_size
    def test_preprocessed_values(self):
        source_img = utilities.load_image(SOURCE_IMG_PATH)
        actual_preprocessed_image = utilities.preprocess_image(source_img)

        with h5py.File(REF_VALS_PATH, 'r') as f:
            expected_preprocessed_image = torch.from_numpy(
                f['source_img_preprocessed'][()])

            assert torch.equal(actual_preprocessed_image,
                               expected_preprocessed_image)
 def __init__(self,column,row,image_name, img_dir_name = 'Images/Static_objs',w=62,h=62):
     self.row = row
     self.column = column
     self.type = 'type'
     self.image_name = image_name
     self.image = load_image(image_name, path=img_dir_name, alpha_channel=True)
     self.image = pygame.transform.scale(self.image,(w,h))
     self.rect = self.image.get_rect()
     self.rect.x = self.column*self.rect.w
     self.rect.y = self.row*self.rect.h
Beispiel #29
0
    def __init__(self, width=GRID_UNIT, height=GRID_UNIT):
        # Call the parent class (Sprite) constructor
        pygame.sprite.Sprite.__init__(self)

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        self.image = load_image('White_Block', (width, height))

        # Fetch the rectangle object that has the dimensions of the image
        # Update the position of this object by setting the values of rect.x and rect.y
        self.rect = self.image.get_rect()
Beispiel #30
0
    def __init__(self, pos, color):
        # Call the parent class (Sprite) constructor
        pygame.sprite.Sprite.__init__(self)
        self.pop_sound = utilities.load_sound('balloon_pop.wav')

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        if color == colors.DARK_GREEN:
            self.image = utilities.load_image('green_balloon.png')
        elif color == colors.DARK_BLUE:
            self.image = utilities.load_image('blue_balloon.png')
        elif color == colors.DARK_RED:
            self.image = utilities.load_image('red_balloon.png')
        self.image = pygame.transform.scale(self.image, (10, 20))
        self.color = color

        # Fetch the rectangle object that has the dimensions of the image
        # Update the position of this object by setting the values of rect.x and rect.y
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.y = self.rect.y
Beispiel #31
0
    def __init__(self, pos, life=1, image=BRICK_SPRITE, damage=1, points=1):

        assert life % 1 == 0, "Brick life must be an integer."

        pygame.sprite.Sprite.__init__(self)  # call Sprite initializer
        self.image, self.rect = load_image(image)
        self.life = life
        self.rect.center = pos
        self.damage = damage
        self.destroyed = False
        self.points = points
        self.mask = pygame.mask.from_surface(self.image)
Beispiel #32
0
def helper_upsampler_piterative_experiment(model_name, img_path,
                                           patch_dimension):
    """
    Driver function for running pytorch model inference

    Parameters
    ----------
    img_dimension : int
        image one side dimension.
    patch_dimension : int
        patch size.

    Returns
    -------
    None.

    """
    # Loading model and image
    if model_name in ['EDSR']:
        model = md.load_edsr(device="cuda")
        img = ut.load_image(img_path)
        input_image = img.unsqueeze(0)
    elif model_name in ["RRDB"]:
        model = md.load_rrdb(device="cuda")
        img = ut.npz_loader(img_path)
        input_image = img.unsqueeze(0)
    else:
        print('Unknown model!')
        return

    b, c, h, w = input_image.shape

    total_time = ut.timer()
    out_tuple = forward_chop_iterative(
        input_image,
        shave=10,
        min_size=patch_dimension * patch_dimension,
        model=model,
        device="cuda",
        print_result=True,
    )
    model.cpu()
    del model
    output_image = out_tuple[0]
    total_time = total_time.toc()

    # =============================================================================
    #     for i in out_tuple[1:]:
    #         print(i)
    # =============================================================================
    print('Total executing time: ', total_time)
    return output_image
Beispiel #33
0
 def __init__(self, game_board):
     pygame.sprite.Sprite.__init__(self)
     
     self.game_board = game_board
     
     image_file_path = settings.BASE_ENEMY_IMAGE_PATH
     self.image , self.rect = utilities.load_image(image_file_path)
     
     self.rect.center = self.game_board.get_enemy_spawn()
     
     #Declare some variables:
     self.movement_per_press = settings.PLAYER_MOVE_SPEED
     self.current_direction = settings.D_UP
Beispiel #34
0
 def __init__(self,column,row,type, image_name=None, parent=None):
     self.image_name = None
     if not image_name:
         if type == 'grass':
             self.image_name = 'tile_grass.jpg'
         elif type == 'hole':
             self.image_name = 'tile_hole.png'
         elif type == 'water':
             self.image_name = 'tile_water.gif'
     else:
         self.image_name = image_name   #имя картинки
     self.image = load_image(self.image_name, path='Images/Tiles')  #сама картинка
     self.transparent_image = load_image('transparent_tile.png',path='Images', alpha_channel=True)  #прозрачная картинка, которая накладывается поверх тайла
     self.rect = self.image.get_rect()  #рект картинки
     self.column = column  #столбик, в котором находится тайл
     self.row = row  #строка, в которой находится тайл
     self.type = type #тип тайла
     self.transparent = False  #показатель невидимости. False - тайл видимый
     x = column*self.rect.w     #координата х тайла равна номер столбика умножить на ширину картинки тайла
     y = row*self.rect.h        #координата у тайла равна номер строки умножить на высоту картинки тайла
     self.rect.x = x
     self.rect.y = y
Beispiel #35
0
    def render(self, screen):  # блитуем

        if self.rendering_hit > 0:
            self.rendering_hit += 1
            if self.rendering_hit == 15:
                self.rendering_hit = 0
        if self.hp != 0:
            len_vector_speed = math.sqrt(self.speed_vector[0] ** 2 + self.speed_vector[1] ** 2)

            normal_speed_vector = (self.speed_vector[0] / len_vector_speed, self.speed_vector[1] / len_vector_speed)

            self.angle_of_rotate = math.acos(normal_speed_vector[0]) * 180 / math.pi
            if self.speed_vector[1] > 0:
                self.angle_of_rotate *= -1
            else:
                self.angle_of_rotate = math.fabs(self.angle_of_rotate)

            rotated_airplane_img = pygame.transform.rotate(self.images[self.num_img],
                                                           self.angle_of_rotate)  # поворачиваем картинку аэроплана
            rect_img = rotated_airplane_img.get_rect()

            rect_img.center = self.position_vector  # центр картинки приравниваем вектору позиции

            screen.blit(rotated_airplane_img, rect_img)  # блитуем все на скрин
        else:
            screen.blit(load_image('collision.png', alpha_cannel=1),
                        (self.position_vector[0] - 25, self.position_vector[1] - 25))

        if self.rendering_hit != 0:
            screen.blit(load_image('hit.png', alpha_cannel=1),
                        (self.position_vector[0] - 15, self.position_vector[1] - 15))

        if self.status_of_parallel_motion == True:  # если статус параллельного движения True
            screen.blit(rotated_airplane_img, self.position_vector_2)  # то блитуем паралельный объект

        # отрисовывываем пули
        if self.status_airplane == True:
            for bull in self.bullets:
                bull.render(screen)
Beispiel #36
0
    def initGraphics(self, screen):
        SceneBase.initGraphics(self, screen)

        self.ball = utilities.load_image('ball.png')
        self.ballrect = self.ball.get_rect()
        self.ballrect.left, self.ballrect.top = 0, 0
        width, height = 20, 20
        self.obj = pygame.Surface([width, height])
        self.obj.fill(colors.RED)
        info = pygame.display.Info()
        screenWidth, screenHeight = info.current_w, info.current_h
        self.objrect = pygame.Rect(screenWidth / 4, screenHeight - height,
                                   width, height)
Beispiel #37
0
    def __init__(self, position_vector=(0, 0), speed_vector=(0, 0), num_img=0):
        if num_img == 0:
            self.name = "Airplane-1"
        elif num_img == 1:
            self.name = "Airplane-2"
        else:
            self.name = "Un-Airplane"

        self.position_vector = position_vector  # вектор позиции
        self.speed_vector = speed_vector  # вектор скорости
        self.accel_vector = (0, 0)  # вектор ускорения
        self.dir = None  # направление
        self.angle = 8  # угол поворота в градусах
        self.drawing_surf = pygame.Surface((45, 45), pygame.SRCALPHA)
        self.rect = self.drawing_surf.get_rect()
        self.rect.x, self.rect.y = (self.position_vector)
        self.num_img = num_img  # номер картинки(1го игрока - 0 , 2го - 1)
        self.d_acsel = 2  # ускорение вектора скорости
        self.dir_of_accel = None  # направление ускорения
        self.gravity_vector = (0, -0.5)  # вектор тяжести
        self.status_of_parallel_motion = False  # статус паралельного движения
        self.bullets = []  # пули
        self.status_fire = True  # возможность стрельбы
        self.press_button_fire = False  # статус клавиши огонь (пробел)
        self.fire_rate = 3  # Темп стрельбы, раз в сек
        self.delay_to_fire = 0  # дилэй с предыдушего выстрела
        self.number_bullets = 0  # кол-во пуль
        self.angle_of_rotate = -45  # угол поворота
        self.images = [load_image('airplane.PNG', alpha_cannel=1), load_image('second_airplane.png', alpha_cannel=1)]
        self.hp = 5  # кол-во хп
        self.rendering_hit = 0
        self.key_left = None
        self.key_right = None
        self.key_up = None
        self.key_down = None
        self.key_fire = None
        self.status_airplane = True  # состояние самолета (True - не убит/False - убит)
        self.keys = []
        self.keys_state = 0b00000  # Состояние функциональных клавишь
Beispiel #38
0
 def __init__(self, front, back, left, right, x, y):
     # Llamo al constructor de la super clase
     pygame.sprite.Sprite.__init__(self)
     
     self.frontImages = front
     self.backImages = back
     self.rightImages = right
     self.leftImages = left
     self.speed = 0.1
     self.image = utilities.load_image(self.frontImages[0], True)
     self.imgItem = 0
     self.rect = self.image.get_rect()
     self.rect.centerx = x
     self.rect.centery = y
Beispiel #39
0
def extract_features(x, labels, sess, Dfx, training=True):
    if training:
        data_path = FLAGS.train_dataset
        features_path = "features_train.npy"
        labels_path = "labels_train.npy"
    else:
        data_path = FLAGS.test_dataset
        features_path = "features_test.npy"
        labels_path = "labels_test.npy"

    data_files = glob(os.path.join("./data", data_path, "*.jpg"))
    shuffle(data_files)
    num_batches = min(len(data_files), FLAGS.train_size) // FLAGS.batch_size
    #num_batches =2

    num_examples = num_batches * FLAGS.batch_size
    y = np.zeros(num_examples, dtype=np.uint8)
    for i in range(num_examples):
        for j in range(len(labels)):
            if labels[j] in data_files[i]:
                y[i] = j
                break

    features = np.zeros((num_examples, FLAGS.features_size))

    for batch_i in range(num_batches):
        batch_files = data_files[batch_i * FLAGS.batch_size:(batch_i + 1) *
                                 FLAGS.batch_size]
        batch = [
            utilities.load_image(batch_file,
                                 FLAGS.image_size,
                                 is_crop=FLAGS.is_crop,
                                 resize_w=FLAGS.output_size)
            for batch_file in batch_files
        ]
        batch_x = np.array(batch).astype(np.float32)

        f = sess.run(Dfx, feed_dict={x: batch_x})
        begin = FLAGS.batch_size * batch_i
        end = FLAGS.batch_size + begin
        features[begin:end, ...] = f

    print("Features Extracted, Now saving")
    np.save(os.path.join(FLAGS.feature_dir, features_path), features)
    np.save(os.path.join(FLAGS.feature_dir, labels_path), y)

    print("Features Saved")

    sys.stdout.flush()
Beispiel #40
0
    def render_hp(self, screen):
        if self.name == "Airplane-1":
            if self.hp == 5:
                screen.blit(load_image('hp_5.png', alpha_cannel=1), (260, 0))
            elif self.hp == 4:
                screen.blit(load_image('hp_4.png', alpha_cannel=1), (260, 0))
            elif self.hp == 3:
                screen.blit(load_image('hp_3.png', alpha_cannel=1), (260, 0))
            elif self.hp == 2:
                screen.blit(load_image('hp_2.png', alpha_cannel=1), (260, 0))
            elif self.hp == 1:
                screen.blit(load_image('hp_1.png', alpha_cannel=1), (260, 0))

        elif self.name == "Airplane-2":
            if self.hp == 5:
                screen.blit(load_image('hp_5.png', alpha_cannel=1), (650, 0))
            elif self.hp == 4:
                screen.blit(load_image('hp_4.png', alpha_cannel=1), (689, 0))
            elif self.hp == 3:
                screen.blit(load_image('hp_3.png', alpha_cannel=1), (728, 0))
            elif self.hp == 2:
                screen.blit(load_image('hp_2.png', alpha_cannel=1), (767, 0))
            elif self.hp == 1:
                screen.blit(load_image('hp_1.png', alpha_cannel=1), (806, 0))
def extract_codes(input_folder, vgg16_npy_path):

    contents = os.listdir(input_folder)
    classes = [each for each in contents if os.path.isdir(input_folder + each)]

    batch_size = 10
    codes_list = []
    labels = []
    batch = []
    codes = None

    with tf.Session() as sess:
        vgg = VGG16(vgg16_npy_path)
        _input = tf.placeholder(tf.float32, [None, IMG_WIDTH, IMG_HEIGHT, 3])
        with tf.name_scope("content_vgg"):
            vgg.build_network(_input)

        for cls in classes:
            print ("Processing {} images ...".format(cls))
            class_path = input_folder + cls

            files = os.listdir(class_path)
            for i, file in enumerate(files, 1):
                img = utilities.load_image(os.path.join(class_path, file))
                batch.append(img.reshape((1, IMG_WIDTH, IMG_HEIGHT, 3)))
                labels.append(cls)

                if i % batch_size == 0 or  i == len(files):
                    images = np.concatenate(batch)
                    feed_dict = {_input: images}
                    codes_batch = sess.run(vgg.relu6, feed_dict=feed_dict)

                    if codes is None:
                        codes= codes_batch
                    else:
                        codes = np.concatenate((codes, codes_batch))

                    batch = []
                    prog = float(i) * 100.0 / float(len(files))
                    if prog % 10 == 0:
                        print("{}% processed...".format(prog))

        with open("codes", "w") as f:
            codes.tofile(f)
        import csv
        with open("labels","w") as f:
            writer = csv.writer(f, delimiter='\n')
            writer.writerow(labels)
Beispiel #42
0
    def game_over(self):
        self.screen.fill((0,0,0))
        
        skull_image, skull_rect = utilities.load_image(data.filepath(settings.SKULL_IMAGE_PATH), False)

        while 1:
            for event in pygame.event.get():
                if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                    return
                
            if not random.randint(0, 10) % 5:
                x = random.choice(range(self.screen.get_width()))
                y = random.choice(range(self.screen.get_height()))
                self.screen.blit(skull_image, (x, y))
                
            pygame.display.update()
    def test_noise_image(self):
        noise_image = None
        with h5py.File(REF_VALS_PATH, 'r') as f:
            noise_image = torch.from_numpy(f['noise1234'][()])

        target_image = utilities.preprocess_image(
            utilities.load_image(SOURCE_IMG_PATH))

        model = Model(PYTORCH_MODEL_PATH, torch.device('cpu'), target_image)

        model(noise_image)
        actual_loss_value = model.get_loss().detach().cpu()

        with h5py.File(REF_VALS_PATH, 'r') as f:
            expected_loss_value = torch.tensor(f['loss_value'][()],
                                               dtype=torch.float32)

            assert torch.allclose(actual_loss_value, expected_loss_value)
Beispiel #44
0
    def __init__(self, ws):
        pygame.init()
        self.screen = pygame.display.set_mode((RESX, RESY), 0, 32)
        pygame.display.set_caption("BlackJack v0.1.0a")
        self.run = True
        self.deck_image = load_image(path=os.path.join("images", "cards"), name="back.png")
        self.deck_pos = (600, 50)
        self.ws = ws
        # self.ws.connect()

        # Кнопки gui:
        self.app = app = gui.App()
        self.rect = pygame.Rect((300, 550, 175, 25))
        connect_button = gui.Button("Connect")
        connect_button.connect(gui.CLICK, self.but_connect)
        table = gui.Table()
        table.td(connect_button)
        app.init(widget=table, screen=self.screen, area=self.rect)

        # login form
        self.login_form = LoginForm((200, 200), self.screen, self.ws)


        # Колода
        self.deck = Deck()

        # Диллер
        self.dealer = Dealer((250, 110), self.deck)

        # Список игроков

        # self.players = [Player((25, 400), self.deck), Player((275, 400), self.deck), Player((525, 400), self.deck)]
        self.players_position = ((25, 400), (275, 400), (525, 400))
        self.players = []
        self.add_player(1)
        self.add_player(2)
        self.add_player(3)
        self.server = Server()
        # TEMP
        # for player in self.players:
        #     player.add_cards()
        #     player.add_cards()
        self.dealer.add_cards()
        self.dealer.add_cards()
Beispiel #45
0
 def __init__(self, area):
 
     pygame.sprite.Sprite.__init__(self) #call Sprite initializer
     self.image, self.rect = load_image(USER_SPRITE)
     self.area = area
     self.speedLeft = (int(-USER_SPEED / float(FRAMES_PER_SECOND)), 0)
     self.speedRight = (int(USER_SPEED / float(FRAMES_PER_SECOND)), 0)
     self.rect.midbottom = (self.area.centerx, self.area.bottom)
     self.moving = False # flag to indicate if user is currently moving paddle
     self.paused = False # flag to indicate the paddle is paused
     self.direction = None # direction user is moving paddle\
     self.sin = sin
     self.cos = cos
     
     # calculate the minimum angle (in radians) of the ball when bouncing 
     # off the paddle
     self.ballAngleMin = USER_BALL_MINANGLE * pi / 180.
     self.ballAngleMax = USER_BALL_MAXANGLE * pi / 180.
     self.ballAngleRange = self.ballAngleMax - self.ballAngleMin
Beispiel #46
0
    def __init__(self):
        SceneBase.__init__(self)
        info = pygame.display.Info()
        screenWidth, screenHeight = info.current_w, info.current_h

        self.ball = utilities.load_image('ball.png')
        self.ball.set_colorkey(colors.WHITE)
        self.ballrect = self.ball.get_rect()
        self.v = geo.Vector2D.zero()
        self.g = geo.Vector2D(0, 1)
        self.elasticity = 0.8
        self.friction = 0.1

        size = 20
        self.obj = pygame.Surface([size, size])
        self.obj.fill(colors.RED)
        self.objrect = pygame.Rect(screenWidth / 2, screenHeight / 2, size,
                                   size)
        self.hitLast = False

        self.starttime = time.time()
Beispiel #47
0
def train_model(model, num_images):
    df = utilities.augment_dataframe(pd.read_csv(DATA_PATH +
                                                 'driving_log.csv'))

    df_sample = df.sample(num_images)
    train_features = []
    train_labels = []

    for _, row in df_sample.iterrows():
        image_path = DATA_PATH + row.image.strip()
        train_features.append(utilities.load_image(image_path, row.is_flipped))
        train_labels.append(row.steering)

    history = model.fit(np.array(train_features),
                        np.array(train_labels),
                        batch_size=10,
                        nb_epoch=10,
                        validation_split=0.2)
    save_model(model, 'model.json', 'model.h5')

    return history
Beispiel #48
0
def main(BASE_WIDTH, BASE_HEIGHT):
    pygame.init()
    screen = pygame.display.set_mode((BASE_WIDTH, BASE_HEIGHT))
    pygame.display.set_caption('Q-Tetris')

    background = pygame.Surface(screen.get_size())
    background = background.convert()

    image = load_image('big-galaxy', (BASE_WIDTH, BASE_HEIGHT))
    image_rect = image.get_rect()

    background.blit(image, (0, 0))
    screen.blit(background, image_rect)

    grid_size = BASE_WIDTH, BASE_HEIGHT = BASE_WIDTH - BASE_WIDTH / 3, BASE_HEIGHT + 10
    grid = pygame.Rect((4, -15), grid_size)

    i_shape = Shape('I')
    key_pressing = False
    while 1:
        time_now = time.time()

        for event in pygame.event.get():
            print(time_now)
            key_hold = past_time(time_now)
            if event.type == pygame.QUIT:
                sys.exit()

            if event.type == pygame.KEYDOWN:
                key_pressing = True
            if event.type == pygame.KEYUP:
                key_pressing = False

        if key_pressing:
            i_shape.update(event.key)
            screen.blit(background, i_shape.last_location)

        pygame.draw.rect(screen, WHITE, grid, 10)
        screen.blit(i_shape.letter_surface, (i_shape.x_pos, i_shape.y_pos))
        pygame.display.flip()
Beispiel #49
0
 def __init__(self, game_board):
     """
     Initializes the player ship parameters.
     """
     pygame.sprite.Sprite.__init__(self)
     
     self.game_board = game_board
     
     #Load the player image ship:
     image_file_path = settings.PLAYER_SHIP_IMAGE_PATH
     self.image , self.rect = utilities.load_image(image_file_path)
     
     self.rect.center = self.game_board.get_player_start_position()
     
     #Declare some variables:
     self.movement_per_press = settings.PLAYER_MOVE_SPEED
     self.current_direction = settings.D_UP
     self.is_attacking = False
     self.num_of_lines = 0
     self.num_of_points = 0
     
     self.line_segments = []
Beispiel #50
0
def batch_generator(samples,
                    dataset_path,
                    batch_size,
                    img_size,
                    include_angles=True,
                    include_speed=True,
                    nof_outputs=2,
                    augmentation=False):

    images = np.zeros((batch_size, img_size[0], img_size[1], 3))
    steers = np.zeros((batch_size, nof_outputs))

    while True:
        i = 0
        for index in np.random.permutation(samples.shape[0]):
            speed = samples.iloc[index, 0]
            angle = samples.iloc[index, 1]

            image_path = samples.iloc[index, 2]
            image = utilities.load_image(dataset_path, image_path)

            if augmentation:
                if np.random.rand() < 0.6:
                    image, angle = flip(image, angle)
                image = random_hsv_adjustment(image)
                if np.random.rand() < 0.3:
                    image = erasing_spots(image)
                if np.random.rand() < 0.8:
                    image, angle = random_translations(image, angle)

            images[i] = preprocess(image, img_size)
            steers[i] = [angle, speed] if (include_angles and include_speed) \
                else ([speed] if include_speed else [angle])

            i += 1
            if i == batch_size:
                break
        yield images, steers
Beispiel #51
0
 def load_config(self, configFile):
     """
     Loads the stage configuration file from the specified path and updates
     stage attributes in place.
     
     INPUTS:
         configFile  = path to the config file. The configuration file is
             space delimited and each line represents a single feature of
             the stage. Blank lines are allowed. Specify features in the
             first with the feature type and then its details, with each
             detail separated by a space. The following features can be
             specified, and some are required (denoted):
             
             name: (string) name of the stage. Not currently used; required
             number: (int) order of the stage, with lower numbers first; required
             time: (int) amount of time expected to complete the stage; optional
             background: (str) path to the background image; optional
             brick: (at least one required)
                 [1] (int, int) (row, col) top-left brick centroid position in frame; required
                 [2] (int) brick life; optional
                 [3] (int) damage done to brick by ball; make 0 for obstacles; optional
                 [4] (int) number of points awarded when brick is destroyed; optional
                 [5] (str) path to the brick sprite file; optional
             power: (optional)
                 [1] (int, int) (row, col) top-left powerup centroid position in frame; required
                 [2] (str) powerup type; required; options are: {ball_speed, }
             
             An example:
                 
                 name death lazer
                 number 1
                 time 120
                 background bg.png # inside the stage folder
                 brick 100 100 3 2 1 3brick.png
                 brick 200 100 1 1
                 brick 300 200 1 0 1 obstacle.png
                 power 400 400 ball_speed
                 
     OUTPUTS: Updates the Stage object with the objects needed for the stage.
     """
     configdir = os.path.split(os.path.abspath(configFile))[0]
     cnt = 0 # line count
     with open(configFile, 'r') as fh:
         for line in fh:
             cnt += 1
             line = line.strip()
             lowered = line.lower()
             
             # skip empty lines
             if line == '': continue
             
             # skip commented lines
             if lowered.startswith(STAGE_CONFIG_COMMENT): continue
             
             # raise an error for lines with no useful information
             sLine = line.split(STAGE_CONFIG_DELIM, 1)
             if len(sLine) < 1:
                 raise ValueError('Invalid line in configuration file. Line %i' % cnt)
                 
             # parse out other valid stage configuration information
             key, line = sLine
             key = key.lower()
             
             try:
                 if key == STAGE_CONFIG_NAME: self.name = line
                 elif key == STAGE_CONFIG_NUM: self.number = int(line)
                 elif key == STAGE_CONFIG_TIME: self.time = int(line)
                 elif key == STAGE_CONFIG_BG: 
                     imagePath = os.path.join(configdir, line)
                     self.image, self.rect = load_image(imagePath)
                     
                 # load bricks
                 elif key == STAGE_CONFIG_BRICK:
                     sLine = line.split(STAGE_CONFIG_DELIM, 5)
                     optArgs = {}
                     if len(sLine) > 2: optArgs['life'] = int(sLine[2])
                     if len(sLine) > 3: optArgs['damage'] = int(sLine[3])
                     if len(sLine) > 4: optArgs['points'] = int(sLine[4])
                     if len(sLine) > 5:
                         imagePath = os.path.join(configdir, sLine[5])
                         optArgs['image'] = imagePath
                     brick = Brick(
                         (int(sLine[0]), int(sLine[1])),
                         **optArgs
                     )
                     self.bricks.add(brick)
                     if brick.damage == 0: self.nObstacles += 1
                     
                 # load powerups
                 elif key == STAGE_CONFIG_POWER:
                     sLine = line.split(STAGE_CONFIG_DELIM)
                     powerType = sLine[2]
                     if powerType == STAGE_CONFIG_PWBSP:
                         powerup = BallSpeedup((int(sLine[0]), int(sLine[1])))
                     else:
                         raise ValueError('Invalid powerup type %s' % powerType)
                     self.powerups.add(powerup)
                 
                 
             except ValueError as e:
                 print e.message
                 raise ValueError('Invalid line in configuration file. Line %i' % cnt)
                 
     # check that bricks dont overlap
     for brick1 in self.bricks:
         for brick2 in self.bricks:
             if brick1 is not brick2:
                 offsetX = brick2.rect.left - brick1.rect.left
                 offsetY = brick2.rect.top - brick1.rect.top
                 overlap = brick1.mask.overlap_area(brick2.mask, (offsetX, offsetY))
                 if overlap:
                     errMsg = ' '.join([
                         'Bricks may not overlap. Bricks at',
                         '(%i, %i)' % (brick1.rect.centerx, brick1.rect.centery),
                         'and (%i, %i).' % (brick2.rect.centerx, brick2.rect.centery)
                     ])
                     raise ValueError(errMsg)
Beispiel #52
0
 def __init__(self, game):
     pygame.sprite.Sprite.__init__(self)
     self.game = game
     
     self.image, self.rect = utilities.load_image(data.filepath(settings.HEART_IMAGE_PATH), False)
     self.image.set_colorkey((255, 255, 255))
Beispiel #53
0
	def customInit(self,sprops):
		self.player=sprops['player'] #Player holds pointer to the game instance, this allows me to retrieve all game data
		self.camPosition=(0,0)
		self.mode=0
		self.delayedAction=[]
		self.cursor=utilities.load_image(sprops['datapath'],"cursor.png")
database = 'orl_faces/'
subspace = 'orl_subspace.npz'
projections = 'orl_projections_' + str(components) + '.npz'
image_path = database + 's10/1.pgm'

if not os.path.exists(path + subspace):
   M = ut.load_images(database) 
   eigenvalues, W, mu = pca.create_subspace(M, components)
   pca.save_subspace(path + subspace, eigenvalues, W, mu)
else:
   eigenvalues, W, mu = pca.load_subspace(path + subspace)

if not os.path.exists(path + projections):
    for j in range(40):
        index = j + 1
        img = ut.load_image(database + 's' + str(index) + '/9.pgm')
        x = pca.project_image(img,W,mu)
        ut.save_projection('face ' + str(index), x, projections)
        print index

img = ut.load_image(image_path)
x = pca.project_image(img,W,mu)
y = pca.reverse_projection(x,W,mu)
image = ut.normalize_image(ut.unflatten_image(y,rows,columns))
ut.display_image(image, str(400) + ' components')

name, projection = pca.find_closest(x, path + projections)
closest_img = pca.reverse_projection(projection,W,mu)
closest_image = ut.normalize_image(ut.unflatten_image(closest_img,rows,columns))
print name
ut.display_image(closest_image, name[0])
Beispiel #55
0
 def __init__(self, backgroundDir):
     self.backgroundImage = utilities.load_image(backgroundDir)
     self.objetos = pygame.sprite.Group()
     self.personajes = pygame.sprite.Group()
import pca
import os

path = '../data/'

database = 'orl_faces/'
subspace = 'orl_subspace.npz'
image_path = database + 's10/1.pgm'
components = 400
rows = 112
columns = 92

if not os.path.exists(path + subspace):
   M = ut.load_images(database) 
   eigenvalues, W, mu = pca.create_subspace(M, components)
   pca.save_subspace(path + subspace, eigenvalues, W, mu)
else:
   eigenvalues, W, mu = pca.load_subspace(path + subspace)

img = ut.load_image(image_path)
num_components = [1,2,3,4,5,6,7,8,9,10,15,20,50,75,100,150,200,400]
for i in num_components: 
    x = pca.project_image(img,W[:,1:i],mu)
    y = pca.reverse_projection(x,W[:,1:i],mu)
    image = ut.normalize_image(ut.unflatten_image(y,rows,columns))

    original = ut.unflatten_image(img,rows,columns)

    ut.display_image(image, str(i) + ' components')
    ut.display_image(original, 'original')
Beispiel #57
0
	def imageFromFile(self,datapath,filename):
		debug.debugMessage(5," Opening objects image file.")
		self.graphics  = utilities.load_image(datapath,filename)
Beispiel #58
0
	def fromFile(self,datapath,filename):
		debug.debugMessage(5," Loading object set from file.")
		if not os.path.exists(os.path.join(datapath, filename)): debug.debugMessage(0,"   Objectset file not located")
		FILE=open(os.path.join(datapath, filename),"r")
		full=FILE.read()
		cchar=''
		current=''
		mode=-2
		curObject=0
		prop=""
		numbers  =['0','1','2','3','4','5','6','7','8','9']
		letters  =[' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
		funcchars=['#','=','-',':','+',';']
		endl     =[chr(10)]
		for i in range(0,len(full)):
			cchar=full[i]
			if   cchar in numbers:   a=1
			elif cchar in letters:   a=2
			elif cchar in funcchars: a=3
			elif cchar in endl:      a=4
			else:                    a=0
			if   mode == -2:
				if a==4:
					self.graphics=utilities.load_image(datapath,current)
					mode=-1
					current=''
				else: current+=cchar
			elif mode == -1:
				if a==4:
					debug.debugMessage(5,"Loading object action scripts")
					self.loadScripts(datapath,current)
					mode=0
					current=''
				else: current+=cchar
			elif mode ==  0:    #This reads number of object, like "#134#"
				if   a==1:
					current+=cchar
				elif a==4:
					curObject=int(current)
					while(len(self.objectDefinition)<curObject+1):
						self.objectDefinition+= [OBJECTDEF()]
					debug.debugMessage(3,"Loading tile "+current)
					mode=1
					current=''
			elif mode == 1:  #This reads name of the property, like: "name="
				if   a == 1 or a == 2:
					current+=cchar
				elif a==3:
					if cchar == '-' or cchar == '+':
						current+=cchar
					elif cchar == '#':
						current=''
						cchar=''
						mode=0
					else:
						prop=current.lower()
						if prop in ["name","corpse","image"]:
							mode = 2
						else:
							mode = 3
						current=''
			elif mode==2:   #This reads string     value for the property and assigns it
				if a == 1 or a == 2 or a == 3 or a == 0:
					current+=cchar
				elif a == 4:
					if   prop == "name":
						self.objectDefinition[curObject].name=current
					elif prop == "corpse":
						objectset.props.corpse=current
					elif prop == "image":
						b=[]
						curpr=""
						for o in range(0,len(current)):
							if current[o] == ',' or current[o] == ';':
								b+=[int(curpr)]
								curpr=''
							else:
								curpr+=current[o]
						self.objectDefinition[curObject].image=pygame.Rect( b[0], b[1], b[2], b[3])
					#print prop,"=",current
					current=''
					mode=1
			elif mode == 3: #This reads integer(s) value for the property and assigns it
				if   a == 1 or a == 2:
					current+=cchar
				elif a == 4:
					if   prop == "weight":           self.objectDefinition[curObject].props.weight           = int(current)
					elif prop == "speed":            self.objectDefinition[curObject].props.speed            = int(current)
					elif prop == "terrainattackmin": self.objectDefinition[curObject].props.terrainAttack[0] = int(current)
					elif prop == "terrainattackmax": self.objectDefinition[curObject].props.terrainAttack[1] = int(current)
					elif prop == "maxhp":            self.objectDefinition[curObject].props.maxhp            = int(current)
					elif prop == "magicemit":        self.objectDefinition[curObject].props.magic_emit       = int(current)
					elif prop == "movemode":         self.objectDefinition[curObject].props.moveMode         = int(current)
					elif prop == "movemode2":        self.objectDefinition[curObject].props.moveMode2        = int(current)
					elif prop[0:5] == "sprop":
						self.objectDefinition[curObject].props.sprops[prop[5:len(prop)]]             = int(current)
					elif prop[0:6] == "script":
						self.objectDefinition[curObject].props.scripts[prop[6:len(prop)]]            = current
					current=''
					mode=1
Beispiel #59
0
 def __init__(self, rank, suit):
     self.rank = rank
     self.suit = suit
     self.card_name = str(suit + rank) + '.png'
     # FIXME: загружать карты в соответствии с парметрами
     self.image = load_image(path="images/cards", name=self.card_name)