コード例 #1
0
ファイル: sheet_reader.py プロジェクト: thhuang/SheetMusicAI
 def detect_natural_sign(self, natural_sign_dir: str) -> None:
     natural_sign_imgs = load_imgs(natural_sign_dir)
     detector = Detector(self, natural_sign_imgs,
                         self._threshold_natural_sign)
     self._natural_sign_boxes = detector.detect()
     draw_boxes('natural_sign_boxes_img.png', self._img_rgb,
                self._natural_sign_boxes)
コード例 #2
0
ファイル: sheet_reader.py プロジェクト: thhuang/SheetMusicAI
 def detect_quarter_note(self, quarter_note_dir: str) -> None:
     quarter_note_imgs = load_imgs(quarter_note_dir)
     detector = Detector(self, quarter_note_imgs,
                         self._threshold_quarter_note)
     self._quarter_note_boxes = detector.detect()
     draw_boxes('quarter_note_boxes_img.png', self._img_rgb,
                self._quarter_note_boxes)
コード例 #3
0
def train_generator(img_paths,
                    batch_size,
                    model,
                    y_true_sty,
                    shuffle=True,
                    epochs=None):

    n_samples = len(img_paths)
    indices = list(range(n_samples))
    steps_per_epoch = math.ceil(n_samples / batch_size)
    img_paths = np.array(img_paths)
    cnt_epoch = 0
    while True:
        cnt_epoch += 1
        if shuffle:
            np.random.shuffle(indices)
        for i in range(steps_per_epoch):
            start = batch_size * i
            end = batch_size * (i + 1)
            X = load_imgs(img_paths[indices[start:end]], input_size)
            batch_size_act = X.shape[0]
            y_true_sty_t = [
                np.repeat(feat, batch_size_act, axis=0) for feat in y_true_sty
            ]
            # exrtract content
            y_true_con = model.predict(X)
            yield (X, y_true_sty_t + [y_true_con])

        if epochs is not None:
            if cnt_epoch >= epochs:
                raise StopIteration
コード例 #4
0
	def __init__(self, x, y, windowWidth, strength):
		img_lists = {
			"Ridle": ["boss_idle_1", "boss_idle_2"],
			"Odmg": ["boss_dmg"],
			"Oaa1": ["boss_atkranged1_1", "boss_atkranged1_2"],
			"Oaa2": ["boss_atkranged2_1", "boss_atkranged2_2"],
			"Oaa3": ["boss_atkranged3_1", "boss_atkranged3_2"],
			"D": ["boss_dead", "boss_dead"],
		}
		imgpath = "Images/Boss"
		imagesDemon = load_imgs(img_lists, imgpath, scale=4)
		atkList = [
			Atk(
				"feu", 1.5, 32, 16, load_imgs({"idle": ["fire_1", "fire_2"]}, imgpath),
				10, 3, -1, 0, 6, 0, 3000
			),
			Atk(
				"vent", 2, 32, 16, load_imgs({"idle": ["wind_1", "wind_1"]}, imgpath),
				5, 6, -8, 0, 10, 0, 3000
			),
			Atk(
				"glace", 2, 32, 16, load_imgs({"idle": ["wind_1", "wind_1"]}, imgpath),
				18, 2, 5, 0.8, 0, 0, 2000
			)
		]
		Mob.__init__(self, x, y, 256, 96, imagesDemon, 0.01, 0.008, 2, 3, windowWidth, 250*strength, atkList)
		self.states["Oaa1Right"] = 200
		self.states["Oaa1Left"] = 200
		self.states["Oaa2Right"] = 200
		self.states["Oaa2Left"] = 200
		self.states["Oaa3Right"] = 200
		self.states["Oaa3Left"] = 200
		self.states["DRight"] = 200
		self.states["DLeft"] = 200
		self.strength = strength
		self.spellMax = int(7*strength)
		self.spellCount = 0
		self.flee_x = 0
		self.flee_y = 0
		self.min_x = 5.0*windowWidth/10.0
		self.max_x = windowWidth-self.rect.width
		self.max_y = y + 50
		self.min_y = y
		self.flee_x = (pygame.time.get_ticks()%(self.max_x-self.min_x))+self.min_x
		self.flee_y = (pygame.time.get_ticks()%(self.max_y-self.min_y))+self.min_y
		self.flee_set = True
コード例 #5
0
ファイル: sheet_reader.py プロジェクト: thhuang/SheetMusicAI
 def detect_staff(self, staff_dir: str) -> None:
     staff_imgs = load_imgs(staff_dir)
     detector = Detector(self,
                         staff_imgs,
                         self._threshold_staff,
                         is_staff=True)
     self._staff_boxes = detector.detect()
     self._staff_boxes.sort(key=lambda box: box.y)
     draw_boxes('staff_boxes_img.png', self._img_rgb, self._staff_boxes)
コード例 #6
0
 def __init__(self, x, y, windowWidth, strength):
     img_lists = {
         "Ridle": ["c_fly_1", "c_fly_2"],
         "Rmove": ["c_fly_1", "c_fly_2"],
         "Odmg": ["c_dmg"]
     }
     imgpath = "Images/Corbeau"
     imagesCorbeau = load_imgs(img_lists, imgpath)
     atkList = [
         Atk("shuriken", 2, 16, 16,
             load_imgs({"idle": ["shuriken"]}, imgpath), 2, 3, 1, 0.3, 0, 2,
             2000)
     ]
     Mob.__init__(self, x, y, 32, 32, imagesCorbeau, 0.01, 1, 1, 8,
                  windowWidth, 10 * strength, atkList)
     self.strength = strength
     self.min_y = (pygame.time.get_ticks() % 100) + 300
     self.left = True
     self.right = False
コード例 #7
0
 def __init__(self, x, y, windowWidth, strength):
     img_lists = {
         "Ridle": ["a_idle"],
         "Odmg": ["a_dmg_2"],
         "Oaa1": ["a_atk_1", "a_atk_2", "a_atk_3", "a_atk_4"],
         "Rmove": ["a_move_1", "a_move_2", "a_move_3"],
     }
     imgpath = "Images/Archer"
     imagesArcher = load_imgs(img_lists, imgpath)
     atkList = [
         Atk("fleche", 3, 32, 16, load_imgs({"idle": ["Fleche"]}, imgpath),
             2, 3, -1, 0.05, 15, -1, 3000)
     ]
     Mob.__init__(self, x, y, 64, 64, imagesArcher, 0.2, 1, 5, 7,
                  windowWidth, 20 * strength, atkList)
     self.strength = strength
     self.arrowMax = 3 + int(strength)
     self.arrowCount = 0
     self.flee_x = 0
     self.flee_set = False
コード例 #8
0
 def __init__(self, x, y, windowWidth, strength):
     img_lists = {
         "Ridle": ["s_idle_1", "s_idle_2"],
         "Rmove": ["s_move_0", "s_move_1", "s_move_0", "s_move_1"],
         "Oaa1": ["s_atk_1", "s_atk_2", "s_atk_3", "s_atk_3"],
         "Odmg": ["s_dmg_2"],
     }
     imgpath = "Images/Samurai"
     imagesSamurai = load_imgs(img_lists, imgpath)
     atkList = [
         Atk("sabre", 4, 96, 96,
             load_imgs({"idle": ["particle_sam"]}, imgpath), 10, 10, -4, 0,
             4, 0, 400)
     ]
     Mob.__init__(self, x, y, 96, 96, imagesSamurai, 0.5, 1, 4, 3,
                  windowWidth, 40 * strength, atkList)
     self.states["Oaa1Right"] = 100
     self.states["Oaa1Left"] = 100
     self.strength = strength
     self.areaWidth = 200
コード例 #9
0
 def __init__(self, x, y, windowWidth, strength):
     img_lists = {
         "Ridle": ["n_idle_1", "n_idle_2"],
         "Rmove": ["n_aa_1", "n_mv", "n_aa_1", "n_mv"],
         "Fjump": ["n_jp"],
         "Oaa1": ["n_aa_1", "n_aa_2", "n_aa_3", "n_aa_4"],
         "Odmg": ["n_hurt"],
     }
     imgpath = "Images/Ninja"
     imagesNinja = load_imgs(img_lists, imgpath)
     atkList = [
         Atk("sabre", 2.5, 64, 32,
             load_imgs({"idle": ["particlehit"]}, "Images/Blanchon", 1), 10,
             10, -1, 0, 0, 0, 400)
     ]
     Mob.__init__(self, x, y, 64, 64, imagesNinja, 0.3, 2, 8, 8,
                  windowWidth, 30 * strength, atkList)
     self.strength = strength
     self.areaWidth = 250
     self.left = False
     self.right = False
コード例 #10
0
def run():
    pygame.init()

    screen = pygame.display.set_mode((1280, 720), 0, 32)
    statesBlanchon = {
        "RidleRight": 500,
        "RidleLeft": 500,
        "RmoveLeft": 100,
        "RmoveRight": 100,
        "Oaa1Right": 75,
        "Oaa1Left": 75,
        "FcrouchLeft": 150,
        "FcrouchRight": 150
    }

    imagesBlanchonList = {
        "Ridle": ["b_idle_1", "b_idle_2"],
        "Rmove": ["b_move_0", "b_move_1", "b_move_2", "b_move_1"],
        "Ffall": ["b_jumpdown_1", "b_jumpdown_2"],
        "Fcrouch": ["b_crouch_1", "b_crouch_2"],
        "Rslide": ["b_slide"],
        "Fjump": ["b_jumpup_1", "b_jumpup_2", "b_jumpup_3"],
        "Oaa1": ["b_aa1_1", "b_aa1_2", "b_aa1_3", "b_aa1_3"],
        "Oaa2":
        ["b_aa2_1", "b_aa2_2", "b_aa2_3", "b_aa2_4", "b_aa2_5", "b_aa2_5"],
        "Oaa3": [
            "b_aa3_1", "b_aa3_2", "b_aa3_3", "b_aa3_4", "b_aa3_5", "b_aa3_6",
            "b_aa3_6", "b_aa3_6"
        ],
        "Oaaa": ["b_aa2_2", "b_atkjumpdown", "b_atkjumpdown"],
        "Odmg": ["b_dmg_2", "b_dmg_2"],
        "D": ["b_gameover", "b_gameover"],
    }
    path = "Images/Blanchon"
    imagesBlanchon = load_imgs(imagesBlanchonList, path, scale=8)

    blanchon = AnimItem(imagesBlanchon, statesBlanchon, 500, 384)
    anim = [blanchon]
    jouer = ["Jouer"]
    title = TitleItem("title", 500, 25)
    input_name = NameMenu(screen, jouer)
    credit_menu = CreditMenu(screen)
    leaderboard_menu = LeaderboardMenu(screen)
    menu = [input_name, credit_menu, leaderboard_menu]

    menu_items = ("DifNorm", "DifHard", "Tutoriel", "HighScores", "Credits",
                  "Quitter")

    pygame.display.set_caption('Menu')

    gm = GameMenu(screen, menu_items, menu, title, anim)
    gm.run()
