예제 #1
0
파일: test_epr.py 프로젝트: ydiazn/dhdicom
    def test_anonimization_sucess(self):
        import pydicom

        registers = ['PatientName', 'PatientID']
        recipe = os.path.join(self.base, 'recipes/confidential')
        handler = EPRData(registers, recipe)

        # Verifica que efectivamente la imagen original tiene
        # los registros PatientName y PatientID
        self.image.PatientName
        self.image.PatientID

        file, data = handler.anonimize(self.image)

        # Verifica la eliminación de dichos registros tras la anonimización
        ds = pydicom.read_file(file)
        with self.assertRaises(AttributeError):
            ds.PatientName
        with self.assertRaises(AttributeError):
            ds.PatientID

        # Verificacion de los valores de los registros extraidos
        self.assertDictEqual(data, {
            'PatientName': 'FRANCISCO^ALVARES^QUESAD',
            'PatientID': 'HCMC-18-5456'
        }, 'Error extracting confidential data from image')
예제 #2
0
파일: test_epr.py 프로젝트: ydiazn/dhdicom
    def test_load_all_data_success(self):

        registers = ['PatientName', 'PatientID']
        recipe = os.path.join(self.base, 'recipes/confidential')
        handler = EPRData(registers, recipe)
        data = handler.read(self.image)
        self.assertDictEqual(data, {
            'PatientName': 'FRANCISCO^ALVARES^QUESAD',
            'PatientID': 'HCMC-18-5456'
        }, 'Error extracting confidential data from image')
예제 #3
0
파일: test_epr.py 프로젝트: ydiazn/dhdicom
    def test_an_incorrect_register(self):
        from dhdicom.exceptions import RegisterNotFound

        registers = ['PatientName', 'PatientData']
        recipe = os.path.join(self.base, 'recipes/confidential')
        handler = EPRData(registers, recipe)
        data = handler.read(self.image)
        self.assertDictEqual(data, {
            'PatientName': 'FRANCISCO^ALVARES^QUESAD',
            'PatientData': None
        }, 'Error extracting confidential data from image')
예제 #4
0
    def test_not_authentic_image(self):
        from dhdicom.hidding.mixed import EPRHindingAndAuthentication
        import pydicom

        filename = os.path.join(self.base, 'images/2.dcm')
        image = DicomImage(filename)
        ds = pydicom.read_file(filename)

        dimesions = ds.Rows, ds.Columns

        registers = ['PatientName', 'PatientID']
        recipe = os.path.join(self.base, 'recipes/confidential')
        epr = EPRData(registers, recipe)
        hider = EPRHindingAndAuthentication('nuevaclave')

        handler = DHDicomHandler(data_handler=epr, hider_handler=hider)
        new_image = handler.process(image)

        # Image Tampering
        x = dimesions[0] - 1
        y = dimesions[1] - 1
        pixels = new_image.read()
        pixels[0][0] += 1
        pixels[x][y] += 1
        new_image.write(pixels)

        # Despues del procesamiento los pixeles se modificaron
        authentic, blocks_tampered = handler.authenticate(new_image)
        self.assertFalse(authentic)
        # image size: 255x255, block size:32x32, block num: 255
        np.testing.assert_array_equal(blocks_tampered, np.array([0, 255]))
예제 #5
0
    def test_get_message(self):
        from dhdicom.hidding.mixed import EPRHindingAndAuthentication
        import pydicom

        filename = os.path.join(self.base, 'images/2.dcm')
        image = DicomImage(filename)
        ds = pydicom.read_file(filename)

        registers = ['PatientName', 'PatientID']
        patient_name = ds.PatientName
        patient_id = ds.PatientID

        recipe = os.path.join(self.base, 'recipes/confidential')
        epr = EPRData(registers, recipe)
        data = epr.read(image)
        hider = EPRHindingAndAuthentication('nuevaclave')

        handler = DHDicomHandler(data_handler=epr, hider_handler=hider)
        new_image = handler.process(image)

        self.assertEqual(data, handler.get_epr(new_image))
예제 #6
0
    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')
예제 #7
0
    def test_authentic_image(self):
        from dhdicom.hidding.mixed import EPRHindingAndAuthentication

        filename = os.path.join(self.base, 'images/2.dcm')
        image = DicomImage(filename)

        registers = ['PatientName', 'PatientID']
        recipe = os.path.join(self.base, 'recipes/confidential')
        epr = EPRData(registers, recipe)
        hider = EPRHindingAndAuthentication('nuevaclave')

        handler = DHDicomHandler(data_handler=epr, hider_handler=hider)
        new_image = handler.process(image)

        authentic, *l = handler.authenticate(new_image)
        self.assertTrue(authentic)
        # No hay bloques modificados
        self.assertFalse(l)
예제 #8
0
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")
예제 #9
0
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()