Skip to content
Snippets Groups Projects
Select Git revision
  • master default
1 result

bit2image.py

Blame
  • bit2image.py 3.97 KiB
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # 
    # Copyright 2020
    #   Author: Gonzalo Belcredi, gbelcredi@fing.edu.uy
    #   Instituto de Ingenieria Electrica, Facultad de Ingenieria,
    #   Universidad de la Republica, Uruguay.
    # 
    # This is free software; you can redistribute it and/or modify
    # it under the terms of the GNU General Public License as published by
    # the Free Software Foundation; either version 3, or (at your option)
    # any later version.
    # 
    # This software is distributed in the hope that it will be useful,
    # but WITHOUT ANY WARRANTY; without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    # GNU General Public License for more details.
    # 
    # You should have received a copy of the GNU General Public License
    # along with this software; see the file COPYING.  If not, write to
    # the Free Software Foundation, Inc., 51 Franklin Street,
    # Boston, MA 02110-1301, USA.
    
    from PIL import Image
    import numpy as np
    import math
    
    filename_bin = 'dat/recepcion.dat'
    img_height = 800
    img_width = 549
    sync_start = [0,128,255]*10
    sync_size = 30
    
    array_rx = np.fromfile(filename_bin, dtype='uint8')
    columnas = img_height + sync_size
    filas = len(array_rx)/columnas
    
    DECODE_IMAGE = False
    
    def get_PSNR(image1,image2):
        value = 0
       
        matrix = np.asarray(image1, dtype="int8" )
        matrix_rx = np.asarray(image2, dtype="int8" )
    
        M = matrix.shape[0]
        N = matrix.shape[1]
    
        for i in range(0,M):
            for j in range(0,N):
                value += (float(matrix[i,j])-float(matrix_rx[i,j])) **2
    
        MSE = value /(M * N)
        if MSE < 10e-6:
            MSE = 10e-6
        PSNR = 10 * math.log10((2**8-1)/MSE)
        
        return MSE,PSNR
    
    def get_sync_peaks(signal, sync):
        """!@brief Devuelve los indices de comienzo del cuadro de sincronización.
        @param signal Señal
        @param sync Vector de sincronización
        @result peaks Indices de sincronización.
        """
        # list of maximum correlations found: (index, value)
        peaks_corr = [(0, 0)]
    
        # minimum distance between peaks
        mindistance = columnas*img_width - 1000
    
        # need to shift the values down to get meaningful correlation values
        signalshifted = [x-128 for x in signal]
        sync = [x-128 for x in sync]
    
        for i in range(0,len(signalshifted) - len(sync)):
    
            corr = np.dot(sync, signalshifted[i : i+len(sync)])
    
            # if previous peak is too far, keep it and add this value to the
            # list as a new peak
            if i - peaks_corr[-1][0] > mindistance:
                peaks_corr.append((i, corr))
    
            # else if this value is bigger than the previous maximum, set this
            # one
            elif corr > peaks_corr[-1][1]:
                peaks_corr[-1] = (i, corr)
    
        peaks = [i[0] for i in peaks_corr] # retrieve peak indexes from peaks_corr
        
        return peaks 
    
    
    ''' Visualización de señal en recepción '''
    
    array_rx = array_rx[0:filas*columnas]
    image_rx=np.reshape(array_rx,(filas, columnas))
    image = Image.fromarray(image_rx.astype('uint8'))
    image.save('images/imagen_recibida.png')
    image.show()
    
    
    if DECODE_IMAGE:
        peaks = get_sync_peaks(array_rx,sync_start)
        nr_images = len(peaks)
        print("Se identificaron ", nr_images, " imágenes.")
        print("Indices de comienzo de imagen:", peaks)
    
        for i in range(0,nr_images):
            if (peaks[i]+img_width*columnas) < len(array_rx):
                array = array_rx[peaks[i]:peaks[i]+img_width*columnas]
                matrix = np.reshape(array,(img_width, columnas))
    
                ''' Quito el frame de sincronización para recuperar la imagen original'''
                matrix_deframed = matrix[:,30:]
                image = Image.fromarray(matrix_deframed.astype('uint8'))
                image.save('images/imagen_recibida_'+str(i+1)+'.png')
                image.show()
    
    
        ''' Calculo MSE y PSNR '''
        img = Image.open('images/image.png' )
        img_rx = Image.open('images/imagen_recibida_1.png') #Seleccionar aquí la imagen correspondiente
        img.load()
        img_rx.load()
    
        MSE, PSNR = get_PSNR(img,img_rx)
        print("MSE: ", MSE)
        print("PSNR (dB): ", PSNR)