コード例 #11
0
ファイル: evaluator.py プロジェクト: KUR-creative/unet
def eval_and_save_result(dataset_dir, model_path, eval_result_dirpath,
                         eval_summary_name='eval_summary.yml',
                         files_2b_copied=None,
                         num_filters=64,num_maxpool=4,
                         modulo=16):
    '''
    '''
    #---- load ----
    train_dir = os.path.join(dataset_dir,'train')
    valid_dir = os.path.join(dataset_dir,'valid')
    test_dir = os.path.join(dataset_dir,'test')
    train_img_dir = os.path.join(train_dir,'image')
    train_label_dir = os.path.join(train_dir,'label')
    valid_img_dir = os.path.join(valid_dir,'image')
    valid_label_dir = os.path.join(valid_dir,'label')
    test_img_dir = os.path.join(test_dir, 'image')
    test_label_dir = os.path.join(test_dir, 'label')
    assert_exists(train_img_dir)
    assert_exists(train_label_dir)
    assert_exists(valid_img_dir)
    assert_exists(valid_label_dir)
    assert_exists(test_img_dir)
    assert_exists(test_label_dir)
    train_inputs = list(load_imgs(train_img_dir))
    train_answers = list(load_imgs(train_label_dir))
    valid_inputs = list(load_imgs(valid_img_dir))
    valid_answers = list(load_imgs(valid_label_dir))
    test_inputs = list(load_imgs(test_img_dir))
    test_answers = list(load_imgs(test_label_dir))

    #---- eval ----
    segnet = model.unet(model_path, (None,None,1), 
                        num_filters=num_filters, num_maxpool=num_maxpool)
    train_iou_arr, train_result_tuples = evaluate(segnet, train_inputs, train_answers, modulo)
    valid_iou_arr, valid_result_tuples = evaluate(segnet, valid_inputs, valid_answers, modulo)
    test_iou_arr, test_result_tuples = evaluate(segnet, test_inputs, test_answers, modulo)
    K.clear_session()
    print('Evaluation completed!')

    #---- save ----
    summary_path, train_path, valid_path, test_path = make_eval_directory(eval_result_dirpath,
                                                                          eval_summary_name)
    save_eval_summary(summary_path, train_iou_arr, valid_iou_arr, test_iou_arr)
    print('Evaluation summary is saved!')

    save_img_tuples(train_result_tuples, train_path)
    save_img_tuples(valid_result_tuples, valid_path)
    save_img_tuples(test_result_tuples, test_path)
    print('Evaluation result images are saved!')

    if files_2b_copied is None:
        files_2b_copied = [model_path]
    else:
        files_2b_copied.append(model_path)

    for file_path in files_2b_copied:
        file_name = os.path.basename(file_path)
        shutil.copyfile(file_path, os.path.join(eval_result_dirpath, file_name))
        print("file '%s' is copyed into '%s'" % (file_name,eval_result_dirpath))
コード例 #12
0
    def __init__(self, x, y, windowWidth, strength):
        img_lists = {
            "Ridle": ["m_idle_1", "m_idle_2"],
            "Odmg": ["m_dmg"],
            "Oaa1": ["m_atk1_1", "m_atk1_2"],
            "Oaa2": ["m_atk2_1", "m_atk2_2"],
            "Oaa3": ["m_atk3_3", "m_atk3_2", "m_atk3_3", "m_atk3_4"],
            "D": ["m_dead_1", "m_dead_2"],
        }
        imgpath = "Images/Moine"
        imagesMoine = load_imgs(img_lists, imgpath)
        atkList = [
            Atk(
                "violet", 2.5, 32, 16,
                load_imgs({"idle": ["m_atkranged1_1", "m_atkranged1_2"]},
                          imgpath), 7, -12, -5, 0, 6, 0, 3000),
            Atk(
                "lazer", 3, 32, 16,
                load_imgs({"idle": ["m_atkranged2_1", "m_atkranged2_2"]},
                          imgpath), 4, 3, -1, 0, 12, 0, 3000),
            Atk(
                "orbe", 0.1, 32, 32,
                load_imgs({"idle": ["m_atkranged3_1", "m_atkranged3_2"]},
                          imgpath), 10, 3, -3, 0.1, 2, -3, 4000)
        ]

        Mob.__init__(self, x, y, 64, 64, imagesMoine, 0.2, 0.5, 2, 4,
                     windowWidth, 130 * strength, atkList)
        self.states["Oaa1Right"] = 200
        self.states["Oaa1Left"] = 200
        self.states["Oaa2Right"] = 200
        self.states["Oaa2Left"] = 200
        self.states["Oaa3Right"] = 150
        self.states["Oaa3Left"] = 150
        self.states["DRight"] = 200
        self.states["DLeft"] = 200
        self.areaWidth = 350
        self.stockOrb = 4
        self.strength = strength
コード例 #13
0
        logger_file = open(logger_path, 'w')
        print('epoch,loss_D,loss_G', file=logger_file)
  
    '''
    imgs1 = load_imgs(img_dir1)
    idx, tags1 = load_anime_tags(tag_file1)
    imgs2 = load_imgs(img_dir2)
    tags2 = load_extra_tags(tag_file2)
    
    imgs = np.concatenate((imgs1[idx], imgs2), axis=0)
    tags = np.concatenate((tags1, tags2), axis=0)
    del imgs1, imgs2, tags1, tags2, idx
    
    ''' 
    ### only extra data ###
    imgs = load_imgs(img_dir2)
    tags = load_extra_tags(tag_file2)
    
    '''
    ### for img flip ###
    flip_imgs = np.array([ np.fliplr(img) for img in imgs ])
    imgs = np.concatenate((imgs, flip_imgs), axis=0)
    tags = np.tile(tags, (2, 1))
    '''
    imgs = torch.FloatTensor(imgs).permute(0, 3, 1, 2)
    

    conds = torch.zeros((imgs.size(0), num_hair + num_eyes))
    for i, tag in enumerate(tags): conds[(i, i), (hair_dict[tag[0]], eyes_dict[tag[1]] + num_hair)] = 1.
    
    dataset = TensorDataset(imgs, conds)
