コード例 #1
0
def get_square_image():
    """Agrandi les images en largeur pour les avoir carrées"""

    mt = MyTools()

    # La liste de tous les font_a
    rep = "/media/data/3D/projets/darknet-letters/letters/game/textures/pngs"
    sub_dirs = mt.get_all_sub_directories(rep)
    # sub_dirs comprend pngs qui est le root
    del sub_dirs[0]
    print(sub_dirs)

    for sb in sub_dirs:
        # Liste des images du répertoire
        imgs = mt.get_all_files_list(sb, ".png")
        for img_file in imgs:
            print("img_file", img_file)
            img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)
            h, w = img.shape[0], img.shape[1]
            print(h, w)  # 337 171
            top, bottom = 0, 0
            b = int((h - w) / 2)
            left = right = b
            try:
                img = cv2.copyMakeBorder(img,
                                         top,
                                         bottom,
                                         left,
                                         right,
                                         cv2.BORDER_CONSTANT,
                                         value=[0, 0, 0, 0])
            except:
                print("Largeur plus grande que hauteur pour l'image", img_file)
            cv2.imwrite(img_file, img)
コード例 #2
0
def resize_at_biggest():
    """Agrandi les images à la taille de la plus grande"""

    mt = MyTools()

    # La liste de tous les font_a
    rep = "/media/data/3D/projets/darknet-letters/letters/game/textures/pngs"
    sub_dirs = mt.get_all_sub_directories(rep)
    # sub_dirs comprend pngs qui est le root
    del sub_dirs[0]

    maxi = 0
    # Recherche de l'image la plus grande
    for sb in sub_dirs:
        # Liste des images du répertoire
        imgs = mt.get_all_files_list(sb, ".png")
        for img_file in imgs:
            #print("img_file", img_file)
            img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)
            h, w = img.shape[0], img.shape[1]
            if h > maxi:
                maxi = h
    print("maxi", maxi)

    # Retaillage à maxi
    for sb in sub_dirs:
        # Liste des images du répertoire
        imgs = mt.get_all_files_list(sb, ".png")
        for img_file in imgs:
            print("img_file", img_file)
            img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)
            img = cv2.resize(img, (maxi, maxi), interpolation=cv2.INTER_AREA)
            cv2.imwrite(img_file, img)
コード例 #3
0
def regroupage_font_images():
    """Regroupage des images de lettres d'une font, minuscule ou majuscule
    20 images 445x445
    5 x 445 = 2225 = w
    5 x 445 = 2225 = h
    abcde
    fghij
    klmno
    pqrst
    54ème ligne vide
    """

    mt = MyTools()

    textures = "/media/data/3D/projets/darknet-letters/letters/game/textures/"

    # La liste de tous les font_a
    rep = "/media/data/3D/projets/darknet-letters/letters/game/textures/pngs"
    sub_dirs = mt.get_all_sub_directories(rep)
    # sub_dirs comprend pngs qui est le root
    del sub_dirs[0]

    for sb in sub_dirs:
        # de /medi...../textures/pngs/font_6, récup de 6=font
        #font = sb[-6:][-1]
        font = sb[-1]

        # dtype=np.uint8
        minuscules = np.zeros((2225, 2225, 4))
        majuscules = np.zeros((2225, 2225, 4))

        # Liste des images du répertoire
        imgs = mt.get_all_files_list(sb, ".png")
        for img_file in imgs:
            #print("img_file", img_file)
            # position et maj_min
            position, maj_min = get_position_and_maj_min(img_file)

            if position != (-1, -1):
                # l'image
                img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)

                # agglomération des images
                if maj_min == "min":
                    minuscules = paste_image(minuscules, img, position[0],
                                             position[1])
                else:
                    majuscules = paste_image(majuscules, img, position[0],
                                             position[1])

        # Enreg des 2 fichiers dans le dossiers textures
        minuscule_file = textures + "minuscule_" + str(font) + ".png"
        cv2.imwrite(minuscule_file, minuscules)
        print("Enregistrement de:", minuscule_file)

        majuscules_file = textures + "majuscules_" + str(font) + ".png"
        cv2.imwrite(majuscules_file, majuscules)
コード例 #4
0
def directory_rename():

    mt = MyTools()
    rep_num = 0
    rep = "/media/data/3D/projets/darknet-letters/letters/game/textures/pngs"

    sub_dirs = mt.get_all_sub_directories(rep)
    # sub_dirs comprend pngs qui est le root
    del sub_dirs[0]

    for sb in sub_dirs:
        dst = rep + "/font_" + str(rep_num)
        print(sb, dst)
        os.rename(sb, dst)
        rep_num += 1
