Exemplo n.º 1
0
    def resize_image(self, factor):
        '''
        Resize bitmap 
        1. with dimension (width x height) 
        2. with ratio value (strictly positive integer)
        '''
        # get current width and current height
        width = np.shape(self.image_matrix)[1]
        height = np.shape(self.image_matrix)[0]

        # get new width and new height with dimension values
        if len(factor) == 2:
            new_width = int(factor[0])
            new_height = int(factor[1])
        # get new width and new height with ratio value
        elif len(factor) == 1:
            new_width = int(
                float(factor[0]) * get_int_from_bytes(self.bi_width.tolist()))
            new_height = int(
                float(factor[0]) * get_int_from_bytes(self.bi_height.tolist()))

        # resizing procedure
        # if new dimension is greater than the current dimension, we simply duplicate pixels
        # if new dimension is lesser than the current dimension, we simply get less pixels (and lose information)
        self.image_matrix = [[
            self.image_matrix[int(height * a / new_height)][int(
                width * b / new_width)] for b in range(new_width)
        ] for a in range(new_height)]

        if self.verbose == True:
            print("{} has been resized to {} x {}".format(
                self.img.replace('../images/', ''), new_width, new_height))
Exemplo n.º 2
0
    def test_get_int_from_bytes(self):
        '''
        unit test for get_int_from_bytes
        '''

        # Test if it return int value from array of bytes
        self.assertTrue(isinstance(get_int_from_bytes([ord(b'\x00'), ord(b'\x02'), ord(b'\x00'), ord(b'\x00')]), int))
        self.assertTrue(isinstance(get_int_from_bytes([0, 2, 0, 0]), int))
Exemplo n.º 3
0
    def fit(self, is_processing):
        '''
        Fit the bitmap header
        1. if output is required we fit the bitmap palette and image bytes
        '''
        if self.verbose == True:
            #-------performance calculation--------
            starttime = timeit.default_timer()
            print("Start fitting time:", starttime)
            #--------------------------------------

        # fit all bitmap bytes into self.octets
        self.ouverture_fichiers_image()

        #file header
        self.bf_type = self.octets[0:2]
        self.bf_size = self.octets[2:6]
        self.bf_reserved1 = self.octets[6:8]
        self.bf_reserved2 = self.octets[8:10]
        self.bf_offbits = self.octets[10:14]

        #file info
        self.bi_size = self.octets[14:18]
        self.bi_width = self.octets[18:22]
        self.bi_height = self.octets[22:26]
        self.bi_planes = self.octets[26:28]
        self.bi_bitcount = self.octets[28:30]
        self.bi_compression = self.octets[30:34]
        self.bi_sizeimage = self.octets[34:38]
        self.bi_xpelspermeter = self.octets[38:42]
        self.bi_ypelspermeter = self.octets[42:46]
        self.bi_clrused = self.octets[46:50]
        self.bi_clrimportant = self.octets[50:54]

        # if output or histogram is required
        if is_processing:
            # fit bitmap palette
            self.b_palette = self.octets[54:get_int_from_bytes(self.bf_offbits.
                                                               tolist())]

            # fit image matrix with bitmap image bytes
            self.image_matrix = self.octets[
                get_int_from_bytes(self.bf_offbits.tolist()):].reshape(
                    get_int_from_bytes(self.bi_height.tolist()),
                    get_int_from_bytes(self.bi_width.tolist()),
                    int(get_int_from_bytes(self.bi_bitcount.tolist()) / 8))

        if self.verbose == True:
            print('image successfully loaded')
            #-------performance calculation--------
            print("Fitting duration:", timeit.default_timer() - starttime)
Exemplo n.º 4
0
 def do_magic(image):
     '''
     generated a new image by applying new_coordinate calculation on each pixels of the image
     '''
     new_image = np.empty(
         (len(self.image_matrix), len(self.image_matrix[1]),
          int(get_int_from_bytes(self.bi_bitcount) / 8)),
         dtype='int64')
     width = np.shape(image)[1]
     length = np.shape(image)[0]
     for i in range(width):
         for j in range(length):
             u, v = new_coordinate(i, j, image)
             new_image[u][v] = image[i][j]
     return new_image