コード例 #14
0
def main(self, name, difHard):
    from Model.class_Menu import DieMenu

    if name == "":
        name = "nom par defaut"

    pygame.init()

    WIDTH = 1280
    HEIGHT = 720
    fenetre = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)

    fond_e = pygame.transform.scale(
        pygame.image.load(
            "Images/Background/niveauRecurciforce.png").convert(),
        (WIDTH, HEIGHT))

    blanchonAa1 = pygame.image.load("Images/Spell/aa1.png").convert()
    blanchonAa2 = pygame.image.load("Images/Spell/aa2.png").convert()
    blanchonAa3 = pygame.image.load("Images/Spell/aa3.png").convert()
    blanchonAaMidAir = pygame.image.load("Images/Spell/aaMidAir.png").convert()
    blanchonVector = pygame.image.load("Images/Spell/vector.png").convert()

    imagesBlanchonList = {
        "Ridle": ["b_idle_1", "b_idle_2"],
        "Rmove": ["b_move_0", "b_move_1", "b_move_2", "b_move_1"],
        "Ffall": ["b_jumpdown_1", "b_jumpdown_2"],
        "Fcrouch": ["b_crouch_1", "b_crouch_2"],
        "Rslide": ["b_slide"],
        "Fjump": ["b_jumpup_1", "b_jumpup_2", "b_jumpup_3"],
        "Oaa1": ["b_aa1_1", "b_aa1_2", "b_aa1_3", "b_aa1_3"],
        "Oaa2":
        ["b_aa2_1", "b_aa2_2", "b_aa2_3", "b_aa2_4", "b_aa2_5", "b_aa2_5"],
        "Oaa3": [
            "b_aa3_1", "b_aa3_2", "b_aa3_3", "b_aa3_4", "b_aa3_5", "b_aa3_6",
            "b_aa3_6", "b_aa3_6"
        ],
        "Oaaa": ["b_aa2_2", "b_atkjumpdown", "b_atkjumpdown"],
        "Odmg": ["b_dmg_2", "b_dmg_2"],
        "D": ["b_gameover", "b_gameover"],
    }
    path = "Images/Blanchon"
    imagesBlanchon = load_imgs(imagesBlanchonList, path)
    blanchon_atkList = [
        Atk("autoHit1", 0.5, 32, 32,
            load_imgs({"idle": ["particlehit"]}, path, 1), 10, 5, -1, 0, 0, 0,
            225),
        Atk("autoHit2", 0.7, 32, 32,
            load_imgs({"idle": ["particlehit"]}, path, 1), 15, 5, -2, 0, 0, 0,
            300),
        Atk("autoHit3", 0.7, 32, 32,
            load_imgs({"idle": ["particlehit"]}, path, 1), 15, 6, -16, 0, 0, 0,
            500),
        Atk("EOF", 4, 32, 17, load_imgs({"idle": ["vector"]}, path), 15, 4, -1,
            0, 4, 0, 2000),
        Atk("airAutoHit", 1, 64, 32,
            load_imgs({"idle": ["particlehit"]}, path, 1), 10, 5, 5, 0, 0, 0,
            300)
    ]
    blanchon = Hero(200, 200, 64, 64, imagesBlanchon, 0.3, 0.7, 8, 6, WIDTH,
                    100.0, blanchon_atkList, difHard)
    sol = Platform(
        0, HEIGHT - 70, WIDTH, 10,
        pygame.image.load("Images/plateformtest.png").convert_alpha(), 0.4)

    # INIT ENNEMIS
    foes = []

    # INIT POLICE
    Mult = pygame.font.Font("Polices/Lady Radical.ttf", 25)
    Mult.set_bold(False)
    MultB = pygame.font.Font("Polices/Lady Radical.ttf", 40)
    MultB.set_bold(False)
    damageFont = pygame.font.Font("Polices/Lady Radical.ttf", 30)
    timerFont = pygame.font.Font("Polices/Lady Radical.ttf", 25)
    timerFont.set_bold(False)
    levelFont = pygame.font.Font("Polices/Lady Radical.ttf", 25)
    levelFont.set_bold(False)
    scoreFont = pygame.font.Font("Polices/Lady Radical.ttf", 25)
    levelFont.set_bold(False)
    clearFont = pygame.font.Font("Polices/Lady Radical.ttf", 30)
    clearFont.set_bold(False)
    clearLabel = clearFont.render("STAGE CLEAR", 1, (10, 200, 50))

    # INIT MUSIQUE
    pygame.mixer.init()
    musicMob = "Music/mob.wav"
    musicBoss = "Music/boss.wav"
    # INIT VAR DE JEU
    damageArray = []
    timerDamage = 300
    score = 0
    niveau = 1

    tempsParSalve = 10.0

    # INIT SYSTEM CLOCK
    clock = pygame.time.Clock()
    fps = 60

    while not blanchon.isDead():
        salve = 1
        # INIT PLATEFORMES
        platforms = [
            Platform(randint(100, 400), HEIGHT - 180, 100, 10,
                     pygame.image.load("Images/plateform.png").convert_alpha(),
                     1),
            Platform(randint(100, 400), HEIGHT - 280, 100, 10,
                     pygame.image.load("Images/plateform.png").convert_alpha(),
                     1)
        ]
        while salve < 6 and not blanchon.isDead():
            i = 0
            if salve < 5:
                # AJOUTER DES MOBS A FOES
                while i < int(niveau + salve / 5):
                    mobId = randint(0, 3)
                    if mobId == 0:
                        foes.append(
                            Ninja(randint(50, WIDTH - 100), HEIGHT - 300,
                                  WIDTH, 1 + niveau / 10))
                    elif mobId == 1:
                        foes.append(
                            Samurai(randint(50, WIDTH - 100), HEIGHT - 300,
                                    WIDTH, 1 + niveau / 10))
                    elif mobId == 2:
                        foes.append(
                            Archer(randint(50, WIDTH - 100), HEIGHT - 300,
                                   WIDTH, 1 + niveau / 10))
                    elif mobId == 3:
                        foes.append(
                            Corbeau(randint(50, WIDTH - 100), HEIGHT - 300,
                                    WIDTH, 1 + niveau / 10))
                    i += 1
            else:
                # AJOUTER UN BOSS A FOES
                while i < 1 + int(niveau / 5):
                    if (niveau + i) % 2 == 0:
                        foes.append(Demon(500, 350, WIDTH, 1 + niveau / 10))
                    elif (niveau + i) % 2 == 1:
                        foes.append(Moine(500, 350, WIDTH, 1 + niveau / 10))
                    i += 1
            niveauLabel = levelFont.render(f"{niveau} - {salve}", 1,
                                           (250, 250, 250))
            timer = tempsParSalve
            timeSave = pygame.time.get_ticks()
            if salve == 5:
                pygame.mixer.music.load(musicBoss)
                pygame.mixer.music.play(-1)
            elif salve == 1:
                pygame.mixer.music.load(musicMob)
                pygame.mixer.music.set_volume(0.4)
                pygame.mixer.music.play(-1)
            # BOUCLE DE JEU =========================================================================================
            while len(foes) > 0 and (timer > 0.0
                                     or salve >= 4) and not blanchon.isDead():
                # GESTION TIMER-----------------------------------------------------------------
                if timer <= 0.0:
                    timer = 0
                else:
                    timer = timer - (pygame.time.get_ticks() -
                                     timeSave) / 1000.0
                    timeSave = pygame.time.get_ticks()

                # render text
                if salve != 5:
                    timerLabel = timerFont.render(f"{timer:.1f} sec", 1,
                                                  (50, 100, 200))
                else:
                    timerLabel = timerFont.render("BOSS", 1, (50, 100, 200))
                scoreLabel = scoreFont.render(f"Score : {int(score)}", 1,
                                              (200, 200, 100))

                clock.tick(fps)
                # GESTION EVENT------------------------------------------------------------------
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:  # si l'utilisateur clique sur la croix
                        sys.exit()  # on ferme la fenêtre
                    if event.type == pygame.KEYDOWN:
                        blanchon.key_down(event)
                    if event.type == pygame.KEYUP:
                        blanchon.key_up(event)

                # GESTION DU DECORS--------------------------------------------------------------
                # Fond
                fenetre.blit(fond_e, (0, 0))
                # timer
                fenetre.blit(timerLabel, (490, 660))
                fenetre.blit(niveauLabel, (500, 690))

                # Plateformes
                nbPlatf = len(platforms)
                for i in range(0, nbPlatf):
                    fenetre.blit(platforms[i].get_img(),
                                 platforms[i].get_rect())

                # GESTION DU HERO----------------------------------------------------------------
                # Affichage Multiplicateur de dégats
                Multipl = Mult.render("Mult : ", 1, (255, 255, 0))
                combo = blanchon.get_combo()
                if combo < 2:
                    MultiplCombo = MultB.render(f"{combo:.2f}", 1,
                                                (255, 255, 0))
                elif combo < 3:
                    MultiplCombo = MultB.render(f"{combo:.2f}", 1, (0, 0, 255))
                elif combo < 4:
                    MultiplCombo = MultB.render(f"{combo:.2f}", 1,
                                                (255, 0, 255))
                else:
                    MultiplCombo = MultB.render(f"{combo:.2f}", 1, (255, 0, 0))

                fenetre.blit(Multipl, (700, 660))
                fenetre.blit(MultiplCombo, (800, 650))
                # Affichage du score
                fenetre.blit(scoreLabel, (700, 690))

                # CoolDown Attaque de Blanchon
                colorRect = (125, 125, 125, 128)

                if not blanchon.get_onGround():
                    cd = blanchon_atkList[4].get_cd()
                    if cd > 0:
                        pygame.draw.rect(fenetre, (0, 0, 0), (95, 655, 60, 60))
                    else:
                        pygame.draw.rect(fenetre, (200, 200, 50),
                                         (95, 655, 60, 60))
                    tailleRect1 = 60 * cd / blanchon_atkList[4].get_maxCd()
                    posRect1 = 715 - tailleRect1
                    fenetre.blit(blanchonAaMidAir, (100, 660))
                    CdAH = damageFont.render(f"{cd:.1f}" if cd else "", 1,
                                             (255, 0, 0))
                elif blanchon.get_autoHitTimer3() > 0:
                    pygame.draw.rect(fenetre, (200, 200, 50),
                                     (95, 655, 60, 60))
                    fenetre.blit(blanchonAa3, (100, 660))
                    tailleRect1 = 60 * blanchon.get_autoHitTimer3() / 3000
                    posRect1 = 715 - tailleRect1
                    CdAH = damageFont.render(
                        f"{blanchon.get_autoHitTimer3()/1000:.1f}" if
                        blanchon.get_autoHitTimer3() else "", 1, (255, 0, 0))
                elif blanchon.get_autoHitTimer2() > 0:
                    pygame.draw.rect(fenetre, (200, 200, 50),
                                     (95, 655, 60, 60))
                    fenetre.blit(blanchonAa2, (100, 660))
                    tailleRect1 = 60 * blanchon.get_autoHitTimer2() / 3000
                    posRect1 = 715 - tailleRect1
                    CdAH = damageFont.render(
                        f"{blanchon.get_autoHitTimer2()/1000:.1f}" if
                        blanchon.get_autoHitTimer2() else "", 1, (255, 0, 0))
                else:
                    cd = blanchon_atkList[0].get_cd()
                    if cd > 0:
                        pygame.draw.rect(fenetre, (0, 0, 0), (95, 655, 60, 60))
                    else:
                        pygame.draw.rect(fenetre, (200, 200, 50),
                                         (95, 655, 60, 60))

                    fenetre.blit(blanchonAa1, (100, 660))
                    tailleRect1 = 60 * cd / blanchon_atkList[0].get_maxCd()
                    posRect1 = 715 - tailleRect1
                    CdAH = damageFont.render(f"{cd:.1f}" if cd else "", 1,
                                             (255, 0, 0))

                CaseAa = pygame.Surface((60, tailleRect1), pygame.SRCALPHA)
                CaseAa.fill(colorRect)
                fenetre.blit(CaseAa, (95, posRect1))
                fenetre.blit(CdAH, (110, 670))
                if blanchon_atkList[3].get_cd() > 0:
                    pygame.draw.rect(fenetre, (0, 0, 0), (175, 655, 60, 60))
                    pygame.draw.rect(fenetre, (255, 255, 255),
                                     (180, 660, 50, 50))
                else:
                    pygame.draw.rect(fenetre, (200, 200, 50),
                                     (175, 655, 60, 60))
                    pygame.draw.rect(fenetre, (255, 255, 255),
                                     (180, 660, 50, 50))

                fenetre.blit(blanchonVector, (189, 677))

                tailleRect2 = 60 * blanchon_atkList[3].get_cd(
                ) / blanchon_atkList[3].get_maxCd()
                posRect2 = 715 - tailleRect2
                CaseAa = pygame.Surface((60, tailleRect2), pygame.SRCALPHA)
                CaseAa.fill((125, 125, 125, 128))
                fenetre.blit(CaseAa, (175, posRect2))

                CdProj = damageFont.render(
                    f"{blanchon_atkList[3].get_cd():.1f}", 1, (255, 0, 0))
                if blanchon_atkList[3].get_cd() > 0:
                    fenetre.blit(CdProj, (190, 670))
                # Teste Hero => Plateforme
                heroOnGround = blanchon.isOnGround()
                blanchon.setOnAir()
                blanchon.testPlatform(sol)
                for i in range(0, nbPlatf):
                    blanchon.testPlatform(platforms[i])

                # Le hero est descendu d'une plateforme
                if heroOnGround and not blanchon.isOnGround():
                    blanchon.giveDoubleJump()  # On lui donne un saut

                blanchon.update(blanchon, fps)

                # AFFICHAGE DES DEGATS----------------------------------------------------------
                i = 0
                while i < len(damageArray):
                    if damageArray[i][2] > 0:
                        fenetre.blit(damageArray[i][0], damageArray[i][1])
                        damageArray[i][2] = damageArray[i][2] - (1000 / fps)
                        i += 1
                    else:
                        damageArray.pop(i)

                # GESTION DES MOBS---------------------------------------------------------------
                # Teste Mob => Plateforme && Atk Hero => Mob
                nbAtkHero = len(blanchon.get_AtkEffectList())
                i = 0
                while i < len(foes):
                    foes[i].nextImg(fps)
                    fenetre.blit(foes[i].get_img(), foes[i].get_rect())
                    pygame.draw.rect(fenetre, (0, 0, 0),
                                     (foes[i].get_rect().x,
                                      foes[i].get_rect().y - 10, 60, 6))
                    pygame.draw.rect(
                        fenetre, (255, 0, 0),
                        (foes[i].get_rect().x, foes[i].get_rect().y - 10,
                         int(
                             max(
                                 min(
                                     foes[i].get_hp() / foes[i].get_hpMax() *
                                     60, 60), 0)), 6))
                    foes[i].setOnAir()
                    foes[i].testPlatform(sol)

                    for j in range(0, nbPlatf):
                        foes[i].testPlatform(platforms[j])

                    # Check si le mob i se fait toucher par l'atk de hero k
                    for k in range(0, nbAtkHero):
                        hpBefore = foes[i].get_hp()
                        foes[i].testAtkEffect(blanchon.get_AtkEffectList()[k])
                        degats = foes[i].get_hp() - hpBefore
                        if degats < 0.0:
                            damageArray.append([
                                damageFont.render(f"{degats:.1f}", 1,
                                                  (50, 150, 255)),
                                (foes[i].get_x(), foes[i].get_y() - 40),
                                timerDamage
                            ])

                    nbAtkFoe = len(foes[i].get_AtkEffectList())
                    for l in range(0, nbAtkFoe):
                        hpBefore = blanchon.get_hp()
                        blanchon.testAtkEffect(foes[i].get_AtkEffectList()[l])
                        degats = blanchon.get_hp() - hpBefore
                        if degats < 0:
                            damageArray.append([
                                damageFont.render(f"{degats:.1f}", 1,
                                                  (255, 0, 0)),
                                (blanchon.get_x(), blanchon.get_y() - 40),
                                timerDamage
                            ])

                        fenetre.blit(foes[i].get_AtkEffectList()[l].get_img(),
                                     foes[i].get_AtkEffectList()[l].get_rect())

                    foes[i].update(blanchon, fps)
                    if foes[i].get_hp() <= 0:
                        # AJOUT DES POINTS AU SCORE
                        score += foes[i].get_hpMax() * foes[i].get_hpMax()
                        foes.pop(i)
                    else:
                        i += 1

                for i in range(0, nbAtkHero):
                    fenetre.blit(blanchon.get_AtkEffectList()[k].get_img(),
                                 blanchon.get_AtkEffectList()[k].get_rect())

                # Affichage Hero
                blanchon.nextImg(fps)
                fenetre.blit(blanchon.get_img(), blanchon.get_rect())
                pygame.draw.rect(
                    fenetre, (0, 0, 0),
                    (blanchon.get_rect().x, blanchon.get_rect().y - 10, 60, 6))
                pygame.draw.rect(
                    fenetre, (0, 255, 0),
                    (blanchon.get_rect().x, blanchon.get_rect().y - 10,
                     int(
                         max(
                             blanchon.get_hp() / float(blanchon.get_hpMax()) *
                             60, 0)), 6))

                pygame.display.flip()
            # AJOUTE DES POINTS AU SCORE
            score += (tempsParSalve - timer) * 500
            salve += 1

        # ON FAIT UNE PAUSE ENTRE CHAQUE NIVEAU
        if not blanchon.isDead():
            timePause = 3000.0
            timeStart = pygame.time.get_ticks()
            while timePause > 0.0:
                clock.tick(fps)
                timePause = timePause - pygame.time.get_ticks() + timeStart
                timeStart = pygame.time.get_ticks()

                fenetre.blit(fond_e, (0, 0))

                for i in range(0, len(foes)):
                    foes[i].update(blanchon, fps)
                    fenetre.blit(foes[i].get_img(), foes[i].get_rect())

                blanchon.setOnAir()
                blanchon.testPlatform(sol)

                for i in range(0, len(blanchon.get_AtkEffectList())):
                    blanchon.get_AtkEffectList()[i].update(blanchon, fps)
                    fenetre.blit(blanchon.get_AtkEffectList()[i].get_img(),
                                 blanchon.get_AtkEffectList()[i].get_rect())
                blanchon.update(blanchon, fps)
                fenetre.blit(blanchon.get_img(), blanchon.get_rect())

                fenetre.blit(clearLabel, (400, 300))
                pygame.display.flip()
            niveau += 1

    dieMenu = DieMenu(fenetre, ("Rejouer", "Menu"), name, score)
    dieMenu.run(difHard)

    pygame.display.flip()
