def extract(self, watermarked_image): import cv2 # To array watermarked_array = misc.fromimage(watermarked_image) modifiedBlocks = [] # components for i in range(3): component = watermarked_array[:, :, i] m = self.extractFromComponent(component) modifiedBlocks += m modifiedBlocks = list(set(modifiedBlocks)) # Dividing in 32x32 blocks blocks32x32 = BlocksImage(watermarked_array, 32, 32) for item in modifiedBlocks: coord = blocks32x32.get_coord(item) for x in range(32): for y in range(32): watermarked_array[coord[0]+x, coord[1]+y] = [0, 255, 0] cv2.rectangle( watermarked_array, (coord[1], coord[0]), (coord[3], coord[2]), (0, 255, 0), 1) return Image.fromarray(watermarked_array)
def main(): try: # Load cover image root = Tk() root.filename = filedialog.askopenfilename( initialdir="static/", title="Select file", filetypes=(("png files", "*.jpg"), ("jpg files", "*.png"), ("all files", "*.*"))) cover_image = Image.open(root.filename).convert('RGB') # Creando path para almacebar los bloques de esta imagen b_path = 'static/' + root.filename.split('/')[-1][:-4] + '/' try: os.stat(b_path) except Exception as e: os.mkdir(b_path) root.destroy() except Exception as e: root.destroy() print("Error: ", e) print("The image file was not loaded") # Instance a la clase Bloque cover_array = np.asarray(cover_image) blocks = BlocksImage(cover_array) random_blocks = [i for i in range(blocks.max_num_blocks())] random.shuffle(random_blocks) for i in range(blocks.max_num_blocks()): print("Block #: ", random_blocks[i] + 1) block_array = blocks.get_block(random_blocks[i] + 1) # Save block image block_image = Image.fromarray(block_array, 'RGB') block_path = b_path + str(i) + '.png' block_image.save(block_path) # Clasificacion del block clasificador = clasificar(block_path) print(clasificador) class_path = b_path + str(clasificador['c']) + '_' + str( clasificador['delta']) + '/' if len(clases) == 0: # Add como clase 1 os.mkdir(class_path) clases['1'] = [clasificador['c'], clasificador['delta']] block_image = Image.open(block_path).save(class_path + str(i) + '.png') elif is_in_clases([clasificador['c'], clasificador['delta']]): # Add a la clase correspondiente block_image = Image.open(block_path).save(class_path + str(i) + '.png') else: # Add clase clases[len(clases) + 1] = [clasificador['c'], clasificador['delta']] os.mkdir(class_path) block_image = Image.open(block_path).save(class_path + str(i) + '.png') print("Clases: ", clases)
def extract(self, watermarked_image): print("...Proceso de extraccion...") # Instancias necesarias itools = ImageTools() print("Convirtiendo a YCbCr") # Convirtiendo a modelo de color YCbCr watermarked_ycbcr_array = itools.rgb2ycbcr(watermarked_image) # Tomando componente Y watermarked_array = watermarked_ycbcr_array[:, :, 0] bt_of_watermarked_Y = BlocksImage(watermarked_array) extract = [] print("Extrayendo") # Recorrer todos los bloques de la imagen for i in range(self.len_watermark_list): block = bt_of_watermarked_Y.get_block(self.pos[i]) # Valores de coeficiente y delta optimo para el bloque (c, delta) = self.clasificar(self.pos[i], watermarked_image) dqkt_block = DqKT().dqkt2(np.array(block, dtype=np.float32)) negative = False (px, py) = self.get_indice(c) if dqkt_block[px, py] < 0: negative = True C1 = (2*delta*round(abs(dqkt_block[px, py])/(2.0*delta)) + delta/2.0) - abs(dqkt_block[px, py]) C0 = (2*delta*round(abs(dqkt_block[px, py])/(2.0*delta)) - delta/2.0) - abs(dqkt_block[px, py]) if negative: C1 *= -1 C0 *= -1 if C0 < C1: extract.append(0) else: extract.append(1) wh = int(math.sqrt(self.len_watermark_list)) extract_image = Image.new("1", (wh, wh), 255) array_extract_image1 = misc.fromimage(extract_image) for i in range(wh): for y in range(wh): if extract[wh*i+y] == 0: array_extract_image1[i, y] = 0 watermark_extracted = misc.toimage(array_extract_image1) for i in range(10): watermark_extracted = DAT().dat2(watermark_extracted) return watermark_extracted
def insert(self, cover_image): # Image to array cover_array = np.asarray(cover_image) # Blue component blue_cover_array = cover_array[:, :, 2] blue_cover_array.setflags(write=1) # Dividing in 32x32 blocks blocks32x32 = BlocksImage(blue_cover_array, 32, 32) # Touring each block 32x32 for num_block in range(blocks32x32.max_num_blocks()): # Copying block 32x32 blocksCopy32x32 = deepcopy(blocks32x32.get_block(num_block)) # Dividing in 16x16 blocks blocksCopy16x16 = BlocksImage(blocksCopy32x32, 16, 16) # Get first block first_block = blocksCopy16x16.get_block(0) # Pariar for i in range(16): for y in range(16): if (first_block[i, y] % 2) == 1: first_block[i, y] -= 1 # Hash of blocksCopy32x32 pareado blocksHash = utils.sha256Binary(blocksCopy32x32.tolist()) # Insert data for i in range(16): for y in range(16): first_block[i, y] += int(blocksHash[16 * i + y]) # Update block blocks32x32.set_block(blocksCopy32x32, num_block) watermarked_image = Image.fromarray(cover_array) return watermarked_image
def extractFromComponent(self, component_cover_array): # Dividing in 32x32 blocks blocks32x32 = BlocksImage(component_cover_array, 32, 32) # Touring each block 32x32 modifiedBlocks = [] for num_block in range(blocks32x32.max_num_blocks()): # Copying block 32x32 blockCopy32x32 = deepcopy(blocks32x32.get_block(num_block)) # Dividing in 16x16 blocks blocksCopy16x16 = BlocksImage(blockCopy32x32, 16, 16) # Get first block first_block = blocksCopy16x16.get_block(0) # Watermark w = '' # Pariar for i in range(16): for y in range(16): if (first_block[i, y] % 2) == 1: first_block[i, y] -= 1 w += '1' else: w += '0' # Hash of blocksCopy32x32 pareado blocksHash = utils.sha256Binary(blockCopy32x32.tolist()) if w != blocksHash: modifiedBlocks.append(num_block) return modifiedBlocks
def clasificar(self, num_block, cover_image): # Instancia necesaria clasification = Clasification() bt_of_rgb_cover = BlocksImage(misc.fromimage(cover_image)) # Predict p = clasification.predict(bt_of_rgb_cover.get_block(num_block)) if p == 1: return (17, 90) elif p == 4: return (19, 60) elif p == 5: return (20, 130) elif p == 7: return (28, 94) elif p == 8: return (34, 130) else: return (19, 130)
def sprint(path): cover_image = Image.open(path).convert('RGB') # Creando path para almacenar los bloques de esta imagen b_path = 'static/' + path.split('/')[-1][:-4] + '/' try: os.stat(b_path) except Exception: os.mkdir(b_path) # Instance a la clase Bloque cover_array = np.asarray(cover_image) blocks = BlocksImage(cover_array) random_blocks = [i for i in range(blocks.max_num_blocks())] random.shuffle(random_blocks) for i in range(blocks.max_num_blocks()): block_array = blocks.get_block(random_blocks[i]) # Save block image block_image = Image.fromarray(block_array, 'RGB') block_path = b_path + str(random_blocks[i]) + '.png' try: os.stat(block_path) print("Ya existe: ", block_path) except Exception: block_image.save(block_path) # Clasificacion del block clasificador = clasificar(block_path) # print(clasificador) class_path = b_path + str(clasificador['c']) + '_' + str( clasificador['delta']) + '/' try: os.stat(class_path) except Exception: os.mkdir(class_path) Image.open(block_path).save(class_path + str(random_blocks[i]) + '.png')
def extract(self, watermarked_image): import cv2 # To array watermarked_array = np.asarray(watermarked_image) modifiedBlocks = [] # components for i in range(3): component = watermarked_array[:, :, i] component.setflags(write=1) m = self.extractFromComponent(component) modifiedBlocks += m modifiedBlocks = list(set(modifiedBlocks)) print(modifiedBlocks) # Dividing in 32x32 blocks blocks32x32 = BlocksImage(watermarked_array, 32, 32) for item in modifiedBlocks: coord = blocks32x32.get_coord(item) cv2.rectangle(watermarked_array, (coord[1], coord[0]), (coord[3], coord[2]), (0, 255, 0), 1) return Image.fromarray(watermarked_array)
def insert(self, cover_image): print("...Proceso de insercion...") # Instancias necesarias itools = ImageTools() print("Convirtiendo a YCbCr") # Convirtiendo a modelo de color YCbCr cover_ycbcr_array = itools.rgb2ycbcr(cover_image) # Obteniendo componente Y cover_array = cover_ycbcr_array[:, :, 0] # Objeto de la clase Bloque bt_of_cover = BlocksImage(cover_array) # Generando bloques a marcar print("Generando bloques a marcar") self.generar(bt_of_cover.max_num_blocks()) print("Marcando") # Marcar los self.len_watermark_list bloques for i in range(self.len_watermark_list): block = bt_of_cover.get_block(self.pos[i]) # Calculando DCT dct_block = DCT().dct2(block) c = self.c delta = self.delta # negative = False (px, py) = self.get_indice(c) # if dct_block[px, py] < 0: # negative = True if self.watermark_list[i % self.len_watermark_list] == 0: # Bit a insertar 0 dct_block[px, py] = 2*delta*round(abs(dct_block[px, py])/(2.0*delta)) - delta/2.0 else: # Bit a insertar 1 dct_block[px, py] = 2*delta*round(abs(dct_block[px, py])/(2.0*delta)) + delta/2.0 # if negative: # dct_block[px, py] *= -1 idct_block = DCT().idct2(dct_block) bt_of_cover.set_block(idct_block, self.pos[i]) print("Convirtiendo a RGB") image_rgb_array = itools.ycbcr2rgb(cover_ycbcr_array) return Image.fromarray(image_rgb_array)
def extract(self, watermarked_image): # Instancias necesarias itools = ImageTools() # Convirtiendo a modelo de color YCbCr watermarked_ycbcr_array = itools.rgb2ycbcr(watermarked_image) # Tomando componente Y watermarked_array = watermarked_ycbcr_array[:, :, 0] # Wavelet Transform LL, [LH, HL, HH] = pywt.dwt2(watermarked_array, 'haar') colums = len(LL[0]) extract = [] # Extracting # Dividiendo LL en bloques de 8x8 bt_of_LL = BlocksImage(LL) for i in range(bt_of_LL.max_num_blocks()): # Cuantificado QLL = utils.quantification(bt_of_LL.get_block(i), self.Q) # replaced directly by the resulting Q-LL bt_of_LL.set_block(QLL, i) for i in range(self.len_watermark_list): # Extrayendo px = self.pos[i] // colums py = self.pos[i] - (px * colums) extract.append(abs(round((HH[px, py] - LL[px, py]) / self.k))) # for i in range(self.len_watermark_list + 1): # # Marcado # if i > 0: # px = i // colums # py = i - (px * colums) # extract.append(abs(round((HH[px, py] - LL[px, py])/self.k))) wh = int(math.sqrt(self.len_watermark_list)) extract_image1 = Image.new("L", (wh, wh), 255) array_extract_image = misc.fromimage(extract_image1) for i in range(wh): for y in range(wh): if extract[wh * i + y] == 0: array_extract_image[i, y] = 0 watermark_extracted = misc.toimage(array_extract_image) return watermark_extracted
def insertInComponent(self, component_cover_array): # Dividing in 32x32 blocks blocks32x32 = BlocksImage(component_cover_array, 32, 32) # Touring each block 32x32 for num_block in range(blocks32x32.max_num_blocks()): # Copying block 32x32 blocksCopy32x32 = deepcopy(blocks32x32.get_block(num_block)) # Dividing in 16x16 blocks blocksCopy16x16 = BlocksImage(blocksCopy32x32, 16, 16) # Get first block first_block = blocksCopy16x16.get_block(0) # Pariar for i in range(16): for y in range(16): if (first_block[i, y] % 2) == 1: first_block[i, y] -= 1 # Hash of blocksCopy32x32 pareado blocksHash = utils.sha256Binary(blocksCopy32x32.tolist()) # Insert data for i in range(16): for y in range(16): first_block[i, y] += int(blocksHash[16*i + y]) # Update block blocks32x32.set_block(blocksCopy32x32, num_block)
def extract(self, watermarked_image): import cv2 # To array watermarked_array = np.asarray(watermarked_image) # Blue component blue_watermarked_array = watermarked_array[:, :, 2] blue_watermarked_array.setflags(write=1) blue_watermarked_array_noise = blue_watermarked_array.copy() # Dividing in 32x32 blocks blocks32x32 = BlocksImage(blue_watermarked_array_noise, 32, 32) # Touring each block 32x32 modifiedBlocks = [] for num_block in range(blocks32x32.max_num_blocks()): # Copying block 32x32 blockCopy32x32 = deepcopy(blocks32x32.get_block(num_block)) # Dividing in 16x16 blocks blocksCopy16x16 = BlocksImage(blockCopy32x32, 16, 16) # Get first block first_block = blocksCopy16x16.get_block(0) # Watermark w = '' # Pariar for i in range(16): for y in range(16): if (first_block[i, y] % 2) == 1: first_block[i, y] -= 1 w += '1' else: w += '0' # Hash of blocksCopy32x32 pareado blocksHash = utils.sha256Binary(blockCopy32x32.tolist()) if w != blocksHash: modifiedBlocks.append(num_block) print(modifiedBlocks) for item in modifiedBlocks: coord = blocks32x32.get_coord(item) cv2.rectangle(watermarked_array, (coord[1], coord[0]), (coord[3], coord[2]), (0, 255, 0), 1) return Image.fromarray(watermarked_array)
def insert(self, cover_image): print("...Proceso de insercion...") # Instancias necesarias itools = ImageTools() print("Convirtiendo a YCbCr") # Convirtiendo a modelo de color YCbCr cover_ycbcr_array = itools.rgb2ycbcr(cover_image) # Obteniendo componente Y cover_array = cover_ycbcr_array[:, :, 0] # Objeto de la clase Bloque bt_of_cover = BlocksImage(cover_array) # Generando bloques a marcar print("Generando bloques a marcar") self.generar(bt_of_cover.max_num_blocks()) print("Marcando") # Marcar los self.len_watermark_list bloques for i in range(self.len_watermark_list): block = bt_of_cover.get_block(self.pos[i]) # Valores de coeficiente y delta optimo para el bloque (c, delta) = self.clasificar(self.pos[i], cover_image) # Calculando Krawchout Transform dqkt_block = DqKT().dqkt2(block) negative = False (px, py) = self.get_indice(c) if dqkt_block[px, py] < 0: negative = True if self.watermark_list[i % self.len_watermark_list] == 0: # Bit a insertar 0 dqkt_block[px, py] = 2*delta*round(abs(dqkt_block[px, py])/(2.0*delta)) + delta/2.0 else: # Bit a insertar 1 dqkt_block[px, py] = 2*delta*round(abs(dqkt_block[px, py])/(2.0*delta)) - delta/2.0 if negative: dqkt_block[px, py] *= -1 idqkt_block = DqKT().idqkt2(dqkt_block) inv = idqkt_block for x in range(8): for y in range(8): if (inv[x, y] - int(inv[x, y])) < 0.5: inv[x, y] = int(inv[x, y]) else: inv[x, y] = int(inv[x, y]) + 1 if inv[x, y] > 255: inv[x, y] = 255 if inv[x, y] < 0: inv[x, y] = 0 bt_of_cover.set_block(idqkt_block, self.pos[i]) print("Convirtiendo a RGB") image_rgb_array = itools.ycbcr2rgb(cover_ycbcr_array) return Image.fromarray(image_rgb_array)
def insert(self, cover_image): # Instancia itools = ImageTools() print("Convirtiendo a YCbCr") # Convirtiendo a modelo de color YCbCr cover_ycbcr_array = itools.rgb2ycbcr(cover_image) # Obteniendo componente Y cover_array = cover_ycbcr_array[:, :, 0] print("DWT") # DWT LL, [LH, HL, HH] = pywt.dwt2(cover_array, 'haar') # Generando posiciones a utilizar self.generar(LL.size) # Dividiendo LL en bloques de 8x8 bt_of_LL = BlocksImage(LL) bt_of_HH = BlocksImage(HH) print("Re-asignando subbanda HH") for i in range(bt_of_LL.max_num_blocks()): # Cuantificado QLL = utils.quantification(bt_of_LL.get_block(i), self.Q) # replaced directly by the resulting Q-LL bt_of_HH.set_block(QLL, i) QWLL = np.copy(HH) # QWLL = np.full_like(HH) print("Modificando LL") for i in range(self.len_watermark_list): colums = len(LL[0]) # Marcado px = self.pos[i] // colums py = self.pos[i] - (px * colums) QWLL[px, py] = HH[px, py] + self.watermark_list[i] / 255 * self.k # print("Modificando LL") # for i in range(self.len_watermark_list + 1): # colums = len(LL[0]) # # Marcado # if i > 0: # px = i // colums # py = i - (px * colums) # LL[px, py] += self.watermark_list[i-1]/255 * self.k bt_of_QWLL = BlocksImage(QWLL) for i in range(bt_of_LL.max_num_blocks()): # Descuantificando UQWLL = utils.unquantification(bt_of_QWLL.get_block(i), self.Q) # replaced directly by the resulting Q-LL bt_of_LL.set_block(UQWLL, i) # Inverse transform print("IDWT") cover_ycbcr_array[:, :, 0] = pywt.idwt2((LL, (LH, HL, HH)), 'haar') print("Convirtiendo a RGB") image_rgb_array = itools.ycbcr2rgb(cover_ycbcr_array) return Image.fromarray(image_rgb_array)
def extract(self, watermarked_image): c = self.c delta = self.delta print("...Proceso de extraccion...") # Instancias necesarias itools = ImageTools() print("Convirtiendo a YCbCr") # Convirtiendo a modelo de color YCbCr watermarked_ycbcr_array = itools.rgb2ycbcr(watermarked_image) # Tomando componente Y watermarked_array = watermarked_ycbcr_array[:, :, 0] bt_of_watermarked_Y = BlocksImage(watermarked_array) extract = [] print("Extrayendo") # Recorrer todos los bloques de la imagen for i in range(self.len_watermark_list): block = bt_of_watermarked_Y.get_block(self.pos[i]) dct_block = DCT().dct2(block) negative = False (px, py) = self.get_indice(c) if dct_block[px, py] < 0: negative = True C1 = (2*delta*round(abs(dct_block[px, py])/(2.0*delta)) + delta/2.0) - abs(dct_block[px, py]) C0 = (2*delta*round(abs(dct_block[px, py])/(2.0*delta)) - delta/2.0) - abs(dct_block[px, py]) if negative: C1 *= -1 C0 *= -1 if (dct_block[px, py] - C0) < (dct_block[px, py] - C1): extract.append(0) else: extract.append(1) wh = int(math.sqrt(self.len_watermark_list)) extract_image = Image.new("1", (wh, wh), 255) array_extract_image1 = misc.fromimage(extract_image) for i in range(wh): for y in range(wh): if extract[wh*i+y] == 0: array_extract_image1[i, y] = 0 # myqr1 = MyQR62() watermark_extracted = misc.toimage(array_extract_image1) for i in range(10): watermark_extracted = DAT().dat2(watermark_extracted) # # Utilizacion de caracteristica de QR code # array = misc.fromimage(watermark_extracted) # watermark_extracted = misc.toimage( # myqr1.get_resconstructed(array)) # b = BlocksImage(misc.fromimage(watermark_extracted), 2, 2) # for m in range(b.max_num_blocks()): # b.set_color(m) # watermark_extracted = misc.toimage(b.get()) return watermark_extracted