Exemplo n.º 5
0
 def filter(matrix, kernel):
     '''
     The goal of this function is to make 9 shifted copies where the kernel is applied of the original matrix
     Then we just sum up these 9 matrix together and finally optimized the convolution algorithm
     '''
     # initialize list of matrix copies
     copies = np.empty(
         (len(kernel) * len(kernel), len(matrix), len(
             matrix[1]), int(get_int_from_bytes(self.bi_bitcount) / 8)),
         dtype='int64')
     # Go through the kernel (size: 3x3)
     for i in range(np.shape(kernel)[1]):
         for j in range(np.shape(kernel)[0]):
             # Save copies of the original image shifted by 1 pixel around + kernel value application
             copies[i * len(kernel) +
                    j] = np.roll(matrix.copy(),
                                 (i - (len(kernel) // 2), j -
                                  (len(kernel) // 2)),
                                 (0, 1)) * kernel[i][j]
     # return the sum of each copies to get back our new matrix with kernel value applied
     return copies.sum(axis=0)
Exemplo n.º 6
0
    def ouverture_fichiers_image(self):
        '''
        1. Open the image
        2. Get the size of the image
        3. Get all bytes of the image
        '''
        f_lecture = open(self.img, 'rb')

        # read file size from header
        i = 0
        while (i < 6):
            octet = f_lecture.read(1)
            self.octets.append(ord(octet))
            i += 1
        self.bf_size = get_int_from_bytes([k for k in self.octets[2:]])

        # get every image bytes
        while i < self.bf_size:
            octet = f_lecture.read(1)
            self.octets.append(ord(octet))
            i += 1
        self.octets = np.array(self.octets)
        f_lecture.close
Exemplo n.º 7
0
    def display_header(self):
        '''
        Display information about the bitmap header 
        '''
        print('Bitmap header information')
        print(" dec=", self.bf_type[0], " hexa=",
              hex(self.bf_type[0])[2:].upper())
        print(" dec=", self.bf_type[1], " hexa=",
              hex(self.bf_type[1])[2:].upper())

        print(" =>Magic Number =", self.bf_type, " BM => BitMap signature",
              "\n\n\t --BITMAP FILE HEADER--")

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bf_size], end=' ')
        print("\t\t=>Taille de Fichier = {} octets".format(
            str(get_int_from_bytes(self.bf_size.tolist()))))

        print(self.bf_size.tolist(), end=' ')
        print("\t=>Taille de Fichier = {} octets".format(
            str(get_int_from_bytes(self.bf_size.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bf_reserved1],
              end=' ')
        print("\t\t\t=>Application image (champ réservé 1) = {} noms".format(
            str(get_int_from_bytes(self.bf_reserved1.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bf_reserved2],
              end=' ')
        print("\t\t\t=>Application image (champ réservé 2) = {} noms".format(
            str(get_int_from_bytes(self.bf_reserved2.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bf_offbits], end=' ')
        print("\t\t=>Off Bits (adresse zone definition image) = {} octets".
              format(str(get_int_from_bytes(self.bf_offbits.tolist()))))

        print("\n\t --BITMAP INFO HEADER--")
        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_size], end=' ')
        print("\t\t=>Taille de l'entête BITMAP INFO HEADER = {} octets".format(
            str(get_int_from_bytes(self.bi_size.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_width], end=' ')
        print("\t\t=>Largeur image = {} octets".format(
            str(get_int_from_bytes(self.bi_width.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_height], end=' ')
        print("\t\t=>Hauteur image = {} octets".format(
            str(get_int_from_bytes(self.bi_height.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_planes], end=' ')
        print("\t\t\t=>NB plan image = {} plan".format(
            str(get_int_from_bytes(self.bi_planes.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_bitcount],
              end=' ')
        print("\t\t\t=>Nombre de bits par pixel = {} bits/pixel".format(
            str(get_int_from_bytes(self.bi_bitcount.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_compression],
              end=' ')
        print("\t\t=>Type de compression = {}\
               \n\t\t\t\t->0=pas de compression\
               \n\t\t\t\t->1=compressé à 8 bits par pixel\
               \n\t\t\t\t->2=compressé à 4 bits par pixel".format(
            str(get_int_from_bytes(self.bi_compression.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_sizeimage],
              end=' ')
        print("\t\t=>Taille des données de l'image = {} octets".format(
            str(get_int_from_bytes(self.bi_sizeimage.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_xpelspermeter],
              end=' ')
        print("\t\t=>Résolution horizontale axe X = {} pixels/mètre".format(
            str(get_int_from_bytes(self.bi_xpelspermeter.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_ypelspermeter],
              end=' ')
        print("\t\t=>Résolution verticale axe Y = {} pixels/mètre".format(
            str(get_int_from_bytes(self.bi_ypelspermeter.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_clrused], end=' ')
        print("\t\t=>Nombre de couleurs dans l'image = {}\
               \n\t\t\t\t->0=maximum possible\
               \n\t\t\t\t->Si une palette est utilisée, ce nombre indique\
               \n\t\t\t\t  le nombre de couleurs de la palette".format(
            str(get_int_from_bytes(self.bi_clrused.tolist()))))

        print(*[hex(x)[2:].upper().zfill(2) for x in self.bi_clrimportant],
              end=' ')
        print("\t\t=>Nombre de couleurs importantes dans l'image = {}\
               \n\t\t\t\t->0=toutes importantes".format(
            str(get_int_from_bytes(self.bi_clrimportant.tolist()))))
Exemplo n.º 8
0
    def save_image(self, output):
        '''
        Adjust header bytes and save image
        '''
        def verify_dimension_format(height, width):
            '''
            1. verify if each pixels can be written on 4 bytes
                - byte for the red channel
                - byte for the green channel
                - byte for the blue channel
                - reserved byte
            2. resize the picture if not
            '''
            new_height, new_width = height, width
            if height % 4 != 0:
                new_height = height + 4 - height % 4
            if width % 4 != 0:
                new_width = width + 4 - width % 4
            self.resize_image([new_width, new_height])

        if self.verbose == True:
            #-------performance calculation--------
            starttime = timeit.default_timer()
            print("Start saving time:", starttime)
            #--------------------------------------

        verify_dimension_format(
            np.shape(self.image_matrix)[0],
            np.shape(self.image_matrix)[1])

        # Adjust bf_size within header bytes (width x length x bitperpixel/8 + offbits)
        self.bf_size = []
        for i in (int(np.shape(self.image_matrix)[1]) *
                  int(np.shape(self.image_matrix)[0]) *
                  int(get_int_from_bytes(self.bi_bitcount.tolist()) / 8) +
                  int(get_int_from_bytes(self.bf_offbits.tolist()))).to_bytes(
                      4, byteorder='little'):
            self.bf_size.append(i)
        self.bf_size = np.array(self.bf_size)

        # Adjust bi_sizeimage within header bytes (width x length x bitperpixel/8)
        self.bi_sizeimage = []
        for i in (int(np.shape(self.image_matrix)[1]) *
                  int(np.shape(self.image_matrix)[0]) *
                  int(get_int_from_bytes(self.bi_bitcount.tolist()) /
                      8)).to_bytes(4, byteorder='little'):
            self.bi_sizeimage.append(i)
        self.bi_sizeimage = np.array(self.bi_sizeimage)

        # Adjust bi_width within header bytes
        bi_width = []
        for i in np.shape(self.image_matrix)[1].to_bytes(4,
                                                         byteorder='little'):
            bi_width.append(i)
        self.bi_width = np.array(bi_width)

        # Adjust bi_width within header bytes
        bi_height = []
        for i in np.shape(self.image_matrix)[0].to_bytes(4,
                                                         byteorder='little'):
            bi_height.append(i)
        self.bi_height = np.array(bi_height)

        # convert image matrix back into array of bytes
        flattened = np.array(self.image_matrix).flatten().tolist()
        # append header bytes into octets
        octets = self.octets[:get_int_from_bytes(self.bf_offbits.tolist()
                                                 )].tolist()
        # append image bytes into octets
        [octets.append(i) for i in flattened]
        self.octets = np.array(octets)

        # write bytes into output file
        f_output = open(output, 'wb')
        f_output.write(bytearray(self.bf_type.tolist()))
        f_output.write(bytearray(self.bf_size.tolist()))
        f_output.write(bytearray(self.bf_reserved1.tolist()))
        f_output.write(bytearray(self.bf_reserved2.tolist()))
        f_output.write(bytearray(self.bf_offbits.tolist()))
        f_output.write(bytearray(self.bi_size.tolist()))
        f_output.write(bytearray(self.bi_width.tolist()))
        f_output.write(bytearray(self.bi_height.tolist()))
        f_output.write(bytearray(self.bi_planes.tolist()))
        f_output.write(bytearray(self.bi_bitcount.tolist()))
        f_output.write(bytearray(self.bi_compression.tolist()))
        f_output.write(bytearray(self.bi_sizeimage.tolist()))
        f_output.write(bytearray(self.bi_xpelspermeter.tolist()))
        f_output.write(bytearray(self.bi_ypelspermeter.tolist()))
        f_output.write(bytearray(self.bi_clrused.tolist()))
        f_output.write(bytearray(self.bi_clrimportant.tolist()))
        f_output.write(bytearray(self.b_palette.tolist()))
        f_output.write(
            bytearray(self.octets[get_int_from_bytes(self.bf_offbits.tolist()
                                                     ):].tolist()))
        f_output.close
        if not self.verbose == 'test':
            print('generated image has been saved to {}'.format(output))

        if self.verbose == True:
            #-------performance calculation--------
            print("Saving duration:", timeit.default_timer() - starttime)
            print("Total process time", timeit.default_timer())
Exemplo n.º 9
0
    def fit_overlay(self, overlay_name):
        '''
        Fit Overlay image 
        '''

        if self.verbose == True:
            #-------performance calculation--------
            starttime = timeit.default_timer()
            print("Start fitting overlay time:", starttime)
            #--------------------------------------

        self.overlay_name = overlay_name
        #initialize overlay image
        f_lecture = open(self.overlay_name, 'rb')

        # append overlay header
        i = 0
        while (i < 54):
            octet = f_lecture.read(1)
            self.overlay_header.append(ord(octet))
            i += 1
        bf_size = get_int_from_bytes(self.overlay_header[2:6])
        bf_offbytes = get_int_from_bytes(self.overlay_header[10:14])

        # append palette
        while i < bf_offbytes:
            octet = f_lecture.read(1)
            self.overlay_palette.append(ord(octet))
            i += 1

        # append image
        while i < bf_size:
            octet = f_lecture.read(1)
            self.overlay_image.append(ord(octet))
            i += 1

        self.overlay_header = np.array(self.overlay_header)
        self.overlay_palette = np.array(self.overlay_palette)
        self.overlay_image = np.array(self.overlay_image)

        # fit image matrix with bitmap image bytes
        self.overlay_image_matrix = self.overlay_image.reshape(
            get_int_from_bytes(self.overlay_header[18:22].tolist()),
            get_int_from_bytes(self.overlay_header[22:26].tolist()),
            int(get_int_from_bytes(self.overlay_header[28:30].tolist()) / 8))

        self.resize_image([
            get_int_from_bytes(self.overlay_header[22:26].tolist()),
            get_int_from_bytes(self.overlay_header[18:22].tolist())
        ])

        if self.verbose == True:
            print('image to overload successfully loaded')
            #-------performance calculation--------
            print("Fitting duration:", timeit.default_timer() - starttime)
            #--------------------------------------

        if np.shape(self.overlay_image_matrix) != np.shape(self.image_matrix):
            print('Error: Require both input images to be the same dimension')
            print('{}: {}'.format(self.img, np.shape(self.image_matrix)))
            print('{}: {}'.format(self.overlay_name,
                                  np.shape(self.overlay_image_matrix)))
            f_lecture.close
            sys.exit(-1)

        f_lecture.close