def test_read(self): import pydicom import numpy as np ds = pydicom.read_file(self.file_path) image = DicomImage(self.file_path) np.testing.assert_equal(ds.pixel_array, image.read())
def process(self, image): ''' handler.process(image), oculta registros del EPR en la imagen y los anonimiza. Los registros se especifican en el data_handler ''' # anonimización file, epr = self.data_handler.anonimize(image) # Ocultacion del EPR y autenticacion new_image = DicomImage(file) msg = json.dumps(epr) data = new_image.read() watermarked_pixels = self.hider_handler.process(data, msg) new_image.write(watermarked_pixels) return new_image
def main(): # Keys key = "Aslorent7N;fpr-y5" base = os.path.dirname(__file__) # Directory dir = "tests/dicom" if not os.path.exists(dir): os.makedirs(dir) try: root = Tk() filename = filedialog.askopenfilenames( parent=root, initialdir=dir, title='Please select a directory') # Load cover image (array) cover = DicomImage(filename[0]) except Exception: raise ValueError("The image files were not loaded") root.destroy() # Creating matrix M_Metrics = [] # Creating directory dir_dat_file = os.path.join("dhdicom", "static", "Results") if not os.path.exists(dir_dat_file): os.makedirs(dir_dat_file) dir_dat_file = os.path.join(dir_dat_file, filename[0].split("/")[-2]) dir_dat_file = "%s_Results.dat" % dir_dat_file # Instance metr = Metrics() # Building stego images. Generating results for i in range(len(filename)): row = [] # Generating keys key = utils.sha256_to_key_bin(key) image = DicomImage(filename[i]) registers = ['PatientName', 'PatientID'] recipe = os.path.join(base, 'recipes/confidential') epr = EPRData(registers, recipe) hider = EPRHindingAndAuthentication(key) handler = DHDicomHandler(data_handler=epr, hider_handler=hider) new_image = handler.process(image) cover_array = image.read() watermarked_array = new_image.read() # Experimental analysis row.append(metr.psnr(cover_array, watermarked_array)) row.append(metr.uiqi(cover_array, watermarked_array)) row.append(metr.image_fid(cover_array, watermarked_array)) print(" ") print("Experimental analysis") print(" ") print("PSNR: ", row[0]) print(" ") print("UIQI: ", row[1]) print(" ") print("IF: ", row[2]) print(" ") # Creating cols M_Metrics.append(row) # Saving results np.savetxt(dir_dat_file, M_Metrics, fmt="%.9e") # Saving results np.savetxt(dir_dat_file, M_Metrics, fmt="%.9e")
class VentanaPrincipal(QMainWindow, Ui_Pruebas): def __init__(self, parent=None): # inicializar el padre super(VentanaPrincipal, self).__init__(parent) # configurar la interfaz self.setupUi(self) self.original_image = None self.watermarked_image = None self.hiddenEPRTable.setHorizontalHeaderLabels(["Register", "Value"]) self.eprTable.setHorizontalHeaderLabels(["Register", "Value"]) self.actionAbrir.triggered.connect(self.Cargar_imagen) self.actionSalvar.triggered.connect(self.Salvar_imagen) self.actionCropping.triggered.connect(self.crop_image) self.btn_procesar.clicked.connect(self.Procesar_imagen) self.btnExtractAuthenticate.clicked.connect(self.analizar) self.init_canvas() # Registros EPR base = os.path.dirname(os.path.dirname(__file__)) self.epr = EPRData(settings.EPR_TO_HIDE, settings.RECIPE_FILE) self.hider = EPRHindingAndAuthentication('nuevaclave') def Cargar_imagen(self): ruta_imagen = QFileDialog.getOpenFileName(self, u"Cargar Imágenes", QDir.homePath(), u"Imágenes (*.dcm)") self.clear_canvas() self.original_image = DicomImage(ruta_imagen) self.draw_image(self.dicom_canvas, self.original_image) data = self.epr.read(self.original_image) self.load_epr_data(data) def load_epr_data(self, data): rows_count = len(data) self.eprTable.clearContents() self.eprTable.setRowCount(rows_count) self.eprTable.setColumnCount(2) for row, key in enumerate(data): self.eprTable.setItem(row, 0, QTableWidgetItem(key)) self.eprTable.setItem(row, 1, QTableWidgetItem(data[key])) def load_epr_hidden(self, data): rows_count = len(data) self.hiddenEPRTable.clearContents() self.hiddenEPRTable.setRowCount(rows_count) self.hiddenEPRTable.setColumnCount(2) for row, key in enumerate(data): self.hiddenEPRTable.setItem(row, 0, QTableWidgetItem(key)) self.hiddenEPRTable.setItem(row, 1, QTableWidgetItem(data[key])) def init_canvas(self): pyplot.set_cmap(pyplot.gray()) # Original image figure = Figure() ax = figure.add_subplot(111) ax.set_aspect('equal', 'datalim') self.dicom_canvas = FigureCanvas(figure) # Watermarking image figure = Figure() ax = figure.add_subplot(111) ax.set_aspect('equal', 'datalim') self.watermarked_canvas = FigureCanvas(figure) self.canvasLayout.addWidget(self.dicom_canvas) self.canvasLayout.addWidget(self.watermarked_canvas) def draw_image(self, canvas, image): figure = canvas.figure ax = figure.get_axes()[0] ax.clear() ax.imshow(image.read()) canvas.draw() def Procesar_imagen(self): ouput = QInputDialog.getText(self, u"Hiding EPR", u"Enter a password", text="") clave = ouput[0] hider = EPRHindingAndAuthentication(clave) handler = DHDicomHandler(data_handler=self.epr, hider_handler=hider) image = handler.process(self.original_image) self.draw_image(self.watermarked_canvas, image) self.load_epr_data(self.epr.read(image)) self.load_epr_hidden(handler.get_epr(image)) self.watermarked_image = image def Salvar_imagen(self): dirName = QFileDialog.getExistingDirectory(self, u"Seleccionar ubicación", QDir.homePath(), QFileDialog.ShowDirsOnly) nombre = QInputDialog.getText(self, u"Nombre de la imagen", u"Escriba el nombre de la imagen", text="dhdicom") dir_imagen_guardada = '{}/{}.dcm'.format(dirName, nombre[0]) self.watermarked_image.save(dir_imagen_guardada) def analizar(self): output = QInputDialog.getText(self, u"Hiding EPR", u"Enter a password", text="") clave = output[0] hider = EPRHindingAndAuthentication(clave) self.draw_image(self.watermarked_canvas, self.original_image) handler = DHDicomHandler(data_handler=self.epr, hider_handler=hider) # Tamper dectection authentic, *l = handler.authenticate(self.original_image) if not authentic: block_manager = BlocksImage(self.original_image.read(), 32, 32) total_blocks = block_manager.max_num_blocks() modified_blocks = l[0] if modified_blocks: self.draw_tamper_regions(modified_blocks) image_modification = len(modified_blocks) / total_blocks if image_modification > 0.9: message = "Image is not authentic or its " \ "authenticity could not to be verified. " \ "View tamper region in right image. " \ "Make sure the password is correct." else: message = "Image is not authentic." \ "View tamper region in right image." else: message = "Image is authentic." # Extraccion del EPR try: data = handler.get_epr(self.original_image) self.load_epr_hidden(data) except json.JSONDecodeError: self.hiddenEPRTable.clearContents() QMessageBox.information(self, "Image authentication", message) def clear_canvas(self): pass def crop_image(self): x0, p, n = 0.47, 0.27, 15 z_block = [16, 32, 64] cover_array = np.copy(self.original_image.read()) # Selected blocks for i in range(n): # Instance j = z_block[i % 3] if len(cover_array.shape) == 2: blocks_instance = BlocksImage(cover_array, j, j) L = random_list(x0, p, list(range(blocks_instance.max_num_blocks()))) blocks_instance.set_block( cropping_noise(blocks_instance.get_block(L[i]), j, j), L[i]) else: blocks_instance = BlocksImage3D(cover_array, j, j) L = random_list( x0, p, list(range(blocks_instance.max_num_blocks_image_3d()))) blocks_instance.set_block_image_3d( cropping_noise(blocks_instance.get_block_image_3d(L[i]), j, j), L[i]) self.original_image.write(cover_array) self.draw_image(self.dicom_canvas, self.original_image) def draw_tamper_regions(self, block_indexes): block_image = BlocksImage(self.original_image.read(), 32, 32) figure = self.watermarked_canvas.figure ax = figure.get_axes()[0] block_width = 32 block_height = 32 for block_index in block_indexes: coords = block_image.get_coord(block_index) x = coords[2] y = coords[0] rect = Rectangle((x, y), block_width, block_height, linewidth=1, edgecolor='r', facecolor='none') ax.add_patch(rect) self.watermarked_canvas.draw()