コード例 #15
0
ファイル: sheet_reader.py プロジェクト: thhuang/SheetMusicAI
 def detect_half_rest(self, half_rest_dir: str) -> None:
     half_rest_imgs = load_imgs(half_rest_dir)
     detector = Detector(self, half_rest_imgs, self._threshold_half_rest)
     self._half_rest_boxes = detector.detect()
     draw_boxes('half_rest_boxes_img.png', self._img_rgb,
                self._half_rest_boxes)
コード例 #16
0
os.environ['CUDA_VISIBLE_DEVICES'] = '1'

# vram limit for eficiency
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)

# define class names
classes = ['lecoq', 'crocs', 'vans', 'nike', 'adidas', 'reebok', 'sbenu',
           'puma', 'drmartens', 'zeepseen', 'descente', 'converse', 'newbalance', 'barefoot']

# define our image size (width, height, channels)
target_size = (224, 224)

# load unprocessed images
data_x, data_y = load_imgs(datapath='/home/tkdrlf9202/Datasets/shoes_classification',
                           classes=classes, target_size=target_size)
print(data_x.shape)
# preprocess images for the model
data_x = preprocess_input(data_x)


# preprocess labels with scikit-learn LabelEncoder
label_encoder = LabelEncoder()
label_encoder.fit(data_y)
data_y_int = label_encoder.transform(data_y)

# calculate class weight
cls_weight = class_weight.compute_class_weight('balanced', np.unique(data_y_int), data_y_int)

# split the data to tran & valid data
data_x_train, data_x_valid, data_y_train, data_y_valid = train_test_split(data_x, data_y_int,
コード例 #17
0
    def __init__(self, config):

        screen_width, screen_height = config.screen_width, config.screen_height
        self.dims = (screen_width, screen_height)
        self.test_batch = config.test_batch
        self.test_in = 'test_images/' + config.dataset + '_in/'
        self.test_gt = 'test_images/' + config.dataset + '_gt/'
        self._screen = None
        self.reward = 0
        self.terminal = True
        self.stop_step = config.stop_step
        self.reward_func = config.reward_func

        # test data
        list_in = [self.test_in + name for name in os.listdir(self.test_in)]
        list_in.sort()
        list_gt = [self.test_gt + name for name in os.listdir(self.test_gt)]
        list_gt.sort()
        self.data_all, self.label_all = load_imgs(list_in, list_gt)
        self.test_total = len(list_in)
        self.test_cur = 0

        # BGR --> RGB, swap H and W
        # This is because the data for tools training are in a different format
        # You don't need to do so with your own tools
        temp = self.data_all.copy()
        self.data_all[:, :, :, 0] = temp[:, :, :, 2]
        self.data_all[:, :, :, 2] = temp[:, :, :, 0]
        self.data_all = np.swapaxes(self.data_all, 1, 2)
        temp = self.label_all.copy()
        self.label_all[:, :, :, 0] = temp[:, :, :, 2]
        self.label_all[:, :, :, 2] = temp[:, :, :, 0]
        self.label_all = np.swapaxes(self.label_all, 1, 2)

        self.data_test = self.data_all[0:min(self.test_batch, self.test_total),
                                       ...]
        self.label_test = self.label_all[
            0:min(self.test_batch, self.test_total), ...]

        # reward functions
        self.rewards = {'step_psnr_reward': step_psnr_reward}
        self.reward_function = self.rewards[self.reward_func]

        # base_psnr (input psnr)
        self.base_psnr = 0.
        for k in range(len(self.data_all)):
            self.base_psnr += psnr_cal(self.data_all[k, ...],
                                       self.label_all[k, ...])
        self.base_psnr /= len(self.data_all)

        self.data = np.array([[[[0]]]])
        self._data_index = 0
        self._data_len = len(self.data)

        # build toolbox
        self.action_size = 12 + 1
        toolbox_path = 'toolbox/'
        self.graphs = []
        self.sessions = []
        self.inputs = []
        self.outputs = []
        for idx in range(12):
            g = tf.Graph()
            with g.as_default():
                # load graph
                saver = tf.train.import_meta_graph(toolbox_path + 'tool%02d' %
                                                   (idx + 1) + '.meta')
                # input data
                input_data = g.get_tensor_by_name('Placeholder:0')
                self.inputs.append(input_data)
                # get the output
                output_data = g.get_tensor_by_name('sum:0')
                self.outputs.append(output_data)
                # save graph
                self.graphs.append(g)
            sess = tf.Session(graph=g,
                              config=tf.ConfigProto(log_device_placement=True))
            with g.as_default():
                with sess.as_default():
                    saver.restore(sess, toolbox_path + 'tool%02d' % (idx + 1))
                    self.sessions.append(sess)
コード例 #18
0
    gamma = 2  # 0.75
    pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
    pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
    return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1)) - K.sum(
        (1 - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0))


model = models.lite_conv(height,
                         width,
                         loss=weighted_binary_crossentropy,
                         optimizer=Adam(lr=1e-4),
                         metrics=['accuracy'],
                         channels=1)

print("Loading images")
imgs, masks, labels = load_imgs(random.sample(range(0, 140), 20))  #随机产生不重复整数列表

if os.path.exists("saved_models/{}_1.h5".format(model_name)):
    print('loading model')
    model = load_model("saved_models/{}_1.h5".format(model_name),
                       custom_objects={
                           'weighted_binary_crossentropy':
                           weighted_binary_crossentropy
                       })

print('Fit model')
model_checkpoint = ModelCheckpoint(model_filename,
                                   monitor='val_acc',
                                   save_best_only=True,
                                   verbose=1)
model.summary()
コード例 #19
0
    dtype = torch.float
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    if device.type == 'cuda':
        # # comment this if we want reproducibility
        # torch.backends.cudnn.benchmark = True
        # torch.backends.cudnn.enabled = True

        # # this might affect performance but allows reproducibility
        torch.backends.cudnn.enabled = False
        torch.backends.cudnn.deterministic = True

    # define dataset
    trf_train, trf_test = get_transforms()
    loader_train, loader_val = get_dataloaders(trf_train)
    mturk_images, _ = utils.load_imgs(args.test_dir, trf_test)

    # create model
    model = FTModel(
        models.resnet34(pretrained=True),
        layers_to_remove=1,
        num_features=args.emb_size,
        num_classes=args.num_classes,
    )
    model = model.to(device, dtype)

    # define loss function
    criterion = TripletLossHuman(margin=args.margin,
                                 unit_norm=True,
                                 device=device,
                                 seed=args.seed)
コード例 #20
0
ファイル: sheet_reader.py プロジェクト: thhuang/SheetMusicAI
 def detect_flat_sign(self, flat_sign_dir: str) -> None:
     flat_sign_imgs = load_imgs(flat_sign_dir)
     detector = Detector(self, flat_sign_imgs, self._threshold_flat_sign)
     self._flat_sign_boxes = detector.detect()
     draw_boxes('flat_sign_boxes_img.png', self._img_rgb,
                self._flat_sign_boxes)
