// Calcula el histograma de la region 'area' del filtro 'numFiltro', devolviendo los valores en 'histo', 'media' y 'sigma'
// El histograma se devuelve con NUM_VALORES_HISTO valores independientemente de la profundidad de la imagen 
// nBitsImagen - profundidad en bits de las imagenes. Hay que tener esto en cuenta para transformar histograma a NUM_VALORES_HISTO
// Devuelve false si la imagen correspondiente no esta disponible
bool ControlImagenes::CalculaHistograma(int numFiltro, const CRect& area, int nBitsImagen, long* histo, double& moda, double& sigma, int &nPercentilInf, int &nPercentilSup)
{
    MIL_ID  M_AreaAux;
    double media;

    int nValorMaxImagen = 1<<nBitsImagen;
    long * histoImagen = new long [nValorMaxImagen]; //histograma auxiliar con TODOS los valores de gris de la imagen

    memset(histo,0,NUM_VALORES_HISTO*sizeof(long)); //inicializamos

    if (m_Milimagen[numFiltro-1] != M_NULL)
    {
	    MbufChild2d(m_Milimagen[numFiltro-1], area.left, area.top,area.right - area.left, area.bottom - area.top, &M_AreaAux);
        if (EvaluaHistograma(M_AreaAux,histoImagen, nValorMaxImagen))
        {
            MbufFree(M_AreaAux);
            // calcular histograma con NUM_VALORES_HISTO
            if (NUM_VALORES_HISTO < nValorMaxImagen)
            {
                int nValoresAgrupar = nValorMaxImagen / NUM_VALORES_HISTO; //numero de valores a sumar para agrupar 
                for (int i = 0; i<NUM_VALORES_HISTO; i++)
                {
                    for (int j=0;j<nValoresAgrupar;j++)
                        histo[i] += histoImagen[i*nValoresAgrupar + j];
                }
            }
            else
            {
                memcpy(histo,histoImagen,nValorMaxImagen*sizeof(long));
            }
            delete [] histoImagen;

            procesa_histograma(histo,&media,&sigma);
            moda = moda_histograma(histo, 0, NUM_VALORES_HISTO-1);
            nPercentilInf = percentil_histograma(histo,NUM_VALORES_HISTO,5);
            nPercentilSup = percentil_histograma(histo,NUM_VALORES_HISTO,95);
            return true;
        }
        else
        {
            MbufFree(M_AreaAux);
            delete [] histoImagen;
            return false;
        }
    }
    else
    {
        delete [] histoImagen;
        return false;
    }
}
/**************************  fin_TomaPatrones  ******************************
*****************************************************************************/
int fin_TomaPatrones(int num_bandas)
{
	int i;

	for (i=0; i < num_bandas; i++)
    {
		MbufFree(M_banda_enmascarada_acum[i]);
		MbufFree(M_banda_acum[i]);
        MbufFree(M_cont_campos[i]);
    }
    MbufFree(M_mascara_aux);
    MbufFree(M_acum_aux);

	return 0;
}
Esempio n. 3
0
bool MdispGtkView::saveROIAs(const char *filename)
   {
   /////////////////////////////////////////////////////////////////////////
   // MIL: Get current ROI in buffer-related coordinates.
   /////////////////////////////////////////////////////////////////////////
   MIL_INT OffsetX   = MdispInquire(m_MilDisplay, M_ROI_BUFFER_OFFSET_X, M_NULL);
   MIL_INT OffsetY   = MdispInquire(m_MilDisplay, M_ROI_BUFFER_OFFSET_Y, M_NULL);
   MIL_INT SizeX     = MdispInquire(m_MilDisplay, M_ROI_BUFFER_SIZE_X, M_NULL);
   MIL_INT SizeY     = MdispInquire(m_MilDisplay, M_ROI_BUFFER_SIZE_Y, M_NULL);
      
   /////////////////////////////////////////////////////////////////////////
   // MIL: Create a child of the selected buffer, with the ROI coordinates.
   /////////////////////////////////////////////////////////////////////////
   MIL_ID ChildBuffer = MbufChildColor2d(m_MilImage,
                                         M_ALL_BANDS, 
                                         OffsetX, 
                                         OffsetY, 
                                         SizeX, 
                                         SizeY,
                                         M_NULL);

   /////////////////////////////////////////////////////////////////////////
   // MIL: Save the buffer in the path given by the user.
   /////////////////////////////////////////////////////////////////////////
   MbufSave(filename, ChildBuffer);
   MbufFree(ChildBuffer);
   return true;
   }