コード例 #5
0
class ResizeTrainingShot:
    def __init__(self, root, size):
        self.root = root  # soit ..../semaphore
        self.size = int(size)

        # Mes outils personnels
        self.tools = MyTools()

        # Renommage de training_shot en training_shot_copy
        self.rename_training_shot()

        # Re-création des dossiers
        self.create_training_shot_dir()
        self.create_sub_folders()

        # Liste des images
        self.shot_list = self.get_shot_list()

    def rename_training_shot(self):
        ori = os.path.join(self.root, "training_shot")
        dest = os.path.join(self.root, "training_shot_copy")
        os.rename(ori, dest)

    def create_training_shot_dir(self):
        directory = os.path.join(self.root, "training_shot")
        print("Dossier training_shot:", directory)
        self.tools.create_directory(directory)

    def create_sub_folders(self):
        """Création de n dossiers shot_000"""

        # Nombre de dossiers nécessaires
        d = os.path.join(self.root, "training_shot_copy")
        n = len(self.tools.get_all_sub_directories(d)) - 1
        print("Nombre de sous répertoires", n)
        for i in range(n):
            directory = os.path.join(self.root, 'training_shot',
                                     'shot_' + str(i).zfill(3))
            self.tools.create_directory(directory)
        print("Sous répertoires créés")

    def get_shot_list(self):
        """Liste des images"""

        # Liste
        shot = os.path.join(self.root, "training_shot_copy")
        shot_list = self.tools.get_all_files_list(shot, ".png")

        print("Dossier des images NB:", shot)
        print("Nombre d'images:", len(shot_list))

        return shot_list

    def change_resolution(self, img, x, y):
        """Une image peut-être ratée"""

        try:
            res = cv2.resize(img, (x, y), interpolation=cv2.INTER_AREA)
        except:
            res = np.zeros([self.size, self.size, 1], dtype=np.uint8)
        return res

    def get_new_name(self, shot):

        return shot.replace("/training_shot_copy/", "/training_shot/")

    def create_training_shot_resized_dir(self):

        directory = os.path.join(self.root, "training_shot_resized")
        print("Dossier training_shot_resized:", directory)
        self.tools.create_directory(directory)

    def batch(self):
        """Lecture, resize, save"""

        i = 0

        # Pour chaque image
        for shot in self.shot_list:
            # Lecture
            img = cv2.imread(shot, 0)

            # Resize
            img_out = self.change_resolution(img, self.size, self.size)
            i += 1

            # Save
            new_shot = self.get_new_name(shot)
            print(new_shot)
            cv2.imwrite(new_shot, img_out)
コード例 #6
0
class ResizeBlur:
    def __init__(self, root, size, blur, imshow=1):
        """ root = dossier semaphore
            size = taille des images pour l'ia
            blur = 0 à 10 pour flouter les images pour l'ia
            imshow = 0 ou 1 pour affichage d'image ou non pendant l'exécution
        """

        self.root = root  # soit ..../semaphore
        self.size = int(size)
        self.size = max(20, self.size)
        self.size = min(800, self.size)
        self.blur = blur
        self.imshow = imshow

        # Mes outils personnels
        self.tools = MyTools()

        # Le terrain de jeu
        self.create_training_shot_resized_dir()

        # Liste
        self.shot_list = self.get_shot_list()

        self.create_sub_folders()

    def create_training_shot_resized_dir(self):

        directory = os.path.join(self.root, "training_shot_resized")
        print("Dossier training_shot_resized:", directory)
        self.tools.create_directory(directory)

    def create_sub_folders(self):
        """Création de n dossiers shot_000"""

        # Nombre de dossiers nécessaires
        d = os.path.join(self.root, "training_shot")
        n = len(self.tools.get_all_sub_directories(d)) - 1
        print("Nombre de sous répertoires", n)
        for i in range(n):
            directory = os.path.join(self.root, 'training_shot_resized',
                                     'shot_' + str(i).zfill(3))
            self.tools.create_directory(directory)

    def get_new_name(self, shot):
        """ de
        /media/data/3D/projets/semaphore/training_shot/shot_000/shot_0_a.png
        à
        /media/data/3D/projets/semaphore/training_shot_resized/shot_000/shot_0_a.png
        j'ai
        /media/data/3D/projets/semaphore/training_shot_resized/shot_000/shot_3921_h.png
        """

        t = shot.partition("training_shot")
        # t = ('/media/data/3D/projets/semaphore/', 'training_shot',
        #                                       '/shot_000/shot_1054_s.png')
        name = os.path.join(self.root, "training_shot_resized", t[2][1:])

        return name

    def change_resolution(self, img, x, y):
        """Une image peut-être ratée"""

        try:
            res = cv2.resize(img, (x, y), interpolation=cv2.INTER_AREA)
        except:
            res = np.zeros([self.size, self.size, 1], dtype=np.uint8)
        return res

    def apply_blur(self, img, k):
        """TODO: Utiliser GaussianBlur
        img = cv2.GaussianBlur(img, (5, 5), 0)
        """

        if self.blur:
            img = cv2.blur(img, (k, k))
        return img

    def random_noise(self, img):
        """Entre 0 et 20 pixels au hasard"""

        nb = random.randint(0, 10)

        for i in range(nb):
            x = random.randint(0, 39)
            y = random.randint(0, 39)
            img[x][y] = 1

        return img

    def some_dirty(self, img):
        """0 à 3 paquets de 4 pixels
        0 1 0
        1 1 1
        0 1 0
        """

        nb = random.randint(0, 2)
        for i in range(nb):
            x = random.randint(0, 34)
            y = random.randint(0, 34)

            # 1ère ligne
            a = x + 1
            b = y + 0
            img[a][b] = 1

            # 2ème ligne
            for u in range(3):
                a = x + u
                b = y + 1
                img[a][b] = 1

            # 3ème ligne
            a = x + 1
            b = y + 2
            img[a][b] = 1

        return img

    def batch(self):
        """Liste des images, lecture, conversion, save"""

        i = 0
        if self.imshow:
            cv2.namedWindow('Image In')
            cv2.namedWindow('Image Out')

        # Pour chaque image
        for shot in self.shot_list:
            # Lecture
            img = cv2.imread(shot, 0)

            # ResizeBlur
            img_out = self.change_resolution(img, self.size, self.size)

            # Flou
            img_out = self.apply_blur(img_out, self.blur)

            # Noise
            # L'ajout de bruit est appris par le réseau et va dégrader la
            # reconnaissance, mais Jo dit que non, ça dépend de ???
            # #img_out = self.random_noise(img_out)
            # #img_out = self.some_dirty(img_out)

            # ## Affichage
            if self.imshow:
                if i % 500 == 0:
                    #print(i)
                    imgB = self.change_resolution(img_out, 600, 600)
                    cv2.imshow('Image In', img)
                    cv2.imshow('Image Out', imgB)
                    cv2.waitKey(1)
            i += 1

            # Save
            new_shot = self.get_new_name(shot)
            cv2.imwrite(new_shot, img_out)

        cv2.destroyAllWindows()

    def get_shot_list(self):
        """Liste des images"""

        # Liste
        shot = os.path.join(self.root, "training_shot")
        shot_list = self.tools.get_all_files_list(shot, ".png")

        print("Dossier des images NB:", shot)
        print("Nombre d'images:", len(shot_list))

        return shot_list