コード例 #21
0
ファイル: sheet_reader.py プロジェクト: thhuang/SheetMusicAI
 def detect_whole_note(self, whole_note_dir: str) -> None:
     whole_note_imgs = load_imgs(whole_note_dir)
     detector = Detector(self, whole_note_imgs, self._threshold_whole_note)
     self._whole_note_boxes = detector.detect()
     draw_boxes('whole_note_boxes_img.png', self._img_rgb,
                self._whole_note_boxes)
コード例 #22
0
def main():
    training_path = '/data/cat/train'
    test_path = '/data/cat/test'

    train_data, labels = utils.load_imgs(training_path,
                                         file_ext='.jpg',
                                         neg_folder='non-cat')
    train_data = train_data.astype(np.float32)

    s = time.time()
    train_data, masks = utils.normalize_img_cv(train_data)
    #train_data = utils.normalize_img_max(train_data)
    e = time.time()
    print('\n\n normalize\n\n', e - s)
    print('train_data ', train_data.shape)

    s = time.time()
    #train_data = utils.normalize_img_cv(train_data)
    #train_data = utils.normalize_img_max(train_data)
    e = time.time()
    print('normalize', e - s)
    #return

    counter = collections.Counter(labels)

    fc = TrainFeatureMapGenerator(train_data)
    fc.set_min_feture(2, 2)
    fc.set_max_feture(2, 2)
    fc.caculate_features_all()

    s = time.time()
    fc.prepare_to_train(do_argsort=False)
    e = time.time()
    print('prepare to train', e - s)

    print(fc.fmap.shape)

    w = Weights(labels, init_neg_w=1.0, init_pos_w=1.19)
    #w  = Weights(labels)
    print(w.positive_num, w.negative_num)
    #uw = UnitWeights(labels)
    wt = WeakClassifierTrainer(fc.fmap,
                               w,
                               labels,
                               tmp_val=fc.tmp_val,
                               argsorted=False)
    #wt = WeakClassifierTrainer(fc.fmap, uw, labels, tmp_val=fc.tmp_val,  argsorted=False)

    wc = []
    s = time.time()
    for i in range(1):
        r = wt.train()
        uid, fval, coord = fc.get_feature(r[0], r[1])
        wc.append((uid, fval, coord, r[2], r[3]))
        print('\n\n')
    e = time.time()
    print('train', e - s)

    print(len(wc))
    for item in wc:
        print(item)
    print('\n\n')

    sc = StrongClassifier(wc)
    sc.setImg(train_data, labels=labels)
    ir = sc.inference()

    iv = InferenceVerifier(labels, ir['faces'])
    vr = iv.verify(verbose=True)
コード例 #23
0
ファイル: main.py プロジェクト: KUR-creative/unet
def main(experiment_yml_path):
    with open(experiment_yml_path, 'r') as f:
        settings = yaml.load(f)
    experiment_name, _ = os.path.splitext(
        os.path.basename(experiment_yml_path))
    print('->', experiment_name)
    for k, v in settings.items():
        print(k, '=', v)
    #----------------------- experiment settings ------------------------
    IMG_SIZE = settings['IMG_SIZE']
    BATCH_SIZE = settings['BATCH_SIZE']
    NUM_EPOCHS = settings['NUM_EPOCHS']

    data_augmentation = settings['data_augmentation']  # string

    dataset_dir = settings['dataset_dir']
    save_model_path = settings['save_model_path']  ## NOTE
    history_path = settings['history_path']  ## NOTE

    eval_result_dirpath = os.path.join(settings['eval_result_parent_dir'],
                                       experiment_name)
    # optional settings
    sqr_crop_dataset = settings.get('sqr_crop_dataset')
    kernel_init = settings.get('kernel_init')
    num_maxpool = settings.get('num_maxpool')
    num_filters = settings.get('num_filters')
    overlap_factor = settings.get('overlap_factor')
    #loaded_model = save_model_path ## NOTE
    loaded_model = None
    #--------------------------------------------------------------------

    #--------------------------------------------------------------------
    train_dir = os.path.join(dataset_dir, 'train')
    valid_dir = os.path.join(dataset_dir, 'valid')
    test_dir = os.path.join(dataset_dir, 'test')

    output_dir = os.path.join(dataset_dir, 'output')
    origin_dir = os.path.join(output_dir, 'image')
    answer_dir = os.path.join(output_dir, 'label')
    result_dir = os.path.join(output_dir, 'result')
    #--------------------------------------------------------------------

    #-------------------- ready to generate batch -----------------------
    train_imgs = list(load_imgs(os.path.join(train_dir, 'image')))
    train_masks = list(load_imgs(os.path.join(train_dir, 'label')))
    valid_imgs = list(load_imgs(os.path.join(valid_dir, 'image')))
    valid_masks = list(load_imgs(os.path.join(valid_dir, 'label')))
    test_imgs = list(load_imgs(os.path.join(test_dir, 'image')))
    test_masks = list(load_imgs(os.path.join(test_dir, 'label')))

    if overlap_factor is None: overlap_factor = 2
    #calc mean h,w of dataset
    tr_h, tr_w = sum(map(lambda img: np.array(img.shape[:2]),
                         train_imgs)) / len(train_imgs)
    vl_h, vl_w = sum(map(lambda img: np.array(img.shape[:2]),
                         valid_imgs)) / len(valid_imgs)
    te_h, te_w = sum(map(lambda img: np.array(img.shape[:2]),
                         test_imgs)) / len(test_imgs)
    #print(tr_h,tr_w, '|', vl_h,vl_w, '|', te_h,te_w)
    train_num_sample = int(
        (tr_h / IMG_SIZE) * (tr_w / IMG_SIZE) * overlap_factor)
    valid_num_sample = int(
        (vl_h / IMG_SIZE) * (vl_w / IMG_SIZE) * overlap_factor)
    test_num_sample = int(
        (te_h / IMG_SIZE) * (te_w / IMG_SIZE) * overlap_factor)
    #print(train_num_sample,valid_num_sample,test_num_sample)
    train_steps_per_epoch = modulo_ceil(
        len(train_imgs), BATCH_SIZE) // BATCH_SIZE * train_num_sample
    valid_steps_per_epoch = modulo_ceil(
        len(valid_imgs), BATCH_SIZE) // BATCH_SIZE * valid_num_sample
    test_steps_per_epoch = modulo_ceil(
        len(test_imgs), BATCH_SIZE) // BATCH_SIZE * test_num_sample
    print('# train images =', len(train_imgs), '| train steps/epoch =',
          train_steps_per_epoch)
    print('# valid images =', len(valid_imgs), '| valid steps/epoch =',
          valid_steps_per_epoch)
    print('#  test images =', len(test_imgs), '|  test steps/epoch =',
          test_steps_per_epoch)

    if data_augmentation == 'bioseg':
        aug = augmenter(BATCH_SIZE,
                        IMG_SIZE,
                        1,
                        crop_before_augs=[
                            iaa.Fliplr(0.5),
                            iaa.Flipud(0.5),
                            iaa.Affine(rotate=(-180, 180), mode='reflect'),
                        ],
                        crop_after_augs=[
                            iaa.ElasticTransformation(alpha=(100, 200),
                                                      sigma=14,
                                                      mode='reflect'),
                        ])
    elif data_augmentation == 'manga_gb':
        aug = augmenter(BATCH_SIZE,
                        IMG_SIZE,
                        1,
                        crop_before_augs=[
                            iaa.Affine(rotate=(-3, 3),
                                       shear=(-3, 3),
                                       scale={
                                           'x': (0.8, 1.5),
                                           'y': (0.8, 1.5)
                                       },
                                       mode='reflect'),
                        ])
    elif data_augmentation == 'no_aug':
        aug = augmenter(BATCH_SIZE, IMG_SIZE, 1)

    if sqr_crop_dataset:
        aug = None

    my_gen = batch_gen(train_imgs, train_masks, BATCH_SIZE, aug)
    valid_gen = batch_gen(valid_imgs, valid_masks, BATCH_SIZE, aug)
    test_gen = batch_gen(test_imgs, test_masks, BATCH_SIZE, aug)
    #--------------------------------------------------------------------
    '''
    # DEBUG
    for ims,mas in my_gen:
        for im,ma in zip(ims,mas):
            cv2.imshow('i',im)
            cv2.imshow('m',ma); cv2.waitKey(0)
    '''
    #---------------------------- train model ---------------------------
    if kernel_init is None: kernel_init = 'he_normal'
    if num_maxpool is None: num_maxpool = 4
    if num_filters is None: num_filters = 64

    LEARNING_RATE = 1.0
    model = unet(pretrained_weights=loaded_model,
                 input_size=(IMG_SIZE, IMG_SIZE, 1),
                 kernel_init=kernel_init,
                 num_filters=num_filters,
                 num_maxpool=num_maxpool,
                 lr=LEARNING_RATE)

    model_checkpoint = ModelCheckpoint(save_model_path,
                                       monitor='val_loss',
                                       verbose=1,
                                       save_best_only=True)
    train_timer = ElapsedTimer(experiment_yml_path + ' training')
    history = model.fit_generator(my_gen,
                                  epochs=NUM_EPOCHS,
                                  steps_per_epoch=train_steps_per_epoch,
                                  validation_steps=valid_steps_per_epoch,
                                  validation_data=valid_gen,
                                  callbacks=[model_checkpoint])
    train_time_str = train_timer.elapsed_time()
    #--------------------------------------------------------------------

    #--------------------------- save results ---------------------------
    origins = list(load_imgs(origin_dir))
    answers = list(load_imgs(answer_dir))
    assert len(origins) == len(answers)

    num_imgs = len(origins)

    if not sqr_crop_dataset:
        aug_det = augmenter(num_imgs, IMG_SIZE,
                            1).to_deterministic()  # no augmentation!
        origins = aug_det.augment_images(origins)
        answers = aug_det.augment_images(answers)

    predictions = model.predict_generator(
        (img.reshape(1, IMG_SIZE, IMG_SIZE, 1) for img in origins),
        num_imgs,
        verbose=1)
    evaluator.save_img_tuples(zip(origins, answers, predictions), result_dir)

    test_metrics = model.evaluate_generator(test_gen,
                                            steps=test_steps_per_epoch)
    K.clear_session()
    #print(model.metrics_names)
    #print(test_metrics)
    print('test set: loss =', test_metrics[0], '| IoU =', test_metrics[1])
    #--------------------------------------------------------------------

    #------------------- evaluation and save results --------------------
    with open(history_path, 'w') as f:
        f.write(
            yaml.dump(
                dict(
                    loss=list(map(np.asscalar, history.history['loss'])),
                    acc=list(map(np.asscalar, history.history['mean_iou'])),
                    val_loss=list(map(np.asscalar,
                                      history.history['val_loss'])),
                    val_acc=list(
                        map(np.asscalar, history.history['val_mean_iou'])),
                    test_loss=np.asscalar(test_metrics[0]),
                    test_acc=np.asscalar(test_metrics[1]),
                    train_time=train_time_str,
                )))

    modulo = 2**num_maxpool
    evaluator.eval_and_save_result(
        dataset_dir,
        save_model_path,
        eval_result_dirpath,
        files_2b_copied=[history_path, experiment_yml_path],
        num_filters=num_filters,
        num_maxpool=num_maxpool,
        modulo=modulo)