Esempio n. 4
0
void calcula_y_guarda_AOI(FILE* fich_AOI, parametros& param, MIL_ID Mbanda)
{
    MIL_ID  M_Centro;
    long histo[NUMVAL];
    double media,sigma;
    static bool bPrimeraVez = true;

    if (bPrimeraVez) //primera vez de esta "sesion"
    {
        // Escribir cabecera en el fichero
        bPrimeraVez = false;

        // Get local time
        time_t rawtime;
        struct tm * timeinfo;
        time ( &rawtime );
        timeinfo = localtime ( &rawtime );

        fprintf(fich_AOI, "\n%s - Reflectancias medias y sigmas de regiones de interes\n",asctime (timeinfo));        
    }

	MbufChild2d(Mbanda, param.Cam.anchoImagen/2 - m_nAnchoAOI/2, param.Cam.altoImagen/2 - m_nAnchoAOI/2,
		m_nAnchoAOI, m_nAnchoAOI, &M_Centro);
    evalua_histograma(M_Centro,histo);
    MbufFree(M_Centro);
    procesa_histograma(histo,&media,&sigma);
    if (BITS_CAMARA == 12) 
        fprintf(fich_AOI, "%.2lf\t%.2lf\t",media*param.escala/16,sigma*param.escala/16);        
    else 
        fprintf(fich_AOI, "%.2lf\t%.2lf\t",media*param.escala,sigma*param.escala);        

}
void ControlImagenes::EliminarTodas()
{
    if (M_overlay_normal != M_NULL)
    {
        MbufClear(M_overlay_normal, TRANSPARENTE );// Relleno el buffer overlay con el color TRANSPARENTE
        M_overlay_normal = M_NULL;
    }


    MIL_ID selected;
    MdispInquire(m_Mildisplay,M_SELECTED,&selected);
    if (selected!=M_NULL)
        MdispDeselect(m_Mildisplay,selected);

    for (int i=0;i<MAX_NUM_IMAGENES;i++)
    {
        if (m_Milimagen[i] != M_NULL)
        {
            MbufFree(m_Milimagen[i]);
            m_Milimagen[i] = M_NULL;
        }
    }
    m_numImagenes = 0;

    //Liberamos RGB
    if (m_MilRGB != M_NULL)
    {
        MbufFree(m_MilRGB);
        m_MilRGB = M_NULL;
    }

    //Liberamos imagen identificacion
    if (M_Clasificacion != M_NULL)
    {
        MbufFree(M_Clasificacion);
        M_Clasificacion = M_NULL;
    }
    if (m_bufClasificacionSelectiva != NULL)
    {
        delete [] m_bufClasificacionSelectiva;
        m_bufClasificacionSelectiva = NULL;
    }
    theApp.clasificacion.Liberar();
}
ControlImagenes::~ControlImagenes()
{
    for (int i=0;i<MAX_NUM_IMAGENES;i++)
    {
        if (m_Milimagen[i] != M_NULL)
            MbufFree(m_Milimagen[i]);
    }
    if (m_MilRGB != M_NULL)
        MbufFree(m_MilRGB);

    // CLASIFICACION
    if(M_Clasificacion!=M_NULL)
        MbufFree(M_Clasificacion);
    if (m_bufClasificacionSelectiva != NULL)
        delete [] m_bufClasificacionSelectiva;

    MdispFree(m_Mildisplay);
    //MsysFree(m_Milsistema);
    MappFree(m_Milaplicacion);
}
// A partir de las imagenes guardadas en disco, genera la imagen mosaico
void GenerarMosaicos()
{
	char nombre_fich[512];
    MIL_ID M_aux;
    MIL_ID M_mosaico;
    long lSizeX, lSizeY; //dimensiones imagen


    // Leer tamaño de primera imagen
    sprintf(nombre_fich, "%s%s_%03d_%03d_%02d%s", g_csDirectorioBarrido, g_csMuestra, g_nFilaInicio, g_nColumnaInicio, g_arrFiltros[0]+1, ".tif");
    MbufDiskInquire(nombre_fich,M_SIZE_X, &lSizeX);
    MbufDiskInquire(nombre_fich,M_SIZE_Y, &lSizeY);

	MbufAlloc2d(M_DEFAULT_HOST, lSizeX, lSizeY, 8/*theApp.m_ParamIni.Cam.profundidad*/+M_UNSIGNED,
		M_IMAGE+M_PROC, &M_aux);
	MbufAlloc2d(M_DEFAULT_HOST, lSizeX * (g_nColumnaFin - g_nColumnaInicio + 1), lSizeY * (g_nFilaFin - g_nFilaInicio + 1), 8/*theApp.m_ParamIni.Cam.profundidad*/+M_UNSIGNED,
		M_IMAGE+M_PROC, &M_mosaico);
	for (int f=0; f < g_nBandas; f++)  
    {
        MbufClear(M_mosaico,0);
        for (int i=g_nFilaInicio;i<=g_nFilaFin;i++)
        {
            printf("\rComponiendo mosaico filtro %d  Fila %d ...    ", g_arrFiltros[f], i);
            for (int j=g_nColumnaInicio;j<=g_nColumnaFin;j++)
            {
		        sprintf(nombre_fich, "%s%s_%03d_%03d_%02d%s", g_csDirectorioBarrido, g_csMuestra, i, j, g_arrFiltros[f], ".tif");
		        //carga_imagen_campo8bit(nombre_fich, M_aux, theApp.m_ParamIni.Cam.profundidad); 
		        carga_imagen_campo_bits(nombre_fich, M_aux,8); 
                MbufCopyClip(M_aux,M_mosaico,(j-g_nColumnaInicio)*lSizeX,(i-g_nFilaInicio)*lSizeY);
            }
        }
        printf("\rSalvando mosaico filtro %d ...                      ", g_arrFiltros[f]);
        sprintf(nombre_fich, "%s%s_%02d%s", g_csDirectorioBarrido, g_csMuestra, g_arrFiltros[f], ".tif");
		graba_imagen_campo(nombre_fich, M_mosaico); 

    }
    printf("\r                                                         \n");

	MbufFree(M_aux);
	MbufFree(M_mosaico);
}
/**************************  graba_imagen_campo  ****************************
   Función para efectuar la grabación en disco de una imagen del campo.
   "nombre" es el nombre del archivo a almacenar.
   "buffer" es el buffer que quiero copiar a disco. Se espera que este buffer
   este en 8 o 16 bits reales (dependiendo de la profundidad de la camara)
   nBits - profundidad en bits en que se grabará la imagen (8,12,16)
****************************************************************************/
int graba_imagen_campo_bits(parametros& param, char *nombre, MIL_ID buffer, int nBits, double dEscala)
{
    int res = 0;

    if (param.Cam.profundidad == 16 && (nBits == 8 || nBits == 12))
    {
        MIL_ID M_buf16;
        long altoImagen,anchoImagen;
        MbufInquire(buffer, M_SIZE_X, &anchoImagen);
        MbufInquire(buffer, M_SIZE_Y, &altoImagen);
		MbufAlloc2d(M_sistema, anchoImagen, altoImagen, 16+M_UNSIGNED,
			M_IMAGE+M_DISP+M_PROC, &M_buf16 );
        if (nBits == 8)
        {
            MIL_ID M_buf8;
		    MbufAlloc2d(M_sistema, anchoImagen, altoImagen, 8+M_UNSIGNED,
			    M_IMAGE+M_DISP+M_PROC, &M_buf8 );
            MimShift(buffer,M_buf16,-8);//conversion a 8 bit 
		    MbufCopy(M_buf16, M_buf8); 
    //        MimShift(buffer,buffer,4);//conversion a 12 bit. Para que luego los histogramas funcionen correctamente

            res = graba_imagen_campo(nombre,M_buf8, nBits, dEscala);
            MbufFree(M_buf8);
        }
        else //nBits==12
        {
            MimShift(buffer,M_buf16,-4);//conversion a 12 bit 
            res = graba_imagen_campo(nombre,M_buf16, nBits, dEscala);
        }
        MbufFree(M_buf16);
    }
    else //Grabar tal cual (imagen origen esta en 8 bit o esta en 16 bit y se quiere dejar en 16 bit)
    {
        res = graba_imagen_campo(nombre,buffer, nBits, dEscala);
    }

    return res;
}
UINT CFormTomaUnica::TomaThread( LPVOID Param )
{
    PARAM_THREAD_TOMA* paramThread = (PARAM_THREAD_TOMA*)Param;

    //Tomar Imagenes (en M_banda[])
    captura_bandas( theApp.m_ParamIni, theApp.m_configuracion.m_nImagenAcum,theApp.Rueda, theApp.m_configuracion.m_dEscalaReflectancia);

    //Lanzamos el thread de Actualizacion de Posicion
    paramThread->pDialogo->m_pPadre->LanzarThreadPosicion();

    // Correcion de las diferencias de posicion, escala, etc entre bandas
    theApp.CorregirImagenes(false); //false=sin corregir rotacion

	//	Una vez obtenida la imagen promedio se guarda esta en disco 
	char nombre_fich[512];

    long nInicioX   = 0;
    int nTamX       = theApp.m_ParamIni.Cam.anchoImagen;        
    if (theApp.m_configuracion.m_nDimension_toma_x > 0)
    {
        nInicioX    = (long)(theApp.m_ParamIni.Cam.anchoImagen - theApp.m_configuracion.m_nDimension_toma_x)/2;
        nTamX       = theApp.m_configuracion.m_nDimension_toma_x;
    }

    long nInicioY   = 0;
    int nTamY       = theApp.m_ParamIni.Cam.altoImagen;        
    if (theApp.m_configuracion.m_nDimension_toma_y > 0)
    {
        nInicioY    = (long)(theApp.m_ParamIni.Cam.altoImagen - theApp.m_configuracion.m_nDimension_toma_y)/2;
        nTamY       = theApp.m_configuracion.m_nDimension_toma_y;
    }

	for (int f=0; f < theApp.m_ParamIni.nBandas; f++)  
    {
        // Guardamos en el tamaño de salida definido por el usuario
        MIL_ID Mchild;
        MbufChild2d(M_banda[f],nInicioX, nInicioY, nTamX,nTamY,&Mchild);
		sprintf(nombre_fich, "%s%s_%03d_%02d%s", theApp.m_configuracion.m_csDirectorioToma, paramThread->csNombreToma, paramThread->pDialogo->m_nCampo, theApp.m_ParamIni.filtro[f]+1, EXT_IMAG);
		graba_imagen_campo_bits(theApp.m_ParamIni, nombre_fich, Mchild, theApp.m_configuracion.m_nBits, theApp.m_configuracion.m_dEscalaReflectancia); 
        MbufFree(Mchild);
    }

    paramThread->pDialogo->m_nCampo++;

    delete paramThread;


    return 0;
}
Esempio n. 10
0
void cleanup()
{
	if(MilApplication != 0) {
		if(MilImageX != 0) {
			MdigGrabWait(MilDigitizer, M_GRAB_END);
			for(int n = 0; n < nmilbuff; n++) {
				MbufFree(MilImage[n]);
			}
			MilImageX = MilImageY = 0;
		}
		/* Release defaults. */
		MappFreeDefault(MilApplication, MilSystem, M_NULL,
			MilDigitizer, M_NULL);
		MilApplication = 0;
	}
}
void CvCaptureCAM_MIL::close( CvCaptureCAM_MIL* capture )
{
    if( MilSystem != M_NULL )
    {
        MdigFree( MilDigitizer );
        MbufFree( MilImage );
        MsysFree( MilSystem );
        cvReleaseImage(&rgb_frame );

        g_Mil.MilUser--;
        if(!g_Mil.MilUser)
            MappFree(g_Mil.MilApplication);

        MilSystem = M_NULL;
        MilDigitizer = M_NULL;
    }
}
Esempio n. 12
0
MdispGtkView::~MdispGtkView()
   {
   // Halt the grab, deselected the display, free the display and the image buffer
   // only if MbufAlloc was successful
   if (m_MilImage)
      {
      // Make sure display is deselected and grab is halt
      RemoveFromDisplay();

      // Free image buffer [CALL TO MIL]
      MbufFree(m_MilImage);
      }

   // remove timer
   g_source_remove(m_FrameTimeOutTag);
   
   // Close Annotation XDisplay
   if(m_XDisplay)
      XCloseDisplay(m_XDisplay);
   }