コード例 #7
0
class TtftoPng:

    def __init__(self, size):
        self.size = size
        self.tools = MyTools()

        # 10 polices possible seulement
        self.colors = COLORS
        self.color_num = 0
        
        # Create pngs directory
        self.tools.create_directory("./pngs")
        
        # Dict des dossiers avec ttf
        self.ttf_list = self.get_ttfs()
        
        # Création des sous dossiers dans ./pngs 
        self.create_sub_directories()

    def convert_ttfs(self):
        """Convertit tous les ttfs"""
        
        for rep in self.ttf_list:
            # récup du ttf
            ttf = self.tools.get_all_files_list(rep, 'ttf')
            print("Conversion de:", rep)
            self.convert_ttf(rep, ttf)
            self.color_num += 1
            
    def convert_ttf(self, rep, ttf):
        """Convertit un ttf"""
        
        for l in LETTRES:
            l = l.upper()
            self.convert_letter(l, rep, ttf)
            l = l.lower()
            self.convert_letter(l, rep, ttf)
        # #for c in CHIFFRES:
            # #self.convert_letter(c, rep, ttf)            
            
    def convert_letter(self, letter, rep, ttf):
        """Convertit une lettre
        Conversion de:  ./ttfs/southern/Southern.ttf
        lettre:  A
        dans: ./pngs/southern/
        command convert -background none -fill black -font
        ./ttfs/southern/Southern.ttf -pointsize 300 -write ./pngs/southern/
        label:"A" A.png
        """

        #print("Conversion de {}".format(letter))
        
        filename = "./pngs" + rep[6:] + "/" + letter + ".png"

        if len(ttf) > 0:
            font = "./" + ttf[0]
            # remplacement espace dans le nom,
            # mais dossier ne doit pas avoir d'espace
            font = font.replace(' ', '\\ ')
            color = self.colors[self.color_num]
            
            # #print(  "Conversion de: ", font,
                    # #" lettre: ", letter,
                    # #" dans: ", filename,
                    # #"color", color)

            command = 'convert -background none -fill {4} -font {3} \
                       -pointsize {1} label:"{0}" {2}'.format(  letter,
                                                                self.size,
                                                                filename,
                                                                font,
                                                                color)
            #print("command", command)
            
            subprocess.call(command, shell=True)
        
    def create_sub_directories(self):
        """"Création des sous dossiers dans ./pngs"""
        
        for d in self.ttf_list:
            parts = d.split("/")
            self.tools.create_directory("./pngs/" + parts[-1])
            
    def get_ttfs(self):
        # Tous les fichiers ttf
        ttfs = self.tools.get_all_sub_directories("./ttfs")

        ttf_list  = []
        
        for subdir in ttfs:
            if subdir != "./ttfs":
                dd = self.tools.get_all_sub_directories(subdir)
                for d in dd:
                    if "MACOSX" not in d:
                        if subdir not in ttf_list:
                            ttf_list.append(subdir)
        return ttf_list