// Initialize camera input
bool CvCaptureCAM_MIL::open( int wIndex )
{
    close();

    if( g_Mil.MilApplication == M_NULL )
    {
        assert(g_Mil.MilUser == 0);
        MappAlloc(M_DEFAULT, &(g_Mil.MilApplication) );
        g_Mil.MilUser = 1;
    }
    else
    {
        assert(g_Mil.MilUser>0);
        g_Mil.MilUser++;
    }

    int dev_table[16] = { M_DEV0, M_DEV1, M_DEV2, M_DEV3,
        M_DEV4, M_DEV5, M_DEV6, M_DEV7,
        M_DEV8, M_DEV9, M_DEV10, M_DEV11,
        M_DEV12, M_DEV13, M_DEV14, M_DEV15 };

    //set default window size
    int w = 320;
    int h = 240;

    for( ; wIndex < 16; wIndex++ )
    {
        MsysAlloc( M_SYSTEM_SETUP, //we use default system,
                                   //if this does not work
                                   //try to define exact board
                                   //e.g.M_SYSTEM_METEOR,M_SYSTEM_METEOR_II...
                   dev_table[wIndex],
                   M_DEFAULT,
                   &MilSystem );

        if( MilSystem != M_NULL )
            break;
    }
    if( MilSystem != M_NULL )
    {
        MdigAlloc(MilSystem,M_DEFAULT,
                  M_CAMERA_SETUP, //default. May be M_NTSC or other
                  M_DEFAULT,&MilDigitizer);

        rgb_frame = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 3 );
        MdigControl(MilDigitizer, M_GRAB_SCALE,  1.0 / 2);

        /*below line enables getting image vertical orientation
         consistent with VFW but it introduces some image corruption
         on MeteorII, so we left the image as is*/
        //MdigControl(MilDigitizer, M_GRAB_DIRECTION_Y, M_REVERSE );

        MilImage = MbufAllocColor(MilSystem, 3, w, h,
            8+M_UNSIGNED, M_IMAGE + M_GRAB, M_NULL);
    }

    return MilSystem != M_NULL;
}
示例#2
0
bool MdispGtkView::newDoc()
   {
    // Set buffer attributes
   if(((MdispGtkApp*)dispGtkApp())->m_numberOfDigitizer)
      {
      m_bufferAttributes=M_IMAGE+M_DISP+M_GRAB+M_PROC;
      m_imageSizeX = ((MdispGtkApp*)dispGtkApp())->m_digitizerSizeX;
      m_imageSizeY = ((MdispGtkApp*)dispGtkApp())->m_digitizerSizeY;
      m_NbBands    = ((MdispGtkApp*)dispGtkApp())->m_digitizerNbBands;

      // Allocate a buffer [CALL TO MIL]
      MbufAllocColor(((MdispGtkApp*)dispGtkApp())->m_MilSystem,
                     m_NbBands,
                     m_imageSizeX,
                     m_imageSizeY,
                     M_DEF_IMAGE_TYPE,
                     m_bufferAttributes,
                     &m_MilImage);

      // Clear the buffer [CALL TO MIL] 
      MbufClear(m_MilImage,M_COLOR_BLACK);
      }
   else
      {
      //Import image in buffer [CALL TO MIL]
      MbufImport(IMAGE_FILE,M_DEFAULT,M_RESTORE,((MdispGtkApp*)dispGtkApp())->m_MilSystem,&m_MilImage);

      // Set SizeX and SizeY variable to the size of the buffer [CALL TO MIL]
      if (m_MilImage) 
         {
         m_imageSizeX   = MbufInquire(m_MilImage, M_SIZE_X, M_NULL);
         m_imageSizeY   = MbufInquire(m_MilImage, M_SIZE_Y, M_NULL);
         m_NbBands      = MbufInquire(m_MilImage, M_SIZE_BAND, M_NULL);
         }
      }

   UpdateContentSize();

   // If not able to allocate a buffer, do not create a new document
   if(!m_MilImage)
      return false;

   Initialize();

   return true;
   }