コード例 #24
0
ファイル: tuto.py プロジェクト: Inspirateur/LeReTourDeHanoi
def main(self):
    pygame.init()

    WIDTH = 1280
    HEIGHT = 720
    fenetre = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)

    fond_e = pygame.transform.scale(
        pygame.image.load(
            "Images/Background/niveauRecurciforce.png").convert(), (1280, 720))

    blanchonAa1 = pygame.image.load("Images/Spell/aa1.png").convert()
    blanchonAa2 = pygame.image.load("Images/Spell/aa2.png").convert()
    blanchonAa3 = pygame.image.load("Images/Spell/aa3.png").convert()
    blanchonAaMidAir = pygame.image.load("Images/Spell/aaMidAir.png").convert()
    blanchonVector = pygame.image.load("Images/Spell/vector.png").convert()

    imagesBlanchonList = {
        "Ridle": ["b_idle_1", "b_idle_2"],
        "Rmove": ["b_move_0", "b_move_1", "b_move_2", "b_move_1"],
        "Ffall": ["b_jumpdown_1", "b_jumpdown_2"],
        "Fcrouch": ["b_crouch_1", "b_crouch_2"],
        "Rslide": ["b_slide"],
        "Fjump": ["b_jumpup_1", "b_jumpup_2", "b_jumpup_3"],
        "Oaa1": ["b_aa1_1", "b_aa1_2", "b_aa1_3", "b_aa1_3"],
        "Oaa2":
        ["b_aa2_1", "b_aa2_2", "b_aa2_3", "b_aa2_4", "b_aa2_5", "b_aa2_5"],
        "Oaa3": [
            "b_aa3_1", "b_aa3_2", "b_aa3_3", "b_aa3_4", "b_aa3_5", "b_aa3_6",
            "b_aa3_6", "b_aa3_6"
        ],
        "Oaaa": ["b_aa2_2", "b_atkjumpdown", "b_atkjumpdown"],
        "Odmg": ["b_dmg_2", "b_dmg_2"],
        "D": ["b_gameover", "b_gameover"],
    }
    path = "Images/Blanchon"
    imagesBlanchon = load_imgs(imagesBlanchonList, path)
    blanchon_atkList = [
        Atk("autoHit1", 0.5, 32, 32, load_imgs({"idle": ["particlehit"]},
                                               path), 10, 5, -1, 0, 0, 0, 225),
        Atk("autoHit2", 0.7, 32, 32, load_imgs({"idle": ["particlehit"]},
                                               path), 15, 5, -2, 0, 0, 0, 300),
        Atk("autoHit3", 0.7, 32, 32, load_imgs({"idle": ["particlehit"]},
                                               path), 15, 6, -16, 0, 0, 0,
            500),
        Atk("EOF", 4, 32, 17, load_imgs({"idle": ["vector"]}, path), 15, 4, -1,
            0, 4, 0, 2000),
        Atk("airAutoHit", 1, 64, 32, load_imgs({"idle": ["particlehit"]},
                                               path), 10, 5, 5, 0, 0, 0, 300)
    ]
    blanchon = Hero(200, 200, 64, 64, imagesBlanchon, 0.3, 0.7, 8, 6, WIDTH,
                    100.0, blanchon_atkList)
    sol = Platform(
        0, HEIGHT - 70, WIDTH, 10,
        pygame.image.load("Images/plateformtest.png").convert_alpha(), 0.4)
    # INIT PLATEFORMES
    platforms = [
        Platform(100, HEIGHT - 180, 100, 10,
                 pygame.image.load("Images/plateform.png").convert_alpha(), 1),
        Platform(350, HEIGHT - 280, 100, 10,
                 pygame.image.load("Images/plateform.png").convert_alpha(), 1)
    ]

    # INIT ENNEMIS
    foes = [SacDeSable(600, 500, WIDTH, 1)]

    # INIT SYSTEM CLOCK
    clock = pygame.time.Clock()
    fps = 60
    Mult = pygame.font.Font("Polices/Lady Radical.ttf", 25)
    Mult.set_bold(False)
    MultB = pygame.font.Font("Polices/Lady Radical.ttf", 40)
    MultB.set_bold(True)
    damageFont = pygame.font.Font("Polices/Lady Radical.ttf", 30)
    # damageFont.set_bold(True)

    damageArray = []
    timerDamage = 300

    # TEXTE DU TUTO------------------------------------------------------------------
    self.myfontMini = pygame.font.Font("Polices/Lady Radical.ttf", 15)
    self.myfont = pygame.font.Font("Polices/Lady Radical.ttf", 25)
    fleches = self.myfont.render(
        "Les fleches directionnelles servent a se deplacer", 1, (200, 200, 0))
    atkDeBase = self.myfont.render(
        "'A' (Q sous Windows) permet de donner des coups au corps a corps", 1,
        (200, 200, 0))
    atkDistance = self.myfont.render(
        "'Z' (W sous Windows) permet de lancer des projectiles", 1,
        (200, 200, 0))
    combol = self.myfont.render(
        "Un combo est possible en realisant 3 attaques basiques successives",
        1, (200, 200, 0))
    dbSaut = self.myfont.render("Le double saut est possible", 1,
                                (200, 200, 0))
    quit1 = self.myfontMini.render("Appuyer sur 'Entree' pour ", 1,
                                   (200, 200, 0))
    quit2 = self.myfontMini.render("retourner au menu principal ", 1,
                                   (200, 200, 0))

    while 1:
        clock.tick(fps)
        # GESTION EVENT------------------------------------------------------------------
        for event in pygame.event.get():
            if event.type == pygame.QUIT:  # si l'utilisateur clique sur la croix
                sys.exit()  # on ferme la fenêtre
            if event.type == pygame.KEYDOWN:
                exit_game(event.key)
                blanchon.key_down(event)
            if event.type == pygame.KEYUP:
                blanchon.key_up(event)

        # GESTION DU DECORS--------------------------------------------------------------
        # Fond
        fenetre.blit(fond_e, (0, 0))
        self.screen.blit(fleches, (600, 50))
        self.screen.blit(atkDeBase, (600, 80))
        self.screen.blit(atkDistance, (600, 110))
        self.screen.blit(combol, (600, 140))
        self.screen.blit(dbSaut, (600, 170))
        self.screen.blit(quit1, (1100, 600))
        self.screen.blit(quit2, (1100, 620))
        # Plateformes
        nbPlatf = len(platforms)
        for i in range(0, nbPlatf):
            fenetre.blit(platforms[i].get_img(), platforms[i].get_rect())

        # GESTION DU HERO----------------------------------------------------------------
        # Affichage Multiplicateur de dégats
        Multipl = Mult.render("Mult : ", 1, (255, 255, 0))
        combo = blanchon.get_combo()
        if combo < 2:
            MultiplCombo = MultB.render(f"{combo:.2f}", 1, (255, 255, 0))
        elif combo < 3:
            MultiplCombo = MultB.render(f"{combo:.2f}", 1, (0, 0, 255))
        elif combo < 4:
            MultiplCombo = MultB.render(f"{combo:.2f}", 1, (255, 0, 255))
        else:
            MultiplCombo = MultB.render(f"{combo:.2f}", 1, (255, 0, 0))

        fenetre.blit(Multipl, (700, 680))
        fenetre.blit(MultiplCombo, (800, 670))

        # CoolDown Attaque de Blanchon
        colorRect = (125, 125, 125, 128)

        if not blanchon.get_onGround():
            cd = blanchon_atkList[4].get_cd()
            if cd > 0:
                pygame.draw.rect(fenetre, (0, 0, 0), (95, 655, 60, 60))
            else:
                pygame.draw.rect(fenetre, (200, 200, 50), (95, 655, 60, 60))
            tailleRect1 = 60 * cd / blanchon_atkList[4].get_maxCd()
            posRect1 = 715 - tailleRect1
            fenetre.blit(blanchonAaMidAir, (100, 660))
            CdAH = damageFont.render(f"{cd:.1f}", 1, (255, 0, 0))
        elif blanchon.get_autoHitTimer3() > 0:
            pygame.draw.rect(fenetre, (200, 200, 50), (95, 655, 60, 60))
            fenetre.blit(blanchonAa3, (100, 660))
            tailleRect1 = 60 * blanchon.get_autoHitTimer3() / 3000
            posRect1 = 715 - tailleRect1
            CdAH = damageFont.render(
                f"{blanchon.get_autoHitTimer3()/1000:.1f}", 1, (255, 0, 0))
        elif blanchon.get_autoHitTimer2() > 0:
            pygame.draw.rect(fenetre, (200, 200, 50), (95, 655, 60, 60))
            fenetre.blit(blanchonAa2, (100, 660))
            tailleRect1 = 60 * blanchon.get_autoHitTimer2() / 3000
            posRect1 = 715 - tailleRect1
            CdAH = damageFont.render(
                f"{blanchon.get_autoHitTimer2()/1000:.1f}", 1, (255, 0, 0))
        else:
            cd = blanchon_atkList[0].get_cd()
            if cd > 0:
                pygame.draw.rect(fenetre, (0, 0, 0), (95, 655, 60, 60))
            else:
                pygame.draw.rect(fenetre, (200, 200, 50), (95, 655, 60, 60))

            fenetre.blit(blanchonAa1, (100, 660))
            tailleRect1 = 60 * cd / blanchon_atkList[0].get_maxCd()
            posRect1 = 715 - tailleRect1
            CdAH = damageFont.render(f"{cd:.1f}", 1, (255, 0, 0))

        CaseAa = pygame.Surface((60, tailleRect1), pygame.SRCALPHA)
        CaseAa.fill(colorRect)
        fenetre.blit(CaseAa, (95, posRect1))
        if cd > 0:
            fenetre.blit(CdAH, (110, 670))
        if blanchon_atkList[3].get_cd() > 0:
            pygame.draw.rect(fenetre, (0, 0, 0), (175, 655, 60, 60))
            pygame.draw.rect(fenetre, (255, 255, 255), (180, 660, 50, 50))
        else:
            pygame.draw.rect(fenetre, (200, 200, 50), (175, 655, 60, 60))
            pygame.draw.rect(fenetre, (255, 255, 255), (180, 660, 50, 50))

        fenetre.blit(blanchonVector, (189, 677))

        tailleRect2 = 60 * blanchon_atkList[3].get_cd(
        ) / blanchon_atkList[3].get_maxCd()
        posRect2 = 715 - tailleRect2
        CaseAa = pygame.Surface((60, tailleRect2), pygame.SRCALPHA)
        CaseAa.fill((125, 125, 125, 128))
        fenetre.blit(CaseAa, (175, posRect2))

        CdProj = damageFont.render(f"{blanchon_atkList[3].get_cd():.1f}", 1,
                                   (255, 0, 0))
        if blanchon_atkList[3].get_cd() > 0:
            fenetre.blit(CdProj, (190, 670))
        # Teste Hero => Plateforme
        heroOnGround = blanchon.isOnGround()
        blanchon.setOnAir()
        blanchon.testPlatform(sol)
        for i in range(0, nbPlatf):
            blanchon.testPlatform(platforms[i])

        # Le hero est descendu d'une plateforme
        if heroOnGround and not blanchon.isOnGround():
            blanchon.giveDoubleJump()  # On lui donne un saut

        blanchon.update(blanchon, fps)

        # AFFICHAGE DES DEGATS----------------------------------------------------------
        i = 0
        while i < len(damageArray):
            if damageArray[i][2] > 0:
                fenetre.blit(damageArray[i][0], damageArray[i][1])
                damageArray[i][2] = damageArray[i][2] - (1000 / fps)
                i += 1
            else:
                damageArray.pop(i)

        # GESTION DES MOBS---------------------------------------------------------------
        # Teste Mob => Plateforme && Atk Hero => Mob
        nbAtkHero = len(blanchon.get_AtkEffectList())
        i = 0
        while i < len(foes):
            foes[i].nextImg(fps)
            fenetre.blit(foes[i].get_img(), foes[i].get_rect())
            pygame.draw.rect(
                fenetre, (0, 0, 0),
                (foes[i].get_rect().x, foes[i].get_rect().y - 10, 60, 6))
            pygame.draw.rect(
                fenetre, (255, 0, 0),
                (foes[i].get_rect().x, foes[i].get_rect().y - 10,
                 int(
                     max(
                         min(
                             foes[i].get_hp() / float(foes[i].get_hpMax()) *
                             60, 60), 0)), 6))
            foes[i].setOnAir()
            foes[i].testPlatform(sol)

            for j in range(0, nbPlatf):
                foes[i].testPlatform(platforms[j])

            # Check si le mob i se fait toucher par l'atk de hero k
            for k in range(0, nbAtkHero):
                hpBefore = foes[i].get_hp()
                foes[i].testAtkEffect(blanchon.get_AtkEffectList()[k])
                degats = foes[i].get_hp() - hpBefore
                foes[i].set_hp(degats)
                if degats < 0.0:
                    damageArray.append([
                        damageFont.render(f"{degats:.1f}", 1, (50, 150, 255)),
                        (foes[i].get_x(), foes[i].get_y() - 40), timerDamage
                    ])

            nbAtkFoe = len(foes[i].get_AtkEffectList())
            for l in range(0, nbAtkFoe):
                hpBefore = blanchon.get_hp()
                blanchon.testAtkEffect(foes[i].get_AtkEffectList()[l])
                degats = blanchon.get_hp() - hpBefore
                if degats < 0:
                    damageArray.append([
                        damageFont.render(f"{degats:.1f}", 1, (255, 0, 0)),
                        (blanchon.get_x(), blanchon.get_y() - 40), timerDamage
                    ])

                fenetre.blit(foes[i].get_AtkEffectList()[l].get_img(),
                             foes[i].get_AtkEffectList()[l].get_rect())

            foes[i].update(blanchon, fps)
            if foes[i].get_hp() <= 0:
                foes.pop(i)
            else:
                i += 1

        for i in range(0, nbAtkHero):
            fenetre.blit(blanchon.get_AtkEffectList()[k].get_img(),
                         blanchon.get_AtkEffectList()[k].get_rect())

        # Affichage Hero
        blanchon.nextImg(fps)
        fenetre.blit(blanchon.get_img(), blanchon.get_rect())
        pygame.draw.rect(
            fenetre, (0, 0, 0),
            (blanchon.get_rect().x, blanchon.get_rect().y - 10, 60, 6))
        pygame.draw.rect(
            fenetre, (0, 255, 0),
            (blanchon.get_rect().x, blanchon.get_rect().y - 10,
             int(
                 max(
                     min(blanchon.get_hp() / float(blanchon.get_hpMax()) * 60,
                         60), 0)), 6))

        pygame.display.flip()