// Se elimina la imagen correspondiente al filtro "numFiltro", liberando la memoria del buffer
// Se muestra la imagen correspondiente al primer filtro anterior o posterior disponible
// Devuelve el nuevo filtro que se muestra o -1 si no hay mas
int ControlImagenes::EliminarImagen(int numFiltro, CStatic&	m_control)
{
    int filtroAnterior = EncontrarFiltroAnterior(numFiltro);

    if (filtroAnterior == -1)
    {
        // No hay ningun filtro
        MdispDeselect(m_Mildisplay,m_Milimagen[numFiltro-1]);
        m_control.SetBitmap((HBITMAP)m_backgound_bitmap); 

        //al quitar el fondo, se queda lo ultimo (es decir m_backgound_bitmap)
        //y ademas se veran las imagenes MIL cuando haya
        m_control.SetBitmap(NULL); 
    }
    else
    {
        MdispSelectWindow(m_Mildisplay,m_Milimagen[filtroAnterior-1],m_control);
    }
    MbufFree(m_Milimagen[numFiltro-1]);
    m_Milimagen[numFiltro-1] = M_NULL;
    m_numImagenes--; 

    return filtroAnterior;
}
/*************************** fin_control_digitalizador  *********************
	Libero la memoria reservada para el control del digitalizador (adquisición
	de imágenes).
*****************************************************************************/
int fin_control_digitalizador()
{
	int i;

	// Libero los buffers asociados al digitalizador
	if (M_enfoque != M_NULL)				MbufFree(M_enfoque); // relacionado con determina_contraste2

	if (M_correc_aux != M_NULL)				MbufFree(M_correc_aux);
	for (i=0; i < MAX_FILTROS_DTA; i++)  {
		if (M_correc_numer[i] != M_NULL)	MbufFree(M_correc_numer[i]);
		if (M_correc_denom[i] != M_NULL)	MbufFree(M_correc_denom[i]);
		if (M_banda[i] != M_NULL)			MbufFree(M_banda[i]);
	}
	if (M_imagen_acum != M_NULL)			MbufFree(M_imagen_acum);

	// Libero el digitalizador seleccionado
	if (M_digitalizador != M_NULL)
		libera_digitalizador();

	return 0;
}
int MosMain(void)
{
   MIL_ID       MilApplication,       /* Application Identifier.  */
                MilSystem,            /* System Identifier.       */
                MilDisplay,           /* Display Identifier.      */
                MilImage;             /* Image buffer Identifier. */
   long         ReturnValue;          /* Return Value holder.     */
   MIL_DOUBLE   SynchronousCallTime,  /* Timer variable.          */
                AsynchronousCallTime; /* Timer variable.          */
   int          n;                    /* Counter.                 */
   
   /* Allocate application, system and display. */
   MappAlloc(M_DEFAULT, &MilApplication);
   MsysAlloc(SLAVE_SYSTEM_DESCRIPTOR, M_DEF_SYSTEM_NUM, M_SETUP, &MilSystem);
   MdispAlloc(MilSystem, M_DEV0, MIL_TEXT("M_DEFAULT"), M_DEFAULT, &MilDisplay);

   /* Restore source image into an automatically allocated image buffer. */
   MbufRestore(IMAGE_FILE, MilSystem, &MilImage);
  
   /* Uncomment to display the image.    */
   /* MdispSelect(MilDisplay, MilImage); */
   
   /* Pause */
   MosPrintf(MIL_TEXT("\nMIL DTK:\n"));
   MosPrintf(MIL_TEXT("--------\n\n"));
   MosPrintf(MIL_TEXT("Custom synchronous and asynchronous MIL functions:\n\n"));
   MosPrintf(MIL_TEXT("This example times a synchronous and asynchronous custom function call.\n"));
   MosPrintf(MIL_TEXT("Press a key to continue.\n\n"));
   MosGetch();

   /* Synchronous function call. */
   /* -------------------------- */

   /* Call the function a first time for more accurate timings later (dll load, ...). */
   ReturnValue = SynchronousFunction(MilImage, MilImage, M_DEFAULT);

   /* Start the timer */
   MappTimer(M_TIMER_RESET+M_SYNCHRONOUS, M_NULL);

   /* Loop many times for more precise timing. */
   for (n= 0; n < NB_LOOP; n++)
      {
      /* Call the custom MIL synchronous function. */
      ReturnValue = SynchronousFunction(MilImage, MilImage, M_DEFAULT);
      }

   /* Read the timer. */
   MappTimer(M_TIMER_READ+M_SYNCHRONOUS, &SynchronousCallTime);

   /* Print the synchronous call time. */
   MosPrintf(MIL_TEXT("Synchronous  function call time: %.1f us.\n"), SynchronousCallTime*1000000/NB_LOOP);

   /* Asynchronous function call. */
   /* --------------------------- */

   /* Call the function a first time for more accurate timings later (dll load, ...). */
  AsynchronousFunction(MilImage, MilImage, M_DEFAULT);
  MthrWait(M_DEFAULT, M_THREAD_WAIT, M_NULL);

   /* Start the timer */
   MappTimer(M_TIMER_RESET+M_SYNCHRONOUS, M_NULL);

   /* Loop many times for more precise timing. */
   for (n= 0; n < NB_LOOP; n++)
      {
      /* Call the custom MIL asynchronous function. */
      AsynchronousFunction(MilImage, MilImage, M_DEFAULT);
      }

   /* Read and print the time. */
   MappTimer(M_TIMER_READ+M_SYNCHRONOUS, &AsynchronousCallTime);
      
   /* Print the asynchronous call time. */
   MosPrintf(MIL_TEXT("Asynchronous function call time: %.1f us.\n"), AsynchronousCallTime*1000000/NB_LOOP);
   MosPrintf(MIL_TEXT("Press a key to terminate.\n\n"));
   MosGetch();

   /* Free all allocations. */
   MbufFree(MilImage);
   MdispFree(MilDisplay);
   MsysFree(MilSystem);
   MappFree(MilApplication);

   return 0;
}
/* -------------- */
int MosMain(void)
   { 
   MIL_ID MilApplication;
   MIL_ID MilSystem     ;
   MIL_ID MilDigitizer  ;
   MIL_ID MilDisplay    ;
   MIL_ID MilImageDisp  ;
   MIL_ID GrabBufferList[GRAB_BUFFER_NUMBER];
   MIL_ID ProcSystemList[PROCESSING_SYSTEM_NUMBER];  
   MIL_ID SrcProcBufferList[BUFFER_NUMBER];
   MIL_ID DstProcBufferList[BUFFER_NUMBER];
   MIL_INT SizeX, SizeY, SizeBand;
   MIL_TEXT_CHAR SystemDescriptor[SYSTEM_DESCRIPTOR_SIZE];
   long    NbSystem = 0, NbSystemToAllocate = PROCESSING_SYSTEM_NUMBER;
   MIL_INT    GrabFrameCount, n; 
   double SingleSystemProcessingRate, MultipleSystemProcessingRate;
   ProcessingDataStruct ProcessingData;

   /* Allocations and setup. */
   /* ---------------------- */

   /* MIL application allocation. */
   MappAlloc(M_DEFAULT, &MilApplication);

   /* Allocations on the default grab system. */
   MsysAlloc(M_SYSTEM_DEFAULT, M_DEFAULT, M_DEFAULT, &MilSystem);
   MdispAlloc(MilSystem, M_DEV0, MIL_TEXT("M_DEFAULT"), M_DEFAULT, &MilDisplay);
   MdigAlloc(MilSystem, M_DEV0, MIL_TEXT("M_DEFAULT"), M_DEFAULT, &MilDigitizer);
   
   /* Inquire the digitizer's size. */
   SizeX    = ProcessingData.SizeX = (MIL_INT)(MdigInquire(MilDigitizer, M_SIZE_X, M_NULL)*BUFFER_SCALE);
   SizeY    = ProcessingData.SizeY = (MIL_INT)(MdigInquire(MilDigitizer, M_SIZE_Y, M_NULL)*BUFFER_SCALE);
   SizeBand = ProcessingData.SizeBand = (MIL_INT)(MdigInquire(MilDigitizer, M_SIZE_BAND, M_NULL));
   
   /* Allocate a display buffer and clear it. */
   MbufAllocColor(MilSystem, SizeBand, SizeX, SizeY, 8L+M_UNSIGNED, M_IMAGE+M_GRAB+M_DISP, &MilImageDisp);
   MbufClear(MilImageDisp, 0x0);            

   /* Display the processing result if activated (might be the limiting factor for speed). */
   if (DISPLAY_EACH_IMAGE_PROCESSED)
      MdispSelect(MilDisplay, MilImageDisp); 
      
   /* Allocate the grab buffers. */
   for (n=0; n< GRAB_BUFFER_NUMBER; n++)
      MbufAllocColor(MilSystem, SizeBand, SizeX, SizeY, 8L+M_UNSIGNED, M_IMAGE+M_GRAB, &GrabBufferList[n]);
      
   /* Allocate and order the required processing systems. */
   if (USE_GRAB_SYSTEM_AS_ONE_PROCESSOR)
      NbSystemToAllocate--;
   for (n=0; n<NbSystemToAllocate; n++)
      {
      /* Create a system descriptor: (Protocol://Address/System (Ex: dmiltcp://127.0.0.1/M_SYSTEM_HOST)) */
      MosSprintf(SystemDescriptor, SYSTEM_DESCRIPTOR_SIZE, MT("%s://%s/%s"), 
                 DISTRIBUTED_MIL_PROTOCOL, SYSTEM_ADDRESSES[n], PROCESSING_SYSTEM_TYPE);

      /* Allocate the system. */
      MsysAlloc(SystemDescriptor, M_DEFAULT, M_DEFAULT, &ProcSystemList[n]);

      /* Count the sucessfully allocated processing systems. */
      if (ProcSystemList[n])
         NbSystem++;
      }

   /* If the grab system is used to process, we add it at the end of the processing system list .
      This permits to dispatch the job to the other remote systems before to use the grab system 
      itself to process synchronously.
    */
   if (USE_GRAB_SYSTEM_AS_ONE_PROCESSOR)
      {
      ProcSystemList[NbSystem] = MilSystem;
      NbSystem++;
      }

   /* Allocate and order the source and destination processing buffers alternating the target system. */
   for (n=0; n<(NbSystem*BUFFER_PER_PROCESSOR); n++)
      {
      MbufAllocColor(ProcSystemList[n%NbSystem], SizeBand, SizeX, SizeY, 8L+M_UNSIGNED, 
                                                 M_IMAGE+M_PROC, &SrcProcBufferList[n]);
      MbufAllocColor(ProcSystemList[n%NbSystem], SizeBand, SizeX, SizeY, 8L+M_UNSIGNED, 
                                                 M_IMAGE+M_PROC, &DstProcBufferList[n]);
      }

   /* Set the specified grab scale. */
   MdigControl(MilDigitizer, M_GRAB_SCALE, BUFFER_SCALE);
      
   /* Single system processing. */
   /* ------------------------- */

   /* Print a message. */
   /* Print a message. */
   MosPrintf(MIL_TEXT("\nDISTRIBUTED MIL PROCESSING:\n"));
   MosPrintf(MIL_TEXT("---------------------------\n\n"));
   MosPrintf(MIL_TEXT("1 System processing:\n"));
   
   /* Initialize processing variables. */
   ProcessingData.NbSystem = 1;
   ProcessingData.ProcessEachImageOnAllSystems = M_NO;
   ProcessingData.NbProc = 0;
   ProcessingData.MilDigitizer = MilDigitizer;
   ProcessingData.DispBuffer = MilImageDisp; 
   ProcessingData.SrcProcBufferListPtr = SrcProcBufferList;
   ProcessingData.DstProcBufferListPtr = DstProcBufferList;
      
   /* Start processing the buffers. */
   MdigProcess(MilDigitizer, GrabBufferList, GRAB_BUFFER_NUMBER, M_START, M_DEFAULT, 
                                                 ProcessingFunction, &ProcessingData);
      
   /* Wait for a key and stop the processing. */
   MosPrintf(MIL_TEXT("Press <Enter> to stop.\n\n"));  
   MosGetch();   
   MdigProcess(MilDigitizer, GrabBufferList, GRAB_BUFFER_NUMBER, M_STOP+M_WAIT, M_DEFAULT, 
                                                       ProcessingFunction, &ProcessingData);
 
   /* Print statistics. */
   if (ProcessingData.NbProc != 0)
      {
      SingleSystemProcessingRate = ProcessingData.NbProc/ProcessingData.Time;
      MdigInquire(MilDigitizer, M_PROCESS_FRAME_COUNT, &GrabFrameCount);
      MosPrintf(MIL_TEXT("%ld Frames grabbed, %ld Frames processed at %.1f frames/sec (%.1f ms/frame).\n"),
                GrabFrameCount, ProcessingData.NbProc, SingleSystemProcessingRate, 1000.0/SingleSystemProcessingRate); 
      }
   else
      MosPrintf(MIL_TEXT("No frame has been grabbed.\n"));
   MosPrintf(MIL_TEXT("Press <Enter> to continue.\n\n"));
   MosGetch();

   /* Multiple systems processing. */
   /* ---------------------------- */

   /* Print a message. */
   MosPrintf(MIL_TEXT("%ld Systems processing:\n"), NbSystem);
   
   /* Halt continuous grab. */
   MdigHalt(MilDigitizer);

   /* Initialize processing variables. */
   ProcessingData.NbSystem = NbSystem;
   ProcessingData.ProcessEachImageOnAllSystems = PROCESS_EACH_IMAGE_ON_ALL_SYSTEMS;
   ProcessingData.NbProc = 0;
   ProcessingData.DispBuffer = MilImageDisp; 
   ProcessingData.SrcProcBufferListPtr = SrcProcBufferList;
   ProcessingData.DstProcBufferListPtr = DstProcBufferList;
   
   
   /* Start processing the buffers. */
   MdigProcess(MilDigitizer, GrabBufferList, GRAB_BUFFER_NUMBER, M_START, M_DEFAULT, 
                                                 ProcessingFunction, &ProcessingData);
      
   /* Wait for a key and stop the processing. */
   MosPrintf(MIL_TEXT("Press <Enter> to stop.\n\n"));  
   MosGetch();   
   MdigProcess(MilDigitizer, GrabBufferList, GRAB_BUFFER_NUMBER, M_STOP+M_WAIT, M_DEFAULT, 
                                                       ProcessingFunction, &ProcessingData);
 
   /* Print statistics. */
   if (ProcessingData.NbProc != 0)
      {
      MultipleSystemProcessingRate = ProcessingData.NbProc/ProcessingData.Time;
      MdigInquire(MilDigitizer, M_PROCESS_FRAME_COUNT, &GrabFrameCount);
      MosPrintf(MIL_TEXT("%ld Frames grabbed, %ld Frames processed at %.1f frames/sec (%.1f ms/frame).\n\n"),
                GrabFrameCount, ProcessingData.NbProc, MultipleSystemProcessingRate, 1000.0/MultipleSystemProcessingRate); 
      MosPrintf(MIL_TEXT("Speedup factor: %.1f.\n\n"),MultipleSystemProcessingRate/SingleSystemProcessingRate);
      if (DISPLAY_EACH_IMAGE_PROCESSED && ((long)((MultipleSystemProcessingRate/SingleSystemProcessingRate)+0.1) < NbSystem))
          MosPrintf(MIL_TEXT("Warning: Display might limit the processing speed. Disable it and retry.\n\n"));
      }
   else
      MosPrintf(MIL_TEXT("No frame has been grabbed.\n"));
   MosPrintf(MIL_TEXT("Press <Enter> to end.\n\n"));
   MosGetch();
   
   /* Free allocations. */
   /* ----------------- */

   for (n=0; n<GRAB_BUFFER_NUMBER; n++)
      MbufFree(GrabBufferList[n]);
   for (n=0; n<BUFFER_NUMBER; n++)
      {
      MbufFree(SrcProcBufferList[n]);
      MbufFree(DstProcBufferList[n]);
      }
   if (USE_GRAB_SYSTEM_AS_ONE_PROCESSOR)
      NbSystem--;
   for (n=0; n<NbSystem; n++)
      MsysFree(ProcSystemList[n]);
   MbufFree(MilImageDisp);
   MdispFree(MilDisplay);
   MdigFree(MilDigitizer);
   MsysFree(MilSystem);
   MappFree(MilApplication);

   return 0;
}  
Esempio n. 17
0
void mexFunction(int nlhs, mxArray *plhs[],
				 int nrhs, const mxArray *prhs[] )
{
	// validate the command string
	if(nrhs < 1 || mxIsChar(prhs[0]) != 1 || mxGetM(prhs[0]) != 1) {
		mexErrMsgTxt("Missing command string.");
	}

	// get the command
	int cmdlen = mxGetN(prhs[0]) + 1;
	char* command = (char*)mxCalloc(cmdlen, sizeof(char));
	if(mxGetString(prhs[0], command, cmdlen) != 0) {
		mexErrMsgTxt("Get command string failed.");
	}

	// startup 
	if(strcmp(command, "init") == 0) {

		// set things up so a clear will also clean up
		mexAtExit(cleanup);

		if(nrhs > 1) {
			if(!mxIsChar(prhs[1]) || mxGetM(prhs[1]) != 1) {
				mexErrMsgTxt("init argument should be the name of a dcf file.");
			}
			int nmlen = mxGetN(prhs[1]) + 1;
			char* dcfname = (char*)mxCalloc(nmlen, sizeof(char));
			mxGetString(prhs[1], dcfname, nmlen);

			MappAllocDefault(M_SETUP, &MilApplication, &MilSystem,
				M_NULL, M_NULL, M_NULL);
			if(MdigAlloc(MilSystem, M_DEV0, dcfname, M_DEFAULT, &MilDigitizer) == M_NULL) {
				mexErrMsgTxt("init failed.");
			}
		} else {
			/* Allocate defaults. */
			MappAllocDefault(M_SETUP, &MilApplication, &MilSystem,
				M_NULL, &MilDigitizer, M_NULL);
		}
		MBands = (int)MdigInquire(MilDigitizer, M_SIZE_BAND, M_NULL);
		for(int i=0; i<MBands; i++)
			band_is_selected[i] = true;
		bands_selected = MBands;

		MappTimer(M_TIMER_RESET, M_NULL);

		grab_scale_x = grab_scale_y = 1;

		MdigControl(MilDigitizer, M_GRAB_MODE, M_ASYNCHRONOUS);
		MdigControl(MilDigitizer, M_GRAB_SCALE_X, grab_scale_x);
		MdigControl(MilDigitizer, M_GRAB_SCALE_Y, grab_scale_y);
		
	// wrapup
	} else if(strcmp(command, "quit") == 0) {
		cleanup();

	// set the x and y scaling factor
	} else if(strcmp(command, "setscale") == 0) {
		// check the parameters
		if(nrhs != 3 || !mxIsDouble(prhs[1]) || !mxIsDouble(prhs[2])) {
			mexErrMsgTxt("setscale expects 2 arguments.");
		}
		grab_scale_x = mxGetScalar(prhs[1]);
		grab_scale_y = mxGetScalar(prhs[2]);

		MdigControl(MilDigitizer, M_GRAB_SCALE_X, grab_scale_x);
		MdigControl(MilDigitizer, M_GRAB_SCALE_Y, grab_scale_y);

	// select which bands to return for multiband sources
	} else if(strcmp(command, "selectbands") == 0) {
		// check to see if it's legal
		if(MBands == 1) {
			mexErrMsgTxt("selectbands only works for multiband sources.");
		}
		// check the argument
		if(nrhs != 2 || !mxIsDouble(prhs[1]) || mxGetM(prhs[1]) != 1) {
			mexErrMsgTxt("selectbands expects a row vector of band numbers.");
		}
		int nbands = mxGetN(prhs[1]);
		if(nbands == 0 || nbands > MBands) {
			mexErrMsgTxt("selectbands allows only 1 to 3 bands.");
		}
		double* bp = mxGetPr(prhs[1]);
		for(int i=0; i<3; i++) {
			band_is_selected[i] = false;
		}
		bands_selected = 0;
		for(i=0; i<nbands; i++) {
			int bnd = int(bp[i]);
			if(bnd < 0 || bnd > 2) {
				mexErrMsgTxt("selectbands allows bands numbered 0 to 2.");
			}
			if(!band_is_selected[bnd]) {
				band_is_selected[bnd] = true;
				bands_selected++;
			}
		}
		
	// grab a sequence in one call
	} else if(strcmp(command, "grabframes") == 0) {
		// check the parameters
		if(nrhs < 4 || !mxIsDouble(prhs[1]) || !mxIsDouble(prhs[2]) || !mxIsDouble(prhs[3])) {
			mexErrMsgTxt("grabframes expects 3 or 4 arguments.");
		}
		int width = int(mxGetScalar(prhs[1]));
		int height = int(mxGetScalar(prhs[2]));
		int frames = int(mxGetScalar(prhs[3]));

		// indicates whether this is a continuation of a previous grab
		bool grab_continue = false;
		if(nrhs == 5 && mxIsDouble(prhs[4]) && mxGetScalar(prhs[4]) > 0) {
			grab_continue = true;
		}

		// space to record per frame times if requested
		mxArray *time_array = 0;
		double* time_data = 0;
		if(nlhs > 1) {
			time_array = mxCreateDoubleMatrix(frames, 1, mxREAL);
			time_data = mxGetPr(time_array);
		}

		// allocate a matlab multidimensional array to return the image
		int dims[4];
		int ndims = 3;
		dims[0] = height;
		dims[1] = width;
		if(bands_selected > 1) {
			dims[2] = bands_selected;
			dims[3] = frames;
			ndims = 4;
		} else {
			dims[2] = frames;
		}
		mxArray *res = mxCreateNumericArray(ndims, dims, mxUINT8_CLASS, mxREAL);
		int frameelements = width*height*MBands;
		unsigned char* pmat = (unsigned char*)mxGetPr(res);

		// free buffers if they are the wrong size
		if(MilImageX != 0 && (width != MilImageX || height != MilImageY)) {
			MdigGrabWait(MilDigitizer, M_GRAB_END);
			for(int n=0; n<nmilbuff; n++) {
				MbufFree(MilImage[n]);
			}
			MilImageX = MilImageY = 0;
		}
		// allocate a few MIL buffers if we don't already have them
		if(MilImageX == 0) {
			for (int n=0; n<nmilbuff; n++)
			{
				MbufAllocColor(MilSystem,  
					MBands,
					width,
					height,
					8L+M_UNSIGNED, 
					M_IMAGE+M_GRAB, &MilImage[n]);
				if (MilImage[n] == 0)                     
				{
					mexErrMsgTxt("MbufAllocColor failed.");
				}
			}
			MilImageX = width;
			MilImageY = height;
		}

		// grab the frames
		if(!grab_continue) {
			// if you're not continuing a previous grab, then you want a fresh first frame
			MdigGrab(MilDigitizer, MilImage[MilImageNdx]);
		}
		for(int i = 0; i < frames; i++)
		{
			int ndx0 = MilImageNdx;
			MilImageNdx = (MilImageNdx + 1) % nmilbuff;
			MdigGrab(MilDigitizer, MilImage[MilImageNdx]);
			if(time_array)
				MappTimer(M_TIMER_READ, &time_data[i]);
			
			// copy the completed buff to the matlab array
			if(MBands == 1) { // easy
				// get a pointer to the buffer
				unsigned char* pmil;
				MbufInquire(MilImage[ndx0], M_HOST_ADDRESS, &pmil);
				if(pmil == M_NULL) {
					mexErrMsgTxt("no access to mil buffer.");
				}

				// copy the pixels exchanging x and y coordinates to suit matlab
				for(int y=0; y<height; y++) {
					for(int x=0; x<width; x++) {
						pmat[y+x*height] = pmil[x+y*width];
					}
				}
				pmat += width*height;

			} else { // harder
				// I bet there is some smarter way to do this...
				// for each band
				for(int b=0; b<MBands; b++) {
					if(band_is_selected[b]) {
						// allocate a child buffer on the band.
						MIL_ID child = MbufChildColor(MilImage[ndx0], b, M_NULL);
						if(child == M_NULL) {
							mexErrMsgTxt("no child");
						}
						// get a pointer to the child
						unsigned char* pmil;
						MbufInquire(child, M_HOST_ADDRESS, &pmil);
						if(pmil == M_NULL) {
							MbufFree(child);
							mexErrMsgTxt("no access to mil buffer.");
						}
						// do the copy, twizzling the indicies around...
						for(int y=0; y<height; y++) {
							for(int x=0; x<width; x++) {
								pmat[(y + x*height)] = pmil[x+y*width];
							}
						}
						pmat += width*height;

						// release the child
						MbufFree(child);
					}
				}
			}
		}

		plhs[0] = res;
		if(time_array)
			plhs[1] = time_array;

	} else {
		mexErrMsgTxt("Unknown command string.");
	}

}  
/**************************  carga_imagen_campo  ****************************
	Función para efectuar la carga desde disco de una imagen del campo.
	Se le pasan a esta función los siguientes argumentos:
		nombre: nombre del fichero que quiero cargar.
		buffer: le paso el buffer donde quiero almacenar la imagen a cargar.
				Esto define el tamaño del mismo.
        nProfundidad: profundidad (bits) del buffer (8,12,16)
	Esta función únicamente carga la imagen en el buffer seleccionado, no la
	muestra en el display.
    LEE LA PROFUNDIDAD GUARDADA, EL BUFFER ESTA EN nProfundidad
****************************************************************************/
int carga_imagen_campo_bits(char *nombre, MIL_ID buffer, int nProfundidad)
{
    // Leer informacion TIF (escala reflectancia y profundidad)
    int nProfundidadFichero = -1;
    double dEscalaFichero;
    try
    {
        CString csNombreImagen;
        INTERFAZ_LIBTIF::LeerTags(nombre,nProfundidadFichero,dEscalaFichero); //Leemos de la imagen la profundidad en bits y la escala reflectancia-gris
        if (nProfundidadFichero < 0 )
            nProfundidadFichero = 8; // por defecto las imagenes estan en 8 bit
    }
    catch(...)
    {
        nProfundidadFichero = 8;
    }

    if (nProfundidad != nProfundidadFichero) 
    {
        // Buffer auxiliar de 16 es necesario para poder operar (M_PROC)
        MIL_ID M_buf16;
        long altoImagen,anchoImagen;
        MbufInquire(buffer, M_SIZE_X, &anchoImagen);
        MbufInquire(buffer, M_SIZE_Y, &altoImagen);
	    MbufAlloc2d(M_DEFAULT_HOST, anchoImagen, altoImagen, 16+M_UNSIGNED,
		    M_IMAGE+M_DISP+M_PROC, &M_buf16 );
        if (nProfundidad >= 12 && nProfundidadFichero >= 12) 
        {
            if (carga_imagen_campo(nombre,M_buf16))
                return 1;//ERROR
            MimShift(M_buf16,buffer,nProfundidad - nProfundidadFichero);//conversion de 12 a 16 bit 
        }
        else if (nProfundidadFichero == 8) //nProfundidad>8
        {
            MIL_ID M_buf8;
	        MbufAlloc2d(M_DEFAULT_HOST, anchoImagen, altoImagen, 8+M_UNSIGNED,
		        M_IMAGE+M_DISP+M_PROC, &M_buf8 );

            if (carga_imagen_campo(nombre,M_buf8))
                //ERROR
                return 1;

	        MbufCopy(M_buf8, M_buf16); 
            MbufFree(M_buf8);
            MimShift(M_buf16,buffer,nProfundidad - nProfundidadFichero);//conversion de 8 a 12 bit 
        }
        else //(nProfundidad == 8 && nProfundidadFichero > 8
        {
            if (carga_imagen_campo(nombre,M_buf16))
                //ERROR
                return 1;

            MimShift(M_buf16,buffer,nProfundidad - nProfundidadFichero);//conversion de 8 a 12 bit 
        }
        MbufFree(M_buf16);
    }
    else
    {
        if (carga_imagen_campo(nombre,buffer))
            //ERROR
            return 1;
    }

	return  0;
}
Esempio n. 19
0
/* Main function. */
int MosMain(void)
   {
   MIL_ID   MilApplication;
   MIL_ID   MilSystem;
   MIL_ID   MilDigitizer[2];
   MIL_ID   MilDisplay[2];
   MIL_ID   MilImageDisp[2];

   /* Allocations. */
   MappAlloc(M_DEFAULT, &MilApplication);
   MsysAlloc(MIL_TEXT("M_DEFAULT"), M_DEFAULT, M_DEFAULT, &MilSystem);
   MdigAlloc(MilSystem,  M_DEV0,    MIL_TEXT("M_DEFAULT"), M_DEFAULT, &MilDigitizer[0]);
   MdigAlloc(MilSystem,  M_DEV1,    MIL_TEXT("M_DEFAULT"), M_DEFAULT, &MilDigitizer[1]);
   MdispAlloc(MilSystem, M_DEFAULT, MIL_TEXT("M_DEFAULT"), M_DEFAULT, &MilDisplay[0]);
   MdispAlloc(MilSystem, M_DEFAULT, MIL_TEXT("M_DEFAULT"), M_DEFAULT, &MilDisplay[1]);

   /* Allocate 2 display buffers and clear them. */
   MbufAlloc2d(MilSystem,
               (MIL_INT)(MdigInquire(MilDigitizer[0], M_SIZE_X, M_NULL)*GRAB_SCALE),
               (MIL_INT)(MdigInquire(MilDigitizer[0], M_SIZE_Y, M_NULL)*GRAB_SCALE),
               8L+M_UNSIGNED,
               M_IMAGE+M_GRAB+M_PROC+M_DISP, &MilImageDisp[0]);
   MbufClear(MilImageDisp[0], 0x0);
   MbufAlloc2d(MilSystem,
               (MIL_INT)(MdigInquire(MilDigitizer[1], M_SIZE_X, M_NULL)*GRAB_SCALE),
               (MIL_INT)(MdigInquire(MilDigitizer[1], M_SIZE_Y, M_NULL)*GRAB_SCALE),
               8L+M_UNSIGNED,
               M_IMAGE+M_GRAB+M_PROC+M_DISP, &MilImageDisp[1]);
   MbufClear(MilImageDisp[1], 0x80);

   /* Display the buffers. */
   MdispSelect(MilDisplay[0], MilImageDisp[0]);
   MdispSelect(MilDisplay[1], MilImageDisp[1]);

   /* Grab continuously on displays at the specified scale. */
   MdigControl(MilDigitizer[0], M_GRAB_SCALE, GRAB_SCALE);
   MdigGrabContinuous(MilDigitizer[0],MilImageDisp[0]);
   MdigControl(MilDigitizer[1], M_GRAB_SCALE, GRAB_SCALE);
   MdigGrabContinuous(MilDigitizer[1],MilImageDisp[1]);

   /* Print a message. */
   MosPrintf(MIL_TEXT("Press <Enter> to stop continuous grab.\n"));
   MosGetch();

   /* Halt continuous grab. */
   MdigHalt(MilDigitizer[0]);
   MdigHalt(MilDigitizer[1]);

   /* Print a message. */
   MosPrintf(MIL_TEXT("Press <Enter> to end.\n"));
   MosGetch();

   /* Free allocations. */
   MbufFree(MilImageDisp[0]);
   MbufFree(MilImageDisp[1]);
   MdispFree(MilDisplay[0]);
   MdispFree(MilDisplay[1]);
   MdigFree(MilDigitizer[0]);
   MdigFree(MilDigitizer[1]);
   MsysFree(MilSystem);
   MappFree(MilApplication);

   return 0;
   }