def __init__(self, screen, sprite_sheet, sheet_offsets, pos=(0, 0), resize=None, detail=None, frame_delay=None, flip=False): super().__init__() self.screen = screen if not resize: resize = (self.screen.get_height() // 10, self.screen.get_height() // 10) self.image_manager = ImageManager(sprite_sheet, sheet=True, pos_offsets=sheet_offsets, resize=resize, animation_delay=frame_delay) if flip: self.image_manager.flip() self.image, self.rect = self.image_manager.get_image() if detail: self.detail_piece = ImageManager( detail, sheet=True, pos_offsets=sheet_offsets, resize=resize).all_images()[ 0] # grab first image in detail sheet if flip: self.image_manager.flip() self.image.blit(self.detail_piece, (0, 0)) # combine detail else: self.detail_piece = None self.rect.centerx, self.rect.centery = pos
def __init__(self, screen, x, y, direction, maze, p_type=P_TYPE_1): self.screen = screen self.maze = maze self.direction = direction self.p_type = p_type if p_type == Portal.P_TYPE_1: self.image_manager = ImageManager('blue-portal-bg.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (64, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (64, 32, 32, 32), (0, 64, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=250) image, _ = self.image_manager.get_image() else: self.image_manager = ImageManager('orange-portal-bg.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (64, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (64, 32, 32, 32), (0, 64, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=250) image, _ = self.image_manager.get_image() super().__init__(x, y, maze.block_size, maze.block_size, image)
class Portal(Block): """Represents a single portal as a block in the maze""" P_TYPE_1 = 1 P_TYPE_2 = 2 TYPE_1_COLOR = (0, 255, 255) TYPE_2_COLOR = (255, 128, 0) def __init__(self, screen, x, y, direction, maze, p_type=P_TYPE_1): self.screen = screen self.maze = maze self.direction = direction self.p_type = p_type if p_type == Portal.P_TYPE_1: self.image_manager = ImageManager('blue-portal-bg.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (64, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (64, 32, 32, 32), (0, 64, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=250) image, _ = self.image_manager.get_image() else: self.image_manager = ImageManager('orange-portal-bg.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (64, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (64, 32, 32, 32), (0, 64, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=250) image, _ = self.image_manager.get_image() super().__init__(x, y, maze.block_size, maze.block_size, image) def get_nearest_col(self): """Get the current column location on the maze map""" return (self.rect.x - (self.screen.get_width() // 5)) // self.maze.block_size def get_nearest_row(self): """Get the current row location on the maze map""" return (self.rect.y - (self.screen.get_height() // 12)) // self.maze.block_size def update(self): """Update the portal animations""" self.image = self.image_manager.next_image() def blit(self): """Blit the portal to the screen""" self.screen.blit(self.image, self.rect)
def __init__(self): self.images = np.array([ImageManager(), ImageManager()]) self.bridge = CvBridge() # Intrinsic camera calibration matrices self.camera_K = None self.camera_D = None # Image sizes self.image_h = 1 self.image_w = 1 # Current command sent to duckiebot self.joy_command = Twist2DStamped() # Initiate the feature detector self.cv2_detector = None self.last_ros_time = time.time() self.last_theta = 0 # Initialize parameters self.parameters = VisualOdometryParameters() self.mask_params = [0.5, 0.7, 0.4] self.stingray_mask = [] self.mask_img=None self.histogram_img=None
def __init__(self) -> None: self.image_manager = ImageManager() self.updater = Updater(token=environ.get('HS_TELEGRAM_BOT_TOKEN'), request_kwargs={ "connect_timeout": 60., "read_timeout": 60. }, use_context=True)
def setUp(self): aws_connector = AwsConnector(None) self.s3_resource = aws_connector.get_s3_resource() self.s3_resource.create_bucket( Bucket=self.BUCKET, CreateBucketConfiguration={'LocationConstraint': 'eu-west-2'}, ) self.image_manager = ImageManager(self.s3_resource, self.BUCKET)
def __init__(self, parent, pixel_width, pixel_height, pixel_seq=None, FPS=50, left=None, right=None, top=None, bottom=None, width=None, height=None): super().__init__(parent, left=left, right=right, top=top, bottom=bottom, width=width, height=height) self.pixel_height = pixel_height self.pixel_width = pixel_width self.mgr = ImageManager(img_height = pixel_height, img_width = pixel_width, max_texture_size=1024) self.set_wait_img() if pixel_seq is not None: self.set_pixels(pixel_seq) self.img_index = 0 self.switch_time = 1/FPS self.countdown = self.switch_time
def set_image_properties(db_image): """ Sets image properties (width and height) in the database record db_image by reading the image file on disk. """ from image_manager import ImageManager (w, h) = ImageManager.get_image_dimensions(db_image.src) db_image.width = w db_image.height = h
def setUpClass(self): self.database_connector = database_connector.DatabaseConnector() self.item_manager = database_manager.ItemManager( self.database_connector) self.tag_manager = database_manager.TagManager(self.database_connector) aws_connector = AwsConnector(None) self.s3_resource = aws_connector.get_s3_resource() self.image_manager = ImageManager(self.s3_resource, self.BUCKET) self.product_manager = product_manager.ProductManager( self.item_manager, self.tag_manager, self.image_manager)
def get_labels(): decoded_image = base64.b64decode(request.data) image_manager = ImageManager() client = vision.Client() vision_service = VisionService(client, image_manager) labels = vision_service.find_features(decoded_image) style = StylesComparator(request.data) labels = style.filter_labels(labels) twin_response = style.find_twin(labels) style.save_new_image_and_labels(labels) return generate_response(labels, style, twin_response)
def predict(self, image_path): manager = ImageManager() manager.get_image_info([image_path], self.prediction_path) feature_columns = [tf.feature_column.numeric_column(k) for k in self.feature_name] classifier = tf.estimator.DNNClassifier( feature_columns=feature_columns, hidden_units=[10, 10], n_classes=10, model_dir='/tmp/image_model' ) predictions = classifier.predict(input_fn=(lambda: self.input_fn_predict())) for prediction in predictions: id = prediction['class_ids'] if prediction['probabilities'][id] >= 0.6: object_predict = self.find_object_by_id(id) return object_predict else: return None
def __init__(self, screen, initial_count=3, ct_pos=(0, 0), images_size=(32, 32)): self.screen = screen self.max_lives = initial_count self.lives = initial_count sheet_images = ImageManager('pacman-horiz.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (0, 64, 32, 32)], resize=images_size).all_images() life_image = sheet_images[-1] # get last image from the sprite sheet self.life_display = ImageRow(screen, life_image, initial_count, 'Lives', ct_pos)
class SimpleAnimation(pygame.sprite.Sprite): def __init__(self, screen, sprite_sheet, sheet_offsets, pos=(0, 0), resize=None, detail=None, frame_delay=None, flip=False): super().__init__() self.screen = screen if not resize: resize = (self.screen.get_height() // 10, self.screen.get_height() // 10) self.image_manager = ImageManager(sprite_sheet, sheet=True, pos_offsets=sheet_offsets, resize=resize, animation_delay=frame_delay) if flip: self.image_manager.flip() self.image, self.rect = self.image_manager.get_image() if detail: self.detail_piece = ImageManager(detail, sheet=True, pos_offsets=sheet_offsets, resize=resize).all_images()[0] if flip: self.image_manager.flip() self.image.blit(self.detail_piece, (0, 0)) else: self.detail_piece = None self.rect.centerx, self.rect.centery = pos def update(self): self.image = self.image_manager.next_image() if self.detail_piece: self.image.blit(self.detail_piece, (0, 0)) # combine detail def blit(self): self.screen.blit(self.image, self.rect)
def sense_and_act(self): """ Shouldn't actually affect the motors, but should request that a picture should be taken. :return: a """ Motors().stop() image = self.find_sensob(CameraSensob).update() im = ImageManager(image=image) im.dump_image('/') triple2 = [0] * 3 for x in range(im.xmax): for y in range(im.ymax): t = im.get_pixel(x, y) for i in range(len(triple2)): triple2[i] += t[i] t3 = [] for i in triple2: t3.append(i / (im.xmax * im.ymax)) over_50 = False for i in t3: if i > 50: over_50 = True if over_50: self.priority = 1 self.match_degree = 1 self.motor_recommendations = ["r"] else: self.priority = 1 self.match_degree = 1 self.bbcon.notifications.append("q") print("We found our item!") # self.find_sensob(UltrasonicSensob).value = 11.0 self.bbcon.notifications.remove("p")
def test1(data): decoded_image = data if not MOCK_LABELS: image_manager = ImageManager() client = vision.Client() vision_service = VisionService(client, image_manager) labels = vision_service.find_features(decoded_image) else: labels = ['clothing', 'puma', 'star wars'] print labels style = StylesComparator(data) res = style.create_output_for_user(style.image_stream, labels) return res["styles"]
def __init__(self, screen, maze): super().__init__() self.screen = screen self.radius = maze.block_size // 5 self.maze = maze self.sound_manager = SoundManager(sound_files=['pacman-pellet-eat.wav', 'pacman-fruit-eat.wav', 'pacman-killed.wav', 'pacman-portal.wav'], keys=['eat', 'fruit', 'dead', 'portal'], channel=PacMan.PAC_AUDIO_CHANNEL) self.horizontal_images = ImageManager('pacman-horiz.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (0, 64, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), reversible=True) self.vertical_images = ImageManager('pacman-vert.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (0, 64, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), reversible=True) self.death_images = ImageManager('pacman-death.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (0, 64, 32, 32), (32, 64, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=150, repeat=False) self.flip_status = {'use_horiz': True, 'h_flip': False, 'v_flip': False} self.spawn_info = self.maze.player_spawn[1] self.tile = self.maze.player_spawn[0] self.direction = None self.moving = False self.speed = maze.block_size // 7 self.image, self.rect = self.horizontal_images.get_image() self.rect.centerx, self.rect.centery = self.spawn_info # screen coordinates for spawn self.dead = False self.portal_controller = PortalController(screen, self, maze) # controller object for portal # Keyboard related events/actions/releases self.event_map = {pygame.KEYDOWN: self.perform_action, pygame.KEYUP: self.reset_direction} self.action_map = {pygame.K_UP: self.set_move_up, pygame.K_LEFT: self.set_move_left, pygame.K_DOWN: self.set_move_down, pygame.K_RIGHT: self.set_move_right, pygame.K_q: self.blue_portal, pygame.K_w: self.orange_portal}
class SimpleAnimation(pygame.sprite.Sprite): """A class for presenting a basic animation with little to no special logic""" def __init__(self, screen, sprite_sheet, sheet_offsets, pos=(0, 0), resize=None, detail=None, frame_delay=None, flip=False): super().__init__() self.screen = screen if not resize: resize = (self.screen.get_height() // 10, self.screen.get_height() // 10) self.image_manager = ImageManager(sprite_sheet, sheet=True, pos_offsets=sheet_offsets, resize=resize, animation_delay=frame_delay) if flip: self.image_manager.flip() self.image, self.rect = self.image_manager.get_image() if detail: self.detail_piece = ImageManager( detail, sheet=True, pos_offsets=sheet_offsets, resize=resize).all_images()[ 0] # grab first image in detail sheet if flip: self.image_manager.flip() self.image.blit(self.detail_piece, (0, 0)) # combine detail else: self.detail_piece = None self.rect.centerx, self.rect.centery = pos def update(self): """Update to the next image in the animation""" self.image = self.image_manager.next_image() if self.detail_piece: self.image.blit(self.detail_piece, (0, 0)) # combine detail def blit(self): """Blit the current image to the screen""" self.screen.blit(self.image, self.rect)
def main(): pygame.init() size = width, height = 800, 800 d_surf = pygame.display.set_mode(size) clock = pygame.time.Clock() car_id = 'CAR_ID' wheel_id = 'WHEEL_ID' lot_id = 'LOT_ID' car_start_pos = (400, 600) car_length = 90 car_width = 50 car_angle = 0 wheel_angle = 0 image_manager = ImageManager() image_manager.put(car_id, 'images/car.png', (64, 112)) image_manager.put(wheel_id, 'images/tyre.png', (8, 24)) image_manager.put(lot_id, 'images/lot.png', (800, 800)) car = Car(car_id, wheel_id, car_start_pos, car_length, car_width, car_angle, wheel_angle) car_controller = CarController(car) car_drawer = CarDrawer(image_manager) while True: delta_ms = clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type in (pygame.KEYUP, pygame.KEYDOWN): car_controller.handle_event(event) car_controller.update() car.update() d_surf.blit(image_manager.get(lot_id), (0, 0)) car_drawer.draw(d_surf, car) pygame.display.update()
class TestImageManager(unittest.TestCase): BUCKET = 'jf-test555-bucket' VECTOR_TO_UPLOAD = "images/1.eps" VECTOR_FILE_EXT = '.eps' VECTOR_SUBFOLDER = 'vector' PNG_FILE_EXT = '.png' PNG_SUBFOLDER = 'png' ITEM_ID_1 = "1e852a2d-35c2-409e-ac86-38224f5ac2d7" PNG_TO_UPLOAD = "images/test.png" def setUp(self): aws_connector = AwsConnector(None) self.s3_resource = aws_connector.get_s3_resource() self.s3_resource.create_bucket( Bucket=self.BUCKET, CreateBucketConfiguration={'LocationConstraint': 'eu-west-2'}, ) self.image_manager = ImageManager(self.s3_resource, self.BUCKET) def tearDown(self): bucket = self.s3_resource.Bucket(self.BUCKET) for key in bucket.objects.all(): key.delete() bucket.delete() def test_upload_vector_file(self): # act vector_path = self.image_manager.upload_vector_file( self.VECTOR_TO_UPLOAD, self.ITEM_ID_1, self.VECTOR_FILE_EXT, self.VECTOR_SUBFOLDER) # assert images = tuple(img.key for img in self.image_manager.bucket.objects.all()) self.assertIn(vector_path, images) def test_upload_png_file(self): # act png_path = self.image_manager.upload_png_file(self.VECTOR_TO_UPLOAD, self.ITEM_ID_1, self.PNG_FILE_EXT, self.PNG_SUBFOLDER) # assert images = tuple(img.key for img in self.image_manager.bucket.objects.all()) self.assertIn(png_path, images) def test_delete_file(self): # arrange vector_path = self.image_manager.upload_vector_file( self.VECTOR_TO_UPLOAD, self.ITEM_ID_1, self.VECTOR_FILE_EXT, self.VECTOR_SUBFOLDER) # act return_message = self.image_manager.delete_file(vector_path) # assert images = tuple(img.key for img in self.image_manager.bucket.objects.all()) self.assertTrue(return_message) self.assertNotIn(vector_path, images) def test_get_img_path(self): # act image_path = self.image_manager._get_img_path(self.ITEM_ID_1, self.VECTOR_FILE_EXT, self.VECTOR_SUBFOLDER) # assert self.assertTrue(image_path.endswith('.eps')) self.assertEqual( image_path, self.VECTOR_SUBFOLDER + "/" + self.ITEM_ID_1 + self.VECTOR_FILE_EXT) def test_get_file_ext(self): # act file_ext = self.image_manager.get_file_ext(self.VECTOR_TO_UPLOAD) # assert self.assertEqual(file_ext, self.VECTOR_FILE_EXT) def test_is_supported_format(self): # arrange formats = ('.eps', '.jpg') # act eps = self.image_manager.is_supported_format(self.VECTOR_TO_UPLOAD, formats) png = self.image_manager.is_supported_format(self.PNG_TO_UPLOAD, formats) # assert self.assertTrue(eps) self.assertFalse(png) def test_scale_vector(self): # arrange image_object = Image.open(self.VECTOR_TO_UPLOAD) min_width = 2000 # act vector = self.image_manager._scale_vector(image_object, min_width) # assert self.assertTrue(vector.width >= min_width) image_object.close() def test_get_png(self): # arrange vector_file = open(self.VECTOR_TO_UPLOAD, 'rb') # act png = self.image_manager._get_png(vector_file.read()) # assert self.assertIsInstance(png, bytes) vector_file.close() def test_calculate_brightness(self): # arrange with open(self.VECTOR_TO_UPLOAD, 'rb') as vector_file: vector_bytes = vector_file.read() # act brightness = self.image_manager.calculate_brightness(vector_bytes) # assert self.assertAlmostEqual(0.922497, brightness, 2)
import numpy import GA from PIL import Image from image_manager import ImageManager image = ImageManager() def cycle(size_of_population, total_population, mating_parents, colors, img_new, gen): fitness = GA.fitness_function(image.get_array(), total_population, image.use_inverse_img) parents = GA.select(total_population, fitness, mating_parents) offspring_crossover = GA.crossover_function( parents, (size_of_population[0] - parents.shape[0], image.weights, colors), image.get_array(), img_new, image.use_inverse_img) offspring_mutation = GA.mutation(offspring_crossover) total_population[0:parents.shape[0], :, :] = parents total_population[parents.shape[0]:, :, :] = offspring_mutation image.create(image.step_destination + str(gen), 0, total_population) def main(gens, number_of_solutions, mating_parents, colors): img_new = Image.new('RGB', (image.width, image.height), 'WHITE')
def search_and_scrape(self, search_terms_for_directories, target_number=800): for directory, search_terms in search_terms_for_directories.items(): directory = os.path.join(self.image_manager.base_directory, directory) if not os.path.exists(directory): os.makedirs(directory) for search_term in search_terms: self.search_for_items(search_term) n_images_scraped = 0 while n_images_scraped<target_number: images = self.find_images() if len(images) <= n_images_scraped: break self.scrape_images(images[n_images_scraped:], directory, search_term, start_index=n_images_scraped) n_images_scraped = len(images) if __name__=='main': base_directory = '~/tree-logic/tree_photos' manager = ImageManager(base_directory) search_terms_for_directories = { 'betula_papyrifera': ['betula papyrifera'] # ,'acer_macrophylum': ['bigleaf maple forest', 'acer macrophylum tree', 'bigleaf maple branches'] # ,'platanus_acerifolia': ['london plane tree', 'london plane flowers'] # ,'pseudotsuga_menziesii': ['pseudotsuga menziesii tree', 'douglas fir needles'] } search_and_scrape(search_terms_for_directories)
image_manager.get_image_info(image_list, 'Data/training_info.csv', index=True) def is_valid(image): read_test = cv2.imread(image) if read_test is None: return False return True if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--directory', type=str, default='Images', help=""" Path to the images folder. """) parser.add_argument('--path', type=str, default='Data/label_map.txt', help=""" Path to the label_map file. """) FLAGS = parser.parse_args() image_manager = ImageManager() main(image_manager)
def instance(): return ImageManager(tempfile.mkdtemp(prefix='hobo-sapiens__image-hash'))
def test_storage(instance: ImageManager): instance.image_hashes['asd'] = '123' assert instance.image_hashes['asd'] == '123' assert ImageManager( instance.image_hashes.directory).image_hashes['asd'] == '123'
from contract.config import config from contract.download_images import download_images as contract_download_images from contract.download_images import metadata as download_images_metadata from contract.listen_images import listen_images as contract_listen_images from contract.listen_images import metadata as listen_images_metadata from contract.get_contract import get_contract from contract.download_image_data import download_image_data from contract.download_image_data import metadata as download_images_data_metadata from contract.download_image_data import errors as download_images_data_errors from image_manager import ImageManager app = Flask(__name__) image_checker = NNModelChecker() image_manager = ImageManager(image_checker) @app.before_request def log_request_info(): app.logger.debug('Headers: %s', request.headers) app.logger.debug('Body: %s', request.get_data()) def load_image(data): nparr = np.fromstring(data, np.uint8) # decode image img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) img = Image.fromarray(img) return img
def __init__(self, x, y, width, height): images = ['apple.png', 'cherry.png', 'peach.png', 'strawberry.png'] fruit_image, _ = ImageManager(img=choice(images), resize=(width // 2, height // 2)).get_image() super(Fruit, self).__init__(x, y, width, height, fruit_image)
def __init__(self, screen, maze, target, spawn_info, sound_manager, ghost_file='ghost-red.png'): super().__init__() self.screen = screen self.maze = maze self.internal_map = maze.map_lines self.target = target self.sound_manager = sound_manager self.norm_images = ImageManager(ghost_file, sheet=True, pos_offsets=[(0, 0, 32, 32), (0, 32, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=250) self.blue_images = ImageManager('ghost-ppellet.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (0, 32, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=150) self.blue_warnings = ImageManager('ghost-ppellet-warn.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (0, 32, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=150) self.eyes = ImageManager('ghost-eyes.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), keys=['r', 'u', 'd', 'l']) self.score_font = sysfont.SysFont(None, 22) self.score_image = None self.image, self.rect = self.norm_images.get_image() self.curr_eye, _ = self.eyes.get_image( key='r') # default eye to looking right self.image.blit(self.curr_eye, (0, 0)) # combine eyes and body self.return_tile = spawn_info[0] # spawn tile self.return_path = None # path back to spawn tile self.return_delay = 1000 # 1 second delay from being eaten to returning self.eaten_time = None # timestamp for being eaten self.start_pos = spawn_info[1] self.reset_position() self.tile = spawn_info[0] self.direction = None self.last_position = None self.speed = maze.block_size / 10 self.state = { 'enabled': False, 'blue': False, 'return': False, 'speed_boost': False } self.blue_interval = 5000 # 5 second time limit for blue status self.blue_start = None # timestamp for blue status start self.blink = False self.last_blink = time.get_ticks() self.blink_interval = 250
class Ghost(Sprite): """Represents the enemies of PacMan which chase him around the maze""" GHOST_AUDIO_CHANNEL = 1 def __init__(self, screen, maze, target, spawn_info, sound_manager, ghost_file='ghost-red.png'): super().__init__() self.screen = screen self.maze = maze self.internal_map = maze.map_lines self.target = target self.sound_manager = sound_manager self.norm_images = ImageManager(ghost_file, sheet=True, pos_offsets=[(0, 0, 32, 32), (0, 32, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=250) self.blue_images = ImageManager('ghost-ppellet.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (0, 32, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=150) self.blue_warnings = ImageManager('ghost-ppellet-warn.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (0, 32, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=150) self.eyes = ImageManager('ghost-eyes.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), keys=['r', 'u', 'd', 'l']) self.score_font = sysfont.SysFont(None, 22) self.score_image = None self.image, self.rect = self.norm_images.get_image() self.curr_eye, _ = self.eyes.get_image( key='r') # default eye to looking right self.image.blit(self.curr_eye, (0, 0)) # combine eyes and body self.return_tile = spawn_info[0] # spawn tile self.return_path = None # path back to spawn tile self.return_delay = 1000 # 1 second delay from being eaten to returning self.eaten_time = None # timestamp for being eaten self.start_pos = spawn_info[1] self.reset_position() self.tile = spawn_info[0] self.direction = None self.last_position = None self.speed = maze.block_size / 10 self.state = { 'enabled': False, 'blue': False, 'return': False, 'speed_boost': False } self.blue_interval = 5000 # 5 second time limit for blue status self.blue_start = None # timestamp for blue status start self.blink = False self.last_blink = time.get_ticks() self.blink_interval = 250 @staticmethod def find_path(maze_map, start, target): """Determine a path in the maze map from the start to the target tile""" path = [] # path list tried = set() # set for faster membership checks done = False curr_tile = start while not done: if curr_tile == target: done = True # if at target tile, we are done else: options = [ # possible moves (curr_tile[0] + 1, curr_tile[1]), (curr_tile[0] - 1, curr_tile[1]), (curr_tile[0], curr_tile[1] + 1), (curr_tile[0], curr_tile[1] - 1) ] test = (abs(target[0] - start[0]), abs(target[1] - start[0])) prefer = test.index(max(test[0], test[1])) if prefer == 0: options.sort(key=lambda x: x[0], reverse=True) else: options.sort(key=lambda x: x[1], reverse=True) backtrack = True # assume we must backtrack for opt in options: try: if maze_map[opt[0]][opt[1]] not in ( 'x', ) and opt not in tried: backtrack = False # if we haven't tried this option before, and it's not blocked path.append( opt ) # then add to the path, and remember that it's been tried tried.add(opt) curr_tile = opt break except IndexError: continue if backtrack: # backtrack to the previous position in the path curr_tile = path.pop() return path def increase_speed(self): """Increase the ghost's speed""" self.state['speed_boost'] = True self.speed = self.maze.block_size def reset_speed(self): """Reset the ghost's speed""" self.state['speed_boost'] = False self.speed = self.maze.block_size def reset_position(self): """Hard reset the ghost position back to its original location""" self.rect.left, self.rect.top = self.start_pos def get_dir_from_path(self): """Return a new direction based on the next step in the current path""" try: next_step = self.return_path[0] if next_step[0] > self.tile[0]: return 'd' # move up next if next_step[0] < self.tile[0]: return 'u' # move down next if next_step[1] > self.tile[1]: return 'r' # move right next if next_step[1] < self.tile[1]: return 'l' # move left next except IndexError as ie: print('Error while trying to get new path direction', ie) return None def set_eaten(self): """Begin the ghost's sequence for having been eaten by PacMan""" self.state['return'] = True self.state['blue'] = False self.tile = (self.get_nearest_row(), self.get_nearest_col()) self.return_path = Ghost.find_path(self.internal_map, self.tile, self.return_tile) self.direction = self.get_dir_from_path() self.image = self.score_font.render('200', True, (255, 255, 255)) self.eaten_time = time.get_ticks() def get_direction_options(self): """Check if the ghost is blocked by any maze barriers and return all directions possible to move in""" tests = { 'u': self.rect.move((0, -self.speed)), 'l': self.rect.move((-self.speed, 0)), 'd': self.rect.move((0, self.speed)), 'r': self.rect.move((self.speed, 0)) } remove = [] original_pos = self.rect for d, t in tests.items(): self.rect = t # temporarily move self if spritecollideany(self, self.maze.maze_blocks) and d not in remove: remove.append( d) # if collision, mark this direction for removal for rem in remove: del tests[rem] self.rect = original_pos # reset position return list(tests.keys()) def begin_blue_state(self): """Switch the ghost to its blue state""" if not self.state['return']: self.state['blue'] = True self.image, _ = self.blue_images.get_image() self.blue_start = time.get_ticks() self.sound_manager.stop() self.sound_manager.play_loop('blue') def change_eyes(self, look_direction): """Change the ghosts' eyes to look in the given direction""" self.image, _ = self.norm_images.get_image() self.curr_eye, _ = self.eyes.get_image(key=look_direction) self.image.blit(self.curr_eye, (0, 0)) # combine eyes and body def get_chase_direction(self, options): """Figure out a new direction to chase in based on the target and walls""" pick_direction = None target_pos = (self.target.rect.centerx, self.target.rect.centery) test = (abs(target_pos[0]), abs(target_pos[1])) prefer = test.index(max(test[0], test[1])) if prefer == 0: # x direction if target_pos[prefer] < self.rect.centerx: # to the left pick_direction = 'l' elif target_pos[prefer] > self.rect.centerx: # to the right pick_direction = 'r' else: # y direction if target_pos[prefer] < self.rect.centery: # upward pick_direction = 'u' elif target_pos[prefer] > self.rect.centery: # downward pick_direction = 'd' if pick_direction not in options: # desired direction not available if 'u' in options: # pick a direction that is available return 'u' if 'l' in options: return 'l' if 'r' in options: return 'r' if 'd' in options: return 'd' else: # desired direction available, return it return pick_direction def get_flee_direction(self, options): """Figure out a new direction to flee in based on the target and walls""" pick_direction = None target_pos = (self.target.rect.centerx, self.target.rect.centery) test = (abs(target_pos[0]), abs(target_pos[1])) prefer = test.index(max(test[0], test[1])) if prefer == 0: # x direction if target_pos[ prefer] < self.rect.centerx: # to the left, so move right pick_direction = 'r' elif target_pos[ prefer] > self.rect.centerx: # to the right, so move left pick_direction = 'l' else: # y direction if target_pos[prefer] < self.rect.centery: # upward, so move down pick_direction = 'd' elif target_pos[prefer] > self.rect.centery: # downward, so move up pick_direction = 'u' if pick_direction not in options: # desired direction not available if 'u' in options: # pick a direction that is available return 'u' if 'l' in options: return 'l' if 'd' in options: return 'd' if 'r' in options: return 'r' else: # desired direction available, return it return pick_direction def get_nearest_col(self): """Get the current column location on the maze map""" return (self.rect.left - (self.screen.get_width() // 5)) // self.maze.block_size def get_nearest_row(self): """Get the current row location on the maze map""" return (self.rect.top - (self.screen.get_height() // 12)) // self.maze.block_size def is_at_intersection(self): """Return True if the ghost is at an intersection, False if not""" directions = 0 self.tile = (self.get_nearest_row(), self.get_nearest_col()) if self.internal_map[self.tile[0] - 1][self.tile[1]] not in ('x', ): directions += 1 if self.internal_map[self.tile[0] + 1][self.tile[1]] not in ('x', ): directions += 1 if self.internal_map[self.tile[0]][self.tile[1] - 1] not in ('x', ): directions += 1 if self.internal_map[self.tile[0]][self.tile[1] + 1] not in ('x', ): directions += 1 return True if directions > 2 else False def enable(self): """Initialize ghost AI with the first available direction""" options = self.get_direction_options() self.direction = options[0] self.state['enabled'] = True self.sound_manager.play_loop('std') def disable(self): """Disable the ghost AI""" self.direction = None # remove direction self.state['enabled'] = False # reset states self.state['return'] = False self.return_path = None # remove path if self.state['blue']: self.stop_blue_state(resume_audio=False) self.image, _ = self.norm_images.get_image() # reset image self.sound_manager.stop() def stop_blue_state(self, resume_audio=True): """Revert back from blue state""" self.state['blue'] = False self.state['return'] = False self.image, _ = self.norm_images.get_image() self.sound_manager.stop() if resume_audio: self.sound_manager.play_loop('std') def check_path_tile(self): """Check if the ghost has reached the tile it's looking for in the path, and if so remove it from the path""" self.tile = (self.get_nearest_row(), self.get_nearest_col()) if self.return_path and self.tile == self.return_path[0]: del self.return_path[0] if not len(self.return_path) > 0: return '*' # signal that the path is complete return None def update_normal(self): """Update logic for a normal state""" options = self.get_direction_options() if self.is_at_intersection() or self.last_position == ( self.rect.centerx, self.rect.centery): self.direction = self.get_chase_direction(options) if self.direction == 'u' and 'u' in options: self.rect.centery -= self.speed elif self.direction == 'l' and 'l' in options: self.rect.centerx -= self.speed elif self.direction == 'd' and 'd' in options: self.rect.centery += self.speed elif self.direction == 'r' and 'r' in options: self.rect.centerx += self.speed self.change_eyes(self.direction or 'r') # default look direction to right self.image = self.norm_images.next_image() def update_blue(self): """Update logic for blue state""" self.image = self.blue_images.next_image() options = self.get_direction_options() if self.is_at_intersection() or self.last_position == ( self.rect.centerx, self.rect.centery): self.direction = self.get_flee_direction(options) # print(self.internal_map[self.tile[0]][self.tile[1]]) if self.direction == 'u' and 'u' in options: self.rect.centery -= self.speed elif self.direction == 'l' and 'l' in options: self.rect.centerx -= self.speed elif self.direction == 'd' and 'd' in options: self.rect.centery += self.speed elif self.direction == 'r' and 'r' in options: self.rect.centerx += self.speed if abs(self.blue_start - time.get_ticks()) > self.blue_interval: self.stop_blue_state() elif abs(self.blue_start - time.get_ticks()) > int( self.blue_interval * 0.5): if self.blink: self.image = self.blue_warnings.next_image() self.blink = False self.last_blink = time.get_ticks() elif abs(self.last_blink - time.get_ticks()) > self.blink_interval: self.blink = True def update_return(self): """Update logic for when returning to ghost spawn""" if abs(self.eaten_time - time.get_ticks()) > self.return_delay: self.image, _ = self.eyes.get_image(key=self.direction) test = self.check_path_tile() if test == '*': self.state['return'] = False self.direction = self.get_chase_direction( self.get_direction_options()) else: self.direction = self.get_dir_from_path() if self.direction == 'u': self.rect.centery -= self.speed elif self.direction == 'l': self.rect.centerx -= self.speed elif self.direction == 'd': self.rect.centery += self.speed elif self.direction == 'r': self.rect.centerx += self.speed def update(self): """Update the ghost position""" if self.state['enabled']: if not self.state['blue'] and not self.state['return']: self.update_normal() elif self.state['blue']: self.update_blue() elif self.state['return']: self.update_return() self.last_position = (self.rect.centerx, self.rect.centery) def blit(self): """Blit ghost image to the screen""" self.screen.blit(self.image, self.rect)
import cv2 import numpy as np import matplotlib # need to specify matplot lib to use "tkAgg before pyplot is imported" matplotlib.use("TkAgg") import matplotlib.pyplot as plt from image_manager import ImageManager from color_converter import ColorConverter from gui import GUI # Color is strange because OpenCV us BGR for color and matplotlib uses RGB # Need to convert to RGB before plot with matplotlib manager = ImageManager() # img = manager.upload("john.png") # RGB_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) gui = GUI(manager) # print(img[0]) # print(RGB_image[0]) # def make_grayscale(img): # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # probably want to generate the figsize based off of pic dimensions # plt.figure(figsize=(5, 6)), plt.imshow(RGB_image) #grey image(must specify a gray color map in imshow) # manager.make_grayscale() # manager.convert('to_grayscale') # reds = manager.get_reds()
class PacMan(pygame.sprite.Sprite): """Represents the player character 'PacMan' and its related logic/control""" PAC_YELLOW = (255, 255, 0) PAC_AUDIO_CHANNEL = 0 def __init__(self, screen, maze): super().__init__() self.screen = screen self.radius = maze.block_size self.maze = maze self.sound_manager = SoundManager(sound_files=['pacman-pellet-eat.wav', 'Eaten1.wav', 'Eaten4.wav'], keys=['eat', 'fruit', 'dead'], channel=PacMan.PAC_AUDIO_CHANNEL) self.horizontal_images = ImageManager('pacman-horiz.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (0, 64, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), reversible=True) self.vertical_images = ImageManager('pacman-vert.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (0, 64, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), reversible=True) self.death_images = ImageManager('pacman-death.png', sheet=True, pos_offsets=[(0, 0, 32, 32), (32, 0, 32, 32), (0, 32, 32, 32), (32, 32, 32, 32), (0, 64, 32, 32), (32, 64, 32, 32)], resize=(self.maze.block_size, self.maze.block_size), animation_delay=150, repeat=False) self.flip_status = {'use_horiz': True, 'h_flip': False, 'v_flip': False} self.spawn_info = self.maze.player_spawn[1] self.tile = self.maze.player_spawn[0] self.direction = None self.moving = False self.speed = maze.block_size // 7 self.image, self.rect = self.horizontal_images.get_image() self.rect.centerx, self.rect.centery = self.spawn_info # screen coordinates for spawn self.dead = False # Keyboard related events/actions/releases self.event_map = {pygame.KEYDOWN: self.perform_action, pygame.KEYUP: self.reset_direction} self.action_map = {pygame.K_UP: self.set_move_up, pygame.K_LEFT: self.set_move_left, pygame.K_DOWN: self.set_move_down, pygame.K_RIGHT: self.set_move_right, } def set_death(self): """Set the death flag for PacMan and begin the death animation""" self.sound_manager.play('dead') self.dead = True self.image, _ = self.death_images.get_image() def revive(self): """Set dead to False and give PacMan a default image""" self.dead = False self.image, _ = self.horizontal_images.get_image() self.death_images.image_index = 0 def reset_position(self): """Reset position back to pre-define spawn location""" self.rect.centerx, self.rect.centery = self.spawn_info # screen coordinates for spawn def reset_direction(self, event): """Reset the movement direction if key-up on movement keys""" if event.key in (pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT): self.moving = False def perform_action(self, event): """Change direction based on the event key""" if event.key in self.action_map: self.action_map[event.key]() def set_move_up(self): """Set move direction up""" if self.direction != 'u': self.direction = 'u' if self.flip_status['v_flip']: self.vertical_images.flip(False, True) self.flip_status['v_flip'] = False self.flip_status['use_horiz'] = False self.moving = True def set_move_left(self): """Set move direction left""" if self.direction != 'l': self.direction = 'l' if not self.flip_status['h_flip']: self.horizontal_images.flip() self.flip_status['h_flip'] = True self.flip_status['use_horiz'] = True self.moving = True def set_move_down(self): """Set move direction down""" if self.direction != 'd': self.direction = 'd' if not self.flip_status['v_flip']: self.vertical_images.flip(x_bool=False, y_bool=True) self.flip_status['v_flip'] = True self.flip_status['use_horiz'] = False self.moving = True def set_move_right(self): """Set move direction to right""" if self.direction != 'r': self.direction = 'r' if self.flip_status['h_flip']: self.horizontal_images.flip() self.flip_status['h_flip'] = False self.flip_status['use_horiz'] = True self.moving = True def get_nearest_col(self): """Get the current column location on the maze map""" return (self.rect.x - (self.screen.get_width() // 5)) // self.maze.block_size def get_nearest_row(self): """Get the current row location on the maze map""" return (self.rect.y - (self.screen.get_height() // 12)) // self.maze.block_size def is_blocked(self): """Check if PacMan is blocked by any maze barriers, return True if blocked, False if clear""" result = False if self.direction is not None and self.moving: original_pos = self.rect if self.direction == 'u': test = self.rect.move((0, -self.speed)) elif self.direction == 'l': test = self.rect.move((-self.speed, 0)) elif self.direction == 'd': test = self.rect.move((0, self.speed)) else: test = self.rect.move((self.speed, 0)) self.rect = test # temporarily move self # if any collision, result = True if pygame.sprite.spritecollideany(self, self.maze.maze_blocks): result = True elif pygame.sprite.spritecollideany(self, self.maze.shield_blocks): result = True self.rect = original_pos # reset position return result def update(self): """Update PacMan's position in the maze if moving, and if not blocked""" if not self.dead: if self.direction and self.moving: if self.flip_status['use_horiz']: self.image = self.horizontal_images.next_image() else: self.image = self.vertical_images.next_image() if not self.is_blocked(): if self.direction == 'u': self.rect.centery -= self.speed elif self.direction == 'l': self.rect.centerx -= self.speed elif self.direction == 'd': self.rect.centery += self.speed elif self.direction == 'r': self.rect.centerx += self.speed self.tile = (self.get_nearest_row(), self.get_nearest_col()) else: self.image = self.death_images.next_image() def blit(self): """Blit the PacMan sprite to the screen""" self.screen.blit(self.image, self.rect) def eat(self): """Eat pellets from the maze and return the score accumulated""" score = 0 fruit_count = 0 power = None collision = pygame.sprite.spritecollideany(self, self.maze.pellets) if collision: collision.kill() score += 10 self.sound_manager.play('eat') collision = pygame.sprite.spritecollideany(self, self.maze.fruits) if collision: collision.kill() score += 20 fruit_count += 1 self.sound_manager.play('fruit') collision = pygame.sprite.spritecollideany(self, self.maze.power_pellets) if collision: collision.kill() score += 20 power = True self.sound_manager.play('eat') return score, fruit_count, power
from image_manager import ImageManager from sinogram_generator import SinogramGenerator from sklearn.metrics import mean_squared_error def error(tab1,tab2): return mean_squared_error(tab1, tab2) import numpy as np imageManager = ImageManager() img = imageManager.readImage('Shepp_logan.jpg') wyniki = [] dane = [] for i in range(10,15,10): print('-------' + str(i)) sinogramGenrator = SinogramGenerator(img,300,240,1) # print("Min: {}, Max: {}".format(np.min(img), np.max(img))) # sinogram = sinogramGenrator.generate(img) # imageManager.showImage(sinogram, True, 'sinogram_bez_filtra') # imageManager.showImage(sinogramGenrator.revert(), True, 'reverted_bez_filtra') sinogramGenrator.withFilter = True sinogram = sinogramGenrator.generate(img) imageManager.showImage(sinogram, True, 'sinogram_z_filtrem') x = sinogramGenrator.revert() imageManager.showImage(x, True, 'reverted_z_fitrem') wyniki.append(error(x, img)) dane.append(i) print(wyniki) print(dane) print(wyniki)