示例#3
0
文件: milmex.cpp 项目: gbishop/milmex
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.");
	}

}  
/* -------------- */
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;
}  
// Calcula las imagenes monocromas para R, G y B segun los porcentajes dados, 
// reservando memoria y presentando la imagen RGB
// Devuelve true si se ha realizado el calculo, false si no (porque ya se realizó antes)
bool ControlImagenes::MostrarImagenRGB(int arrFiltroPorcentajesR[MAX_NUM_IMAGENES], 
                                       int arrFiltroPorcentajesG[MAX_NUM_IMAGENES], 
                                       int arrFiltroPorcentajesB[MAX_NUM_IMAGENES],
                                       CStatic&	m_control,
                                       int nTotalR,int nTotalG,int nTotalB,
                                       bool bModificado)
{

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

    DisplayBits(8); //para que el display muestre las imagenes en profundidad 8 bit

    // Si es la primera vez, reservar la memoria de la imagen RGB
    if (m_MilRGB == M_NULL)
        MbufAllocColor(M_DEFAULT_HOST, 3, m_nAnchoImagen, m_nAltoImagen, 8+M_UNSIGNED, M_IMAGE+M_DISP, &m_MilRGB); //16 por si las imagenes estan en 16bit
    else if (!bModificado)
    {
        MdispSelectWindow(m_Mildisplay,m_MilRGB,m_control);
        return false;
    }


    unsigned short* pBuffImagen;    //auxiliar para volcar cada imagen de cada filtro, 16 bit
    unsigned char* pRed;           // auxiliar para calcular la banda de color (8 bit)
    unsigned char* pGreen;         // auxiliar para calcular la banda de color (8 bit)
    unsigned char* pBlue;          // auxiliar para calcular la banda de color (8 bit)

    pBuffImagen = (unsigned short*)calloc(m_nAnchoImagen*m_nAltoImagen, sizeof(unsigned short));
    pRed = (unsigned char*)calloc(m_nAnchoImagen*m_nAltoImagen, sizeof(unsigned char));
    pGreen = (unsigned char*)calloc(m_nAnchoImagen*m_nAltoImagen, sizeof(unsigned char));
    pBlue = (unsigned char*)calloc(m_nAnchoImagen*m_nAltoImagen, sizeof(unsigned char));

    for (int i= 0; i<MAX_NUM_IMAGENES;i++)
    {
        // Cargar buffers de filtros solo si se necesita en alguna de las bandas
        if (arrFiltroPorcentajesR[i] != 0 || arrFiltroPorcentajesG[i] != 0 || arrFiltroPorcentajesB[i] != 0)
        {
            MbufGet(m_Milimagen[i],pBuffImagen);

            //Acumular el pocentaje adecuado de este filtro en cada color
            if(arrFiltroPorcentajesR[i] != 0)
            {
                Acumular(pRed, pBuffImagen, ((double)arrFiltroPorcentajesR[i])/nTotalR, m_nAnchoImagen*m_nAltoImagen);
            }
            if(arrFiltroPorcentajesG[i] != 0)
            {
                Acumular(pGreen, pBuffImagen, ((double)arrFiltroPorcentajesG[i])/nTotalG, m_nAnchoImagen*m_nAltoImagen);
            }
            if(arrFiltroPorcentajesB[i] != 0)
            {
                Acumular(pBlue, pBuffImagen, ((double)arrFiltroPorcentajesB[i])/nTotalB, m_nAnchoImagen*m_nAltoImagen);
            }

        }
    }


    // Volcar el array auxiliar calculado al color correspondiente
    MbufPutColor(m_MilRGB,M_SINGLE_BAND,M_BLUE/*2*/,pBlue);
    MbufPutColor(m_MilRGB,M_SINGLE_BAND,M_GREEN/*1*/,pGreen);
    MbufPutColor(m_MilRGB,M_SINGLE_BAND,M_RED/*0*/,pRed);

    free(pBuffImagen);
    free(pBlue);
    free(pGreen);
    free(pRed);

    // Mostar la imagen en color
    MdispSelectWindow(m_Mildisplay,m_MilRGB,m_control);
	// Inicializar Overlay la primera vez que se carga una imagen
	// Esto se hace aqui porque no funciona si no hay un buffer asociado con el display
	// ha de usarse la variable global M_overlay_normal para que funcionen las funciones graficas
    // y porque puede ser que no se haya hecho al cargar las imagenes pancromaticas (en el caso
    // de que la primera imagen mostrada sea la pancromatica, ver CAnalisisDlg::AbrirTodas y CargarImagen)
	if (M_overlay_normal==NULL)
	{
		MdispInquire(m_Mildisplay, M_OVERLAY_ID, &M_overlay_normal);

		// Relleno el buffer overlay con el color TRANSPARENTE
		MbufClear(M_overlay_normal, TRANSPARENTE );
	}

    return true;
}
ControlImagenes::ControlImagenes()
{
    //Inicilizacion
//    m_Milsistema        = M_NULL;
    m_Milaplicacion     = M_NULL;
    m_Mildisplay        = M_NULL;
    m_Miloverlay        = M_NULL;
    m_lut_overlay       = M_NULL;
    m_numImagenes       = 0;
    m_nAnchoImagen      = -1;
    m_nAltoImagen       = -1;
    for (int i=0;i<MAX_NUM_IMAGENES;i++)
        m_Milimagen[i]  = M_NULL;        
    m_MilRGB            = M_NULL;
    M_Clasificacion     = M_NULL;
    m_bufClasificacionSelectiva = NULL;
    m_bDefiniendoArea   = false;
    m_bPintandoRect     = false;


	MappAlloc(M_DEFAULT, &m_Milaplicacion);	// Selecciono la aplicación MIL.
	if ( m_Milaplicacion == M_NULL ) {
        AfxMessageBox("Error: No se pudo inicilizar MIL", MB_ICONERROR | MB_OK);
	}

	//	Pregunto al sistema la versión de la librería de control de proceso de imagen
	//MappInquire(M_VERSION, &m_Milversion);

    // pruebas MIL 8
//	MsysAlloc(M_SYSTEM_METEOR_II_1394, M_DEV0, M_DEFAULT, &M_sistema);	// Selecciono un sistema hardware

//	if ( M_sistema == M_NULL )  {
//        AfxMessageBox("Error: No se pudo inicilizar MIL", MB_ICONERROR | MB_OK);
//	}

    //	Display normal para las imágenes adquiridas y procesadas. 
	MdispAlloc(M_DEFAULT_HOST, M_DEFAULT, "M_DEFAULT", M_WINDOWED + M_GDI_OVERLAY, &m_Mildisplay);
	if ( m_Mildisplay == M_NULL )  {
        AfxMessageBox("Error: No se pudo inicilizar MIL", MB_ICONERROR | MB_OK);
	}

	// El texto tiene color de fondo transparente
    MgraControl(M_DEFAULT, M_BACKGROUND_MODE, M_TRANSPARENT);

    // OVERLAY (diferente para MIL 8 y anteriores
    if (M_MIL_CURRENT_VERSION >= 8.0)
    {
        // Inicializar colores para pintar areas
        m_listaColor[NEGRO_POS] =     M_RGB888(NEGRO_R,NEGRO_G,NEGRO_B);
        m_listaColor[MARRON_POS] =     M_RGB888(MARRON_R,MARRON_G,MARRON_B);
        m_listaColor[ROJO_POS] =     M_RGB888(ROJO_R,ROJO_G,ROJO_B);
        m_listaColor[CYAN_POS] =     M_RGB888(CYAN_R,CYAN_G,CYAN_B);
        m_listaColor[NARANJA_POS] =     M_RGB888(NARANJA_R,NARANJA_G,NARANJA_B);
        m_listaColor[VERDE_POS] =     M_RGB888(VERDE_R,VERDE_G,VERDE_B);
        m_listaColor[AZUL_POS] =     M_RGB888(AZUL_R,AZUL_G,AZUL_B);
        m_listaColor[MORADO_POS] =     M_RGB888(MORADO_R,MORADO_G,MORADO_B);
        m_listaColor[GRIS_POS] =     M_RGB888(GRIS_R,GRIS_G,GRIS_B);
        m_listaColor[ORO_POS] =     M_RGB888(ORO_R,ORO_G,ORO_B);
        m_listaColor[ROSA_POS] =    M_RGB888(ROSA_R,ROSA_G,ROSA_B);

        MdispControl(m_Mildisplay, M_OVERLAY, M_ENABLE);

        // Establezco TRANSPARENTE como color transparente
        MdispControl(m_Mildisplay, M_TRANSPARENT_COLOR, TRANSPARENTE);

        //Tipo de interpolacion para el redimensionamiento de la imagen en el display
        //Si se activa en MIL 8, quedan lineas de color transparernte en el overlay cuando el zoom no es 1
        //MdispControl(m_Mildisplay, M_INTERPOLATION_MODE, M_NEAREST_NEIGHBOR);
    }
    else
    {
        // Inicializar colores para pintar areas
        m_listaColor[0] =     NEGRO   ;
        m_listaColor[1] =     ROJO_OSC  ;
        m_listaColor[2] =     ROJO    ;
        m_listaColor[3] =     CYAN ;
        m_listaColor[4] =     AMARILLO;
        m_listaColor[5] =     VERDE   ;
        m_listaColor[6] =     AZUL    ;
        m_listaColor[7] =     MAGENTA_OSC  ;
        m_listaColor[8] =     GRIS    ;
        m_listaColor[9] =     AMARILLO_OSC     ;
        m_listaColor[10] =    GRIS_CLA   ;

        // LUT
	    MbufAllocColor(M_DEFAULT_HOST, 3L, 256L, 1L, 8L+M_UNSIGNED, M_LUT, &m_lut_overlay);
	    if ( m_lut_overlay == M_NULL)  {
            AfxMessageBox("Error: No se pudo inicilizar MIL", MB_ICONERROR | MB_OK);
	    }
    
	    crea_LUT_overlay(m_lut_overlay, 0);	// Genera LUT color y corrección de gamma
	    configura_overlay(m_Mildisplay, M_NULL, &m_Miloverlay, 1); // repartido entre aqui y CargarImagen // M_NULL, antes ponia M_imagen1 que ya no esta disponible en Analisis, seguramente falle

        //	Asocio la LUT de pseudo-color al display de overlay
	    MdispControl(m_Mildisplay, M_OVERLAY_LUT, m_lut_overlay);


	    //	Modifico la configuración del display: m_Mildisplay_normal.
	    //		- Deshabilito el menú de tareas.
	    //		- Deshabilito la barra del título.
	    //	    - Fijo la posición de la ventana en 0,0. 
	    MdispControl(m_Mildisplay, M_WINDOW_MENU_BAR, M_DISABLE);
	    MdispControl(m_Mildisplay, M_WINDOW_TITLE_BAR, M_DISABLE);
	    MdispControl(m_Mildisplay, M_WINDOW_INITIAL_POSITION_X, 0 );
	    MdispControl(m_Mildisplay, M_WINDOW_INITIAL_POSITION_Y, 0 );

        // Establezco TRANSPARENTE como color transparente
		MdispOverlayKey(m_Mildisplay, M_KEY_ON_COLOR, M_EQUAL, 0xff, TRANSPARENTE);
    }

    // Bitmap de fondo para poner siempre que no haya mas imagenes
    BYTE bBits[] = {0xd8,0xe9,0xec};
    m_backgound_bitmap.CreateBitmap(1,1,1,32,bBits);        
}