コード例 #25
0
def main():
    training_path = '/data/daily/VJ/faces/train'
    test_path = '/data/daily/VJ/faces/test'

    train_data, labels = utils.load_imgs(training_path)
    train_data = train_data.astype(np.float32)

    print('train_data ', train_data.shape)

    s = time.time()
    #train_data = utils.normalize_img_cv(train_data)
    #train_data = utils.normalize_img_max(train_data)
    e = time.time()
    print('normalize', e - s)
    #return

    counter = collections.Counter(labels)

    fc = TrainFeatureMapGenerator(train_data)
    fc.set_min_feture(4, 4)
    fc.set_max_feture(4, 4)
    fc.caculate_features_all()

    s = time.time()
    fc.prepare_to_train(do_argsort=False)
    e = time.time()
    print('prepare to train', e - s)
    '''
	img_idx = 0
	c1 = fc.fmap[:,img_idx] 
	print('c1.shape ', c1.shape, np.sum(c1), np.sum(np.abs(c1)))

	f_all = []
	for i in tqdm(range(fc.fmap.shape[0])):
		_, fval, _ = fc.get_feature(img_idx, i)
		f_all.append(fval)

	f_all = np.asarray(f_all)
	print(f_all.shape, np.sum(f_all), np.sum(np.abs(f_all)))
	'''
    w = Weights(labels)
    print(w.positive_num, w.negative_num)
    #uw = UnitWeights(labels)
    wt = WeakClassifierTrainer(fc.fmap,
                               w,
                               labels,
                               tmp_val=fc.tmp_val,
                               argsorted=False)
    #wt = WeakClassifierTrainer(fc.fmap, uw, labels, tmp_val=fc.tmp_val,  argsorted=False)

    wc = []
    s = time.time()
    for i in range(20):
        r = wt.train()
        uid, fval, coord = fc.get_feature(r[0], r[1])
        wc.append((uid, fval, coord, r[2], r[3]))
        print('\n\n')
    e = time.time()
    print('train', e - s)

    print(len(wc))
    for item in wc:
        print(item)
    print('\n\n')

    sc = strong_classifier(wc)
    tmp = train_data[0].astype(int)
    tmp = tmp.reshape(19, 19, 1)
    cv2.imwrite("0.jpg", tmp)
    #train_data = train_data[0:5,:,:]
    sc.setImg(train_data, labels=labels)
    false_samples = sc.inference()

    m = np.ones(w.w.shape[0])
    fp = np.power(2, false_samples['false_positive'])
    fn = np.power(3, false_samples['false_negative'])

    m = m * fp
    m = m * fn
    w2 = Weights2(labels, multiplier=[m])
    np.savetxt('m.txt', m, fmt='%f')
    np.savetxt('w2.txt', w2.w, fmt='%f')

    wt2 = WeakClassifierTrainer(fc.fmap,
                                w2,
                                labels,
                                tmp_val=fc.tmp_val,
                                argsorted=False)
    wc2 = []
    for i in range(10):
        r = wt2.train()
        uid, fval, coord = fc.get_feature(r[0], r[1])
        wc2.append((uid, fval, coord, r[2], r[3]))
        print('\n\n')
    e = time.time()
    print('train', e - s)

    print(len(wc2))
    for item in wc2:
        print(item)
    print('\n\n')
コード例 #26
0
ファイル: sheet_reader.py プロジェクト: thhuang/SheetMusicAI
 def detect_sharp_sign(self, sharp_sign_dir: str) -> None:
     sharp_sign_imgs = load_imgs(sharp_sign_dir)
     detector = Detector(self, sharp_sign_imgs, self._threshold_sharp_sign)
     self._sharp_sign_boxes = detector.detect()
     draw_boxes('sharp_sign_boxes_img.png', self._img_rgb,
                self._sharp_sign_boxes)
コード例 #27
0
def main():
    training_path = './train'
    test_path = './test'

    train_data, labels = utils.load_imgs(training_path,
                                         file_ext='.jpg',
                                         neg_folder='non-cat')
    train_data = train_data.astype(np.float32)

    s = time.time()
    train_data, masks = utils.normalize_img_cv(train_data)
    #train_data = utils.normalize_img_max(train_data)
    e = time.time()
    print('\n\n normalize\n\n', e - s)
    print('train_data ', train_data.shape)

    s = time.time()
    #train_data = utils.normalize_img_cv(train_data)
    #train_data = utils.normalize_img_max(train_data)
    e = time.time()
    print('normalize', e - s)
    #return

    counter = collections.Counter(labels)

    fc = TrainFeatureMapGenerator(train_data)
    fc.set_min_feture(2, 2)
    fc.set_max_feture(2, 2)
    fc.caculate_features_all()

    s = time.time()
    fc.prepare_to_train(do_argsort=False)
    e = time.time()
    print('prepare to train', e - s)

    print(fc.fmap.shape)

    w = Weights(labels, init_neg_w=1.0, init_pos_w=1.19)
    #w  = Weights(labels)
    print(w.positive_num, w.negative_num)
    #uw = UnitWeights(labels)
    wt = WeakClassifierTrainer(fc.fmap,
                               w,
                               labels,
                               tmp_val=fc.tmp_val,
                               argsorted=False)
    #wt = WeakClassifierTrainer(fc.fmap, uw, labels, tmp_val=fc.tmp_val,  argsorted=False)

    wc = []
    s = time.time()
    for i in range(20):
        r = wt.train()
        uid, fval, coord = fc.get_feature(r[0], r[1])
        wc.append((uid, fval, coord, r[2], r[3]))
        print('\n\n')
    e = time.time()
    print('train', e - s)

    print(len(wc))
    for item in wc:
        print(item)
    print('\n\n')

    sc = StrongClassifier(wc, (24, 24))
    sc.setImg(train_data, labels=labels)
    ir = sc.inference()

    iv = InferenceVerifier(labels, ir['faces'])
    #print('@@@@@@@@@@@@@@@@@@@@ iv ',  ir['faces'].shape)
    vr = iv.verify(verbose=True)

    test_data, test_labels = utils.load_imgs(test_path,
                                             file_ext='.jpg',
                                             neg_folder='non-cat',
                                             max_=3000)
    test_data = test_data.astype(np.float32)

    test_data, masks = utils.normalize_img_cv(test_data, store=True)

    #------------------------------------------------------------------------------------
    m = np.ones(w.w.shape[0])
    fp = np.power(1.0, vr['false_positive'])
    fn = np.power(1.5, vr['false_negative'])

    m = m * fp
    m = m * fn
    w2 = Weights2(labels, init_neg_w=1.0, init_pos_w=3.0, multiplier=[m])
    print(
        "\n\n\n======================================================================\n\n\n"
    )

    fc.clean()
    fc.set_min_feture(4, 4)
    fc.set_max_feture(6, 6)

    fc.caculate_features_all()
    fc.prepare_to_train(do_argsort=False)

    wt2 = WeakClassifierTrainer(fc.fmap,
                                w2,
                                labels,
                                tmp_val=fc.tmp_val,
                                argsorted=False)
    wc2 = []
    s = time.time()
    for i in range(20):
        r = wt2.train()
        uid, fval, coord = fc.get_feature(r[0], r[1])
        wc2.append((uid, fval, coord, r[2], r[3]))
        print('\n\n')
    e = time.time()
    print('train', e - s)

    m = np.ones(w.w.shape[0])
    fp = np.power(1.0, vr['false_positive'])
    fn = np.power(1.5, vr['false_negative'])

    m = m * fp
    m = m * fn
    w3 = Weights2(labels, init_neg_w=1.0, init_pos_w=3.0, multiplier=[m])
    #print("\n\n\n======================================================================\n\n\n")

    fc.clean()
    fc.set_min_feture(8, 8)
    fc.set_max_feture(8, 8)

    fc.caculate_features_all()
    fc.prepare_to_train(do_argsort=False)

    wt3 = WeakClassifierTrainer(fc.fmap,
                                w3,
                                labels,
                                tmp_val=fc.tmp_val,
                                argsorted=False)
    wc3 = []
    s = time.time()
    for i in range(20):
        r = wt3.train()
        uid, fval, coord = fc.get_feature(r[0], r[1])
        wc3.append((uid, fval, coord, r[2], r[3]))
        print('\n\n')
    e = time.time()
    print('train', e - s)

    m = np.ones(w.w.shape[0])
    fp = np.power(1.0, vr['false_positive'])
    fn = np.power(1.5, vr['false_negative'])

    m = m * fp
    m = m * fn
    w4 = Weights2(labels, init_neg_w=1.0, init_pos_w=3.0, multiplier=[m])
    #print("\n\n\n======================================================================\n\n\n")

    fc.clean()
    fc.set_min_feture(10, 10)
    fc.set_max_feture(10, 10)

    fc.caculate_features_all()
    fc.prepare_to_train(do_argsort=False)

    wt4 = WeakClassifierTrainer(fc.fmap,
                                w4,
                                labels,
                                tmp_val=fc.tmp_val,
                                argsorted=False)
    wc4 = []
    s = time.time()
    for i in range(20):
        r = wt4.train()
        uid, fval, coord = fc.get_feature(r[0], r[1])
        wc4.append((uid, fval, coord, r[2], r[3]))
        print('\n\n')
    e = time.time()
    print('train', e - s)

    m = np.ones(w.w.shape[0])
    fp = np.power(1.0, vr['false_positive'])
    fn = np.power(1.5, vr['false_negative'])

    m = m * fp
    m = m * fn
    w5 = Weights2(labels, init_neg_w=1.0, init_pos_w=3.0, multiplier=[m])
    #print("\n\n\n======================================================================\n\n\n")

    fc.clean()
    fc.set_min_feture(12, 12)
    fc.set_max_feture(12, 12)

    fc.caculate_features_all()
    fc.prepare_to_train(do_argsort=False)

    wt5 = WeakClassifierTrainer(fc.fmap,
                                w5,
                                labels,
                                tmp_val=fc.tmp_val,
                                argsorted=False)
    wc5 = []
    s = time.time()
    for i in range(20):
        r = wt5.train()
        uid, fval, coord = fc.get_feature(r[0], r[1])
        wc5.append((uid, fval, coord, r[2], r[3]))
        print('\n\n')
    e = time.time()
    print('train', e - s)

    wcs = [wc, wc2, wc3, wc4, wc5]
    np.savez_compressed('./StrongClassifier', sc=wcs)
    #csc = CascadedStrongClassifier(strong_clfs=wcs)
    csc = CascadedStrongClassifier()
    csc.load_model('./StrongClassifier.npz')

    cat_img = cv2.imread(
        '/data/daily/VJ/VJ_git/new_ranged_table/0625/VJ_git/checkin/cat.jpg')
    cat_img = cv2.cvtColor(cat_img, cv2.COLOR_BGR2GRAY)
    cat_img = cat_img.reshape(1, cat_img.shape[0], cat_img.shape[1])
    print('cat_img', cat_img.shape)

    print(
        "======================================================================"
    )
    r = csc.inference(cat_img)
    print(
        "======================================================================"
    )

    if False:
        r = csc.inference(test_data)
        res = r['positive']
        print('^^^^', type(res))
        iv2 = InferenceVerifier(test_labels, res)
        vr2 = iv2.verify(verbose=True)
        print(
            "\n\n\n======================================================================\n\n\n"
        )
    #------------------------------------------------------------------------------------
    '''
コード例 #28
0
        i, idx_start, idx_end = 0, 0, 0
        while idx_end < len(imgs):
            idx_start = offset * i
            idx_end = min(offset * (i + 1), len(imgs))

            # forward through the CNN and get the embeddings
            _, embs = model.forward(imgs[idx_start:idx_end])
            partial_embs.append(embs.detach().cpu())

            # update index
            i += 1

        # move it to numpy and return
        embs = torch.cat(partial_embs, 0).numpy()
    return embs


if __name__ == '__main__':
    weights_path = 'data/model_best.pth.tar'
    imgs_path = 'data/havran1_ennis_298x298_LDR'
    # we will store the obtained feature vectors in this path
    embs_path = 'data/embs_havran_ennis.mat'

    model = utils.load_model(weights_path)
    imgs, img_paths = utils.load_imgs(imgs_path)
    embs = get_embeddings(model, imgs)

    scipy.io.savemat(embs_path, mdict={'embs': embs, 'img_paths': img_paths})

    print('done')
コード例 #29
0
ファイル: environment.py プロジェクト: zhangleily/RL-Restore
    def __init__(self, config):
        self.reward = 0
        self.terminal = True
        self.stop_step = config.stop_step
        self.reward_func = config.reward_func
        self.is_train = config.is_train
        self.count = 0  # count restoration step
        self.psnr, self.psnr_pre, self.psnr_init = 0., 0., 0.

        if self.is_train:
            # training data
            self.train_list = [
                config.train_dir + file
                for file in os.listdir(config.train_dir)
                if file.endswith('.h5')
            ]
            self.train_cur = 0
            self.train_max = len(self.train_list)
            f = h5py.File(self.train_list[self.train_cur], 'r')
            self.data = f['data'].value
            self.label = f['label'].value
            f.close()
            self.data_index = 0
            self.data_len = len(self.data)

            # validation data
            f = h5py.File(config.val_dir + os.listdir(config.val_dir)[0], 'r')
            self.data_test = f['data'].value
            self.label_test = f['label'].value
            f.close()
            self.data_all = self.data_test
            self.label_all = self.label_test
        else:
            # test data
            self.test_batch = config.test_batch
            self.test_in = config.test_dir + config.dataset + '_in/'
            self.test_gt = config.test_dir + config.dataset + '_gt/'
            list_in = [
                self.test_in + name for name in os.listdir(self.test_in)
            ]
            list_in.sort()
            list_gt = [
                self.test_gt + name for name in os.listdir(self.test_gt)
            ]
            list_gt.sort()
            self.name_list = [
                os.path.splitext(os.path.basename(file))[0] for file in list_in
            ]
            self.data_all, self.label_all = load_imgs(list_in, list_gt)
            self.test_total = len(list_in)
            self.test_cur = 0

            # data reformat, because the data for tools training are in a different format
            self.data_all = data_reformat(self.data_all)
            self.label_all = data_reformat(self.label_all)
            self.data_test = self.data_all[
                0:min(self.test_batch, self.test_total), ...]
            self.label_test = self.label_all[
                0:min(self.test_batch, self.test_total), ...]

        # input PSNR
        self.base_psnr = 0.
        for k in range(len(self.data_all)):
            self.base_psnr += psnr_cal(self.data_all[k, ...],
                                       self.label_all[k, ...])
        self.base_psnr /= len(self.data_all)

        # reward functions
        self.rewards = {'step_psnr_reward': step_psnr_reward}
        self.reward_function = self.rewards[self.reward_func]

        # build toolbox
        self.action_size = 12 + 1
        toolbox_path = 'toolbox/'
        self.graphs = []
        self.sessions = []
        self.inputs = []
        self.outputs = []
        for idx in range(12):
            g = tf.Graph()
            with g.as_default():
                # load graph
                saver = tf.train.import_meta_graph(toolbox_path + 'tool%02d' %
                                                   (idx + 1) + '.meta')
                # input data
                input_data = g.get_tensor_by_name('Placeholder:0')
                self.inputs.append(input_data)
                # get the output
                output_data = g.get_tensor_by_name('sum:0')
                self.outputs.append(output_data)
                # save graph
                self.graphs.append(g)
            sess = tf.Session(graph=g,
                              config=tf.ConfigProto(log_device_placement=True))
            with g.as_default():
                with sess.as_default():
                    saver.restore(sess, toolbox_path + 'tool%02d' % (idx + 1))
                    self.sessions.append(sess)
コード例 #30
0
ファイル: data_gen.py プロジェクト: KUR-creative/unet
                                                   sigma=14,
                                                   mode='reflect'),
                         iaa.Affine(rotate=(-180, 180), mode='reflect'),
                     ])
    aug3 = augmenter(1,
                     256,
                     1,
                     crop_before_augs=[
                         iaa.Fliplr(0.5),
                         iaa.Flipud(0.5),
                         iaa.ElasticTransformation(alpha=(100, 200),
                                                   sigma=14,
                                                   mode='nearest'),
                         iaa.Affine(rotate=(-180, 180), mode='symmetric'),
                     ])
    imgs = load_imgs('./tmp_exp')
    for img in imgs:
        img1 = aug1.augment_images([img])
        img2 = aug2.augment_images([img])
        img3 = aug3.augment_images([img])
        cv2.imshow('1', img1.reshape((256, 256, 1)))
        cv2.imshow('2', img2.reshape((256, 256, 1)))
        cv2.imshow('3', img3.reshape((256, 256, 1)))
        cv2.waitKey(0)
'''
import re
def human_sorted(iterable):
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    return sorted(iterable, key = alphanum_key)