示例#1
0
/**
 * Unloads a loaded LOD map tile
 *
 * @param tile			the LOD map tile to unload
 */
static void unloadLodMapTile(OpenGLLodMapTile *tile)
{
	assert(tile->status == OPENGL_LODMAP_TILE_READY);

	freeImage(tile->heights);
	freeImage(tile->normals);
	freeImage(tile->texture);

	tile->status = OPENGL_LODMAP_TILE_META;
}
示例#2
0
文件: game.c 项目: gubagame/gamengine
void resetLevel(gameLevel *gl)
{
	if(gl)
	{	
		freeImage(&gl->background);
		freeImage(&gl->frame);
		gl->xview=0;
		gl->yview=0;

		freeActors(gl);
	}
}
示例#3
0
SDLManager::~SDLManager()
{
	//Mix_Quit();
	Mix_CloseAudio();
	SDL_EnableUNICODE(SDL_DISABLE);
	TTF_Quit();

	// SDL_Quit already does this for me
	//SDL_FreeSurface(screen);
	freeImage(bg);
    freeImage(x);
    freeImage(o);

	SDL_Quit();
}
示例#4
0
int main(int argc, char **argv) {

    int i;
    int window;
    int threshold;
    FILE *a;
    double noise[] = {0.0,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50};
    double *scores;
    portImage *pa;
    a = fopen(argv[1], "r");
    sscanf(argv[2], "%d", &window);
    pa = readImage(a);

    scores = (double*)malloc( sizeof(double) * window * window );
    if (!scores) {
        fprintf(stderr, "Memory allocation failed.\n");
        return 1;
    }

    for (i = 0; i < 11; i++) { 
        printf("%s,%2.2f,", argv[1], noise[i]);
        calculateAverageDifference(pa, window, noise[i], scores);
        for (threshold = 0; threshold < window*window; threshold++)
            printf("%.3f,",scores[threshold]);
        printf("\n");
    }

    free(scores);
    freeImage(pa);
    fclose(a);
    return 0;
} // End Main
示例#5
0
void locateNovelFeatures(ImageList* novelImages, GraphDiscription graphTemplate, GraphDiscription bunchGraph, JetMasks masks, char* imageDir, char* outputDir, JetDisplacementEstimator dispEst){
    ImageList *subject, *replicate;
    int i;

    for(subject = novelImages; subject != NULL; subject = subject->next_subject){
        for(replicate = subject; replicate != NULL; replicate = replicate->next_replicate){
            Image novel = readRawImage(makePath(imageDir,replicate->filename));
            int *verts = (int*)malloc(sizeof(int)*bunchGraph->numVert);
            printf("Fitting graph for image: %s |", replicate->filename); fflush(stdout);
            for(i = 0; i < bunchGraph->numVert; i++){
                printf("#"); fflush(stdout);
                guessVertexLocation(i, i, graphTemplate, bunchGraph);

                graphTemplate->verts[i].x = graphTemplate->verts[i].x;
                graphTemplate->verts[i].y = graphTemplate->verts[i].y;

                LocatePoint( &(graphTemplate->verts[i].x),  &(graphTemplate->verts[i].y), bunchGraph->bunch[i], novel, masks, dispEst);
                verts[i] = i;
            }
            printf("|\n"); fflush(stdout);

            permuteArray(verts, bunchGraph->numVert);
            freeImage(novel);
            saveGraphDiscription(makePath(outputDir,replicate->filename),graphTemplate);
        }
    }
}
示例#6
0
API OpenGLPrimitive *parseOpenGLScenePrimitiveHeightmap(Scene *scene, const char *path_prefix, const char *name, Store *store)
{
	// Parse num parameter
	Store *heightmapParam;

	if((heightmapParam = getStorePath(store, "heightmap")) == NULL || heightmapParam->type != STORE_STRING) {
		logError("Failed to parse OpenGL scene primitive heightmap '%s': String parameter 'heightmap' not found", name);
		return NULL;
	}

	GString *path = g_string_new(path_prefix);
	g_string_append_printf(path, "/%s", heightmapParam->content.string);
	Image *image = readImageFromFile(path->str);

	if(image == NULL) {
		logError("Failed to parse OpenGL scene primitive heightmap '%s': Failed to load heightmap image from '%s'", name, path->str);
		g_string_free(path, true);
		return NULL;
	}

	g_string_free(path, true);

	// Create heightmap
	OpenGLPrimitive *primitive;

	if((primitive = createOpenGLPrimitiveHeightmap(image, image->width, image->height)) == NULL) {
		logError("Failed to parse OpenGL scene primitive heightmap '%s': Failed to create heightmap primitive from heightmap image", name);
		freeImage(image);
		return NULL;
	}

	return primitive;
}
示例#7
0
文件: util.c 项目: drn2369/LineReg
void freePGMImage(PGMImage* dataPtr){

	/* Free image */
	freeImage(dataPtr->img);

	/* Free ptr */
	free(dataPtr);
}
/* This function frees space that was used to hold on to gabor
 * masks */
void freeJetMasks(JetMasks masks){
    int n;

    for(n = 0; n < masks->size; n++){
        freeImage( masks->masks[n] );
    }
    freeJetParams( masks->params );
    free( masks->masks );
    free( masks );
}
示例#9
0
/**
 * Frees an LOD map tile
 *
 * @param tree			the quadtree for which to free the map tile
 * @param data			the LOD map tile to free
 */
static void freeLodMapTile(Quadtree *tree, void *data)
{
	OpenGLLodMapTile *tile = data;

	g_mutex_clear(&tile->mutex);
	g_cond_clear(&tile->condition);

	if(tile->status == OPENGL_LODMAP_TILE_ACTIVE) {
		deactivateLodMapTile(tile);
	}

	if(tile->status == OPENGL_LODMAP_TILE_READY) {
		freeImage(tile->heights);
		freeImage(tile->normals);
		freeImage(tile->texture);
	}

	free(tile);
}
示例#10
0
SkinDialog::~SkinDialog() {
	if ( skinItems ) {
		free(skinItems);
	}
//	freeImage(screenSnapshot);
	mainWindow = NULL;
	mainDrawImage = NULL;
	freeImage(drawImage);
	mainFont = NULL;
};
示例#11
0
文件: ccgview.cpp 项目: bashrc/ccg
CcgView::~CcgView()
{
    globals.gasIndex = ui->comboBoxGas->currentIndex();
    globals.plotTypeIndex = ui->comboBoxPlotType->currentIndex();
    globals.regionIndex = ui->comboBoxRegion->currentIndex();
    globals.startYear = ui->spinBoxStartYear->value();
    globals.endYear = ui->spinBoxEndYear->value();
    GlobalData::save(&globals);
    freeImage();
    delete ui;
}
示例#12
0
GLuint textureToID(char* filePath){
	GLuint textureId;
	image* imageP = createTexture(filePath);
	glGenTextures(1,&textureId);
	glBindTexture(GL_TEXTURE_2D,textureId);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,imageP->width,imageP->height,0,GL_RGBA,GL_UNSIGNED_BYTE,imageP->texture);
	freeImage(imageP);
	return textureId;
}
示例#13
0
GraphDiscription extractModelJets(ImageList* modelImages, char* imageDir, char* graphDir, JetMasks masks){
    ImageList *subject, *replicate;
    GraphDiscription mj = NULL;
    int count = 0, i;

    for(subject = modelImages; subject != NULL; subject = subject->next_subject){
        for(replicate = subject; replicate != NULL; replicate = replicate->next_replicate){
            /* load the model graph */
            GraphDiscription gd = readGraphDiscription(makePath(graphDir,replicate->filename));

            /* Load the model image */
            Image model = readRawImage(makePath(imageDir,replicate->filename));

            /*MESSAGE2ARG("Extracting Jets From Image #%d.  <%s>", count, replicate->filename);*/
            if(count == 0){
                /* load up a default graph */
                mj = readGraphDiscription(makePath(graphDir,replicate->filename));
            }
            else{
                assert(mj->numVert == gd->numVert);
                for(i = 0; i < mj->numVert; i++){
                    /* Accumulate mean locations */
                    mj->verts[i].x += gd->verts[i].x;
                    mj->verts[i].y += gd->verts[i].y;
                }
            }

            /* extract jets */
                printf("Extracting jets from model image #%03d.  <%s>  |", count, replicate->filename); fflush(stdout);
            for(i = 0; i < gd->numVert; i++){
                printf("#"); fflush(stdout);
                addJetToBunch( mj->bunch[i],
                    extractJet(gd->verts[i].x, gd->verts[i].y, model, masks));
            }
            printf("|\n");

            freeImage(model);
            freeGraphDiscription(gd);
            count++;
        }
    }

    for(i = 0; i < mj->numVert; i++){
        /* Accumulate mean locations */
        mj->verts[i].x /= count;
        mj->verts[i].y /= count;
    }

    return mj;
}
int main(int argc, char** argv){
    Arguments args;
    ImageList *imagenames, *subject, *replicate;
    JetMasks masks;
    GraphDiscription gd;
    Image face;
    FaceGraph graph;
    int i;
    int imagenum = 0, numImage;
    
    processCommand(argc,argv, &args);

    masks = readMasksFile(args.masksFile);
    imagenames = getImageNames(args.imageFile, &numImage);
    
    for(subject = imagenames; subject != NULL; subject = subject->next_subject){
        for(replicate = subject; replicate != NULL; replicate = replicate->next_replicate){
            imagenum++;
            printf("Processing: %s (%5d of %5d) %5.2f%%   \n" , replicate->filename, imagenum, numImage, imagenum*100.0/numImage); fflush(stdout);

            gd = readGraphDiscription(makePath(args.graphDir,replicate->filename));
            face = readRawImage(makePath(args.imageDir,replicate->filename));
            graph = makeFaceGraph(gd->numVert, gd->numVert+gd->numEdge);
            graph->params =masks->params;

            for( i = 0; i < gd->numVert; i++){
                graph->jets[i] = extractJet(gd->verts[i].x,gd->verts[i].y,face,masks);
            }

            for( i = 0; i < gd->numEdge; i++){

                double x = 0.5*(gd->verts[gd->edges[i].vert1].x + gd->verts[gd->edges[i].vert1].x);
                double y = 0.5*(gd->verts[gd->edges[i].vert1].y + gd->verts[gd->edges[i].vert1].y);

                graph->jets[ gd->numVert + i ] = extractJet(x,y,face,masks);
            }

            saveFaceGraph(makePath(args.outputDir,replicate->filename),graph);
            freeImage(face);
            freeGraphDiscription(gd);
            freeFaceGraph(graph);
        }
    }
    printf("\n");

    return 0;
}
示例#15
0
int
main( int argc, char** argv )
{
   char* 		szInputFile 	= "disparity.pgm";
   char* 		szOutputFile 	= "disparity-scaled.pgm";
   unsigned char	ucMinOut	= 90;
   unsigned char	ucMaxOut	= 255;

   switch ( argc )
   {
      case 5:
	 ucMinOut 	= (unsigned char) atoi( argv[3] );
	 ucMaxOut 	= (unsigned char) atoi( argv[4] );
	 // deliberately fall through to 3-parm case
      case 3:
	 szInputFile	= argv[1];
	 szOutputFile	= argv[2];
	 break;
      case 1:
	 // use default parameters
	 break;
      default:
	 printf( "Usage: scaleimage <input pgm> <output pgm> [<min out> <max out>]\n" );
	 return 1;
   }

   // Load the bit image from file 
   TriclopsImage image;
   if ( !pgmReadToTriclopsImage( szInputFile,  &image ) )
   {
      printf( "pgmReadToTriclopsImage() failed. Can't read '%s'\n", szInputFile );
      return 1;
   }

   // scale the output image
   scaleImage( &image, ucMinOut, ucMaxOut );

   triclopsSaveImage( &image, szOutputFile );
   
   // clean up memory allocated in context
   freeImage( &image );
   
   return 0;
}
示例#16
0
文件: ccgview.cpp 项目: bashrc/ccg
void CcgView::showGraph()
{
    if (!fileExists(result_filename)) {
        printf("File not found: %s\n", result_filename.toStdString().c_str());
        ui->pushButtonCalculate->setEnabled(true);
        statusLabel.setText("Ready");
        return;
    }

    if (result_filename.endsWith(".kml")) {
        // open KML file using Google Earth
        if (fileExists(result_filename)) {
            QUrl url(result_filename);
            QDesktopServices::openUrl(url);
        }
        ui->pushButtonCalculate->setEnabled(true);
        statusLabel.setText("Ready");
        return;
    }

    // free any previous image
    freeImage();

    // load the image
    image.load(result_filename);
    if (image.isNull()) {
        QMessageBox::information(this, "Display image","Error Loading image " + result_filename);
        ui->pushButtonCalculate->setEnabled(true);
        statusLabel.setText("Ready");
        return;
    }
    // display the image
    image_scene = new QGraphicsScene();
    image_item = new QGraphicsPixmapItem(QPixmap::fromImage(image));
    image_scene->setSceneRect(image.rect());
    ui->graphicsView->setScene(image_scene);
    ui->graphicsView->scene()->addItem(image_item);
    ui->graphicsView->fitInView(image.rect()); //, Qt::KeepAspectRatio);
    showingImage = true;
    ui->graphicsView->show();
    ui->pushButtonCalculate->setEnabled(true);
    statusLabel.setText("Ready");
}
示例#17
0
int main(int argc, char **argv)
{
    Image mandelbrot;
    int i;
    MPI_Status status;
    double t;

    /* Initialize MPI */
    MPI_Init (&argc, &argv);
    MPI_Comm_rank (MPI_COMM_WORLD, &rank);
    MPI_Comm_size (MPI_COMM_WORLD, &size);

    mandelbrot = makeImage(WIDTH, HEIGHT);

    interval = mandelbrot->height / size;
    start = rank * interval;

    t = MPI_Wtime();
    mandelbrotSet (-0.65, 0, 2.5/HEIGHT, mandelbrot);
    printf("process %d: %f\n", rank, MPI_Wtime()-t);

    /* reconstruct image */
    if (rank == 0) {
        for (i=start+interval; i<mandelbrot->height; ++i) {
            MPI_Recv(mandelbrot->imdata[i], mandelbrot->width, MPI_INT,
                    MPI_ANY_SOURCE, i, MPI_COMM_WORLD, &status);
        }
        writePPM (mandelbrot, "mandelbrot.ppm");
    } else {
        for (i=start; i<start+interval; ++i) {
            MPI_Send(mandelbrot->imdata[i], mandelbrot->width, MPI_INT, 0, i,
                    MPI_COMM_WORLD);
        }
    }

    freeImage(mandelbrot);

    MPI_Finalize ();
    return 0;
}
示例#18
0
void setPassword()
{
	Config cfg;
	char input[11];
	int len;

	#ifndef DEBUG
	footer_changemode = loadImageFromMemory(images[FOOTER_CHANGEMODE].data, images[FOOTER_CHANGEMODE].hdr.size);
	#endif
	while(1)
	{
		#ifdef DEBUG
		printf("\nEnter new password: "******"\nConfirm password: "******"\nPassword changed.");
			#else
			int temp;
			blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
			blitAlphaImageToScreen(0, 0, images[FOOTER_CHANGEMODE].hdr.w, images[FOOTER_CHANGEMODE].hdr.h, footer_changemode, images[FOOTER_CHANGEMODE].hdr.x, images[FOOTER_CHANGEMODE].hdr.y);
			blitAlphaImageToScreen(0, 0, images[TITLE_CONFIRMPASSWORD].hdr.w, images[TITLE_CONFIRMPASSWORD].hdr.h, title_confirmpassword, images[TITLE_CONFIRMPASSWORD].hdr.x, images[TITLE_CONFIRMPASSWORD].hdr.y);
			freeImage(title_confirmpassword);
			msg_passwordchanged = loadImageFromMemory(images[MSG_PASSWORDCHANGED].data, images[MSG_PASSWORDCHANGED].hdr.size);
			blitAlphaImageToScreen(0, 0, images[MSG_PASSWORDCHANGED].hdr.w, images[MSG_PASSWORDCHANGED].hdr.h, msg_passwordchanged, images[MSG_PASSWORDCHANGED].hdr.x, images[MSG_PASSWORDCHANGED].hdr.y);
			freeImage(msg_passwordchanged);
			for(temp = 0; temp < len; temp++)
			{
				blitAlphaImageToScreen(0, 0, images[MASK].hdr.w, images[MASK].hdr.h, mask, images[MASK].hdr.x+(temp*images[MASK].hdr.w), images[MASK].hdr.y);
			}
			sceDisplayWaitVblankStart();
			flipScreen();
			#endif
			sceKernelDelayThread(3000*1000);

			#ifdef DEBUG
			printf("\n\nPress X to require password only at reboot.\n\nPress O to require password always at XMB.");
			#else
			blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
			blitAlphaImageToScreen(0, 0, images[FOOTER_CHANGEMODE].hdr.w, images[FOOTER_CHANGEMODE].hdr.h, footer_changemode, images[FOOTER_CHANGEMODE].hdr.x, images[FOOTER_CHANGEMODE].hdr.y);
			title_requirepassword = loadImageFromMemory(images[TITLE_REQUIREPASSWORD].data, images[TITLE_REQUIREPASSWORD].hdr.size);
			blitAlphaImageToScreen(0, 0, images[TITLE_REQUIREPASSWORD].hdr.w, images[TITLE_REQUIREPASSWORD].hdr.h, title_requirepassword, images[TITLE_REQUIREPASSWORD].hdr.x, images[TITLE_REQUIREPASSWORD].hdr.y);
			freeImage(title_requirepassword);
			buttons = loadImageFromMemory(images[BUTTONS].data, images[BUTTONS].hdr.size);
			blitAlphaImageToScreen(0, 0, images[BUTTONS].hdr.w, images[BUTTONS].hdr.h, buttons, images[BUTTONS].hdr.x, images[BUTTONS].hdr.y);
			freeImage(buttons);
			sceDisplayWaitVblankStart();
			flipScreen();
			#endif

			SceCtrlLatch latch;
			sceCtrlSetSamplingCycle(0);
			sceCtrlSetSamplingMode(PSP_CTRL_MODE_DIGITAL);

			int skipped=0;
			while(1)
			{
				sceCtrlReadLatch(&latch);

				if(!skipped)
				{
					skipped=1;
					continue;
				}
				if (latch.uiMake & PSP_CTRL_CROSS)
				{
					cfg.onlyBoot = 1;
					break;
				}
				if (latch.uiMake & PSP_CTRL_CIRCLE)
				{
					cfg.onlyBoot = 0;
					break;
				}
				sceKernelDelayThread(10*1000);
			}

			sceKernelDelayThread(2000*1000);
			break;
		}
		else
		{
			#ifdef DEBUG
			printf("\nPasswords do not match.");
			#else
			int temp;
			blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
			blitAlphaImageToScreen(0, 0, images[FOOTER_CHANGEMODE].hdr.w, images[FOOTER_CHANGEMODE].hdr.h, footer_changemode, images[FOOTER_CHANGEMODE].hdr.x, images[FOOTER_CHANGEMODE].hdr.y);
			blitAlphaImageToScreen(0, 0, images[TITLE_CONFIRMPASSWORD].hdr.w, images[TITLE_CONFIRMPASSWORD].hdr.h, title_confirmpassword, images[TITLE_CONFIRMPASSWORD].hdr.x, images[TITLE_CONFIRMPASSWORD].hdr.y);
			freeImage(title_confirmpassword);
			msg_notmatch = loadImageFromMemory(images[MSG_NOTMATCH].data, images[MSG_NOTMATCH].hdr.size);
			blitAlphaImageToScreen(0, 0, images[MSG_NOTMATCH].hdr.w, images[MSG_NOTMATCH].hdr.h, msg_notmatch, images[MSG_NOTMATCH].hdr.x, images[MSG_NOTMATCH].hdr.y);
			freeImage(msg_notmatch);
			for(temp = 0; temp < len; temp++)
			{
				blitAlphaImageToScreen(0, 0, images[MASK].hdr.w, images[MASK].hdr.h, mask, images[MASK].hdr.x+(temp*images[MASK].hdr.w), images[MASK].hdr.y);
			}
			sceDisplayWaitVblankStart();
			flipScreen();
			#endif
			sceKernelDelayThread(3000*1000);
		}
	}
	#ifndef DEBUG
	freeImage(footer_changemode);
	#endif

	int result;
	result = sceIoUnassign("flash0:");

	if(result < 0)
	{
		#ifdef DEBUG
		printf("\nError in unassign flash0.");
		#endif
	}
	else
	{
		result = sceIoAssign("flash0:", "lflash0:0,0", "flashfat0:", IOASSIGN_RDWR, NULL, 0);
		if(result < 0)
		{
			#ifdef DEBUG
			printf("\nError in assigning flash0 for write.");
			#endif
		}
		else
		{
			SceUID fp;
			fp = sceIoOpen("flash0:/buttons.ini", PSP_O_WRONLY|PSP_O_TRUNC|PSP_O_CREAT, 0777);

			if(fp < 0)
			{
				#ifdef DEBUG
				printf("\nError writing flash0:/buttons.ini.");
				#endif
			}
			else
			{
				sceIoWrite(fp, &cfg, sizeof(cfg));
				sceIoClose(fp);
				#ifdef DEBUG
				printf("\nPassword written successfully.");
				#endif
			}
		}
	}
}
void convertImages(Arguments* args){
    FILE* list;
    JetMasks masks;
    int x, y,i,j;
    char imagename[MAX_FILENAME_LENGTH];
    char filename[MAX_FILENAME_LENGTH];
    
    MESSAGE("Creating gabor masks.");
    masks = readMasksFile(args->maskFile);

    if(args->saveMasks){
        for(y = 0; y < masks->size; y++){
            char outname[MAX_FILENAME_LENGTH];
            sprintf(outname, "mask%03d.pgm",y);
            writePGMImage(masks->masks[y],outname,0);
        }
    }

       
    list = fopen(args->imageList,"r");
    if(!list){
        printf("Error opening file: %s\n", args->imageList);
        exit(1);
    }

    while(fscanf(list, "%s", imagename) == 1){
        Image im;
        Image grid;
        
        sprintf(filename, "%s/%s", args->inputDir, imagename);
        im = readRawImage(filename);
        MESSAGE1ARG("Processing file: %s",filename);

        /* Find the number of points in the grid */
        
        i = 0;
        for( x = args->gridStartX; x < im->width; x += args->gridSpaceX){
            for( y = args->gridStartY; y < im->height; y+= args->gridSpaceY){
                i++;
            }
        }
        
        grid = makeImage(i,masks->size,1);

        /* Compute convolutions */
        i = 0;
        for( x = args->gridStartX; x < im->width; x += args->gridSpaceX){
            for( y = args->gridStartY; y < im->height; y+= args->gridSpaceY){
                for(j = 0; j < masks->size; j++){
                    if( i < grid->width )
                        IE(grid,i,j,0) = convolvePoint(x, y, 0, im, masks->masks[j]);
                }
                i++;
            }
            
        }

        sprintf(filename, "%s/%s", args->sfiDir, imagename);
        writeRawImage(grid,filename);

        freeImage(grid);
        freeImage(im);

    }

    
    fclose(list);
   
}
示例#20
0
ARPattern::~ARPattern()
{
	freeImage();
}
示例#21
0
int
main (int argc, const char* const argv[])
{
    char garbage[2];
    int command;
    double sigma;

    if (4 > argc || 5 < argc) {
        fprintf (stderr, 
	         "syntax: %s <input file> <output file> <command #> ...\n", 
	         argv[0]);
        return 2;
    }

    if (1 != sscanf (argv[3], "%d%1s", &command, garbage) || 
        1 > command || 3 < command) {
	fprintf (stderr, "Command must be from 1 to 3.\n");
	fprintf (stderr, "  1 -- gaussian filter   <sigma>\n");
	fprintf (stderr, "  2 -- greyscale\n");
	fprintf (stderr, "  3 -- invert colors\n");
	return 2;
    }

    if (1 == command && 
        (5 != argc ||
         1 != sscanf (argv[4], "%lf%1s", &sigma, garbage) || 
	 0 >= sigma || 100 <= sigma)) {
    	fprintf (stderr, "Sigma must be greater than 0 and less than 100.\n");
	return 2;
    }

    Image* inputImage = decode (argv[1]);
    printf ("Width: %d, height: %d\n", inputImage->width, inputImage->height);
    Image* outputImage = generateOutput (inputImage);

    int height = inputImage->height;
    int width  = inputImage->width;
    uint8_t* inRed    = inputImage->redChannel;
    uint8_t* inBlue   = inputImage->blueChannel;
    uint8_t* inGreen  = inputImage->greenChannel;
    uint8_t* inAlpha  = inputImage->alphaChannel;
    uint8_t* outRed   = outputImage->redChannel;
    uint8_t* outBlue  = outputImage->blueChannel;
    uint8_t* outGreen = outputImage->greenChannel;
    uint8_t* outAlpha = outputImage->alphaChannel;

    switch (command) {
	case 1: {
	    int radius = ceil (3 * sigma);
	    int fSize = 1 + 2 * radius;
	    double* gauss = malloc (sizeof (gauss[0]) * fSize * fSize);
	    gaussianFilter (gauss, sigma);
	    convolveImage (width, height, inRed, inGreen, inBlue, inAlpha, 
			   radius, gauss, outRed, outGreen, outBlue, outAlpha);
	    encode (argv[2], outputImage);
	    break;
	}
	case 2:
	    greyscale (width, height, inRed, inGreen, inBlue, inAlpha, 
	               gMonoMult, outRed, outGreen, outBlue, outAlpha);
	    encode (argv[2], outputImage);
	    break;
	case 3:
	    invertColors (width, height, inRed, inGreen, inBlue, inAlpha, 
	    		  outRed, outGreen, outBlue, outAlpha);
	    encode (argv[2], outputImage);
	    break;
    }

    freeImage (inputImage);
    freeImage (outputImage);

    return 0;
}
示例#22
0
int main(int argc, char **argv) {

    int commandArgs = 1;
    int i;
    char x;
    char performContrast = 0;
    char fft_filename[FILENAME_LENGTH];
    char cdf_filename[FILENAME_LENGTH];
    char histo_filename[FILENAME_LENGTH];
    float contrastLow = 0.0;
    float contrastHigh = 0.0;
    float highpasslevel;
    float lowpasslevel;
    float percentCorrupt;
    float sigma;
    float brightness;
    float sat;
    int m;
    int replaceWithM;
    int performHistogram = 0;
    int performCDF = 0;
    int performFFT = 0;
    int performVectorMedianFilter = 0;
    int performMedianFilter = 0;
    int performMeanFilter = 0;
    int performSpacialFilter = 0;
    int performLevelSlicing = 0;
    int performEqualize = 0;
    int performColorScale = 0;
    int performSpatialReduceWidth  = 0;
    int performSpatialReduceHeigth = 0;
    int performHighpass = 0;
    int performLowpass = 0;
    int performComponentMedianFilter = 0;
    int performVectorOrderStatistic = 0;
    int performVectorSpacialOrderStatistic = 0;
    int performVectorMedianOrderStatistic = 0;
    int performMinkowskiAddition = 0;
    int performMinkowskiSubtraction = 0;
    int performMinkowskiOpening = 0;
    int performMinkowskiClosing = 0;
    int performEdgeDetectOne = 0;
    int performEdgeDetectTwo = 0;
    int performEdgeDetectThree = 0;
    int performEdgeDetectFour = 0;
    int performAddGaussianNoise = 0;
    int performAddSaltPepperNoise = 0;
    int performSetBrightness = 0;
    int performSetSaturation = 0;
    int performBrightFilter = 0;
    int imageWriteNecessary = 0;
    int maskwidth = 0;
    int maskheight = 0;
    int maskrepeat = 0;
    FILE *in = stdin;
    FILE *out = stdout;
    struct portImage *pi;

    if (argc < 3) {
        printf("\n");
        printf("  Usage: %s [inputFile] ([outputFile]) [option] ([option] ...)\n", argv[0]);
        printf("\n");
        printf("  InputFile: Either a filename or '-' for stdin.\n");
        printf("  OutputFile: Either a filename or '-' for stdout. (Not needed if no output necessary.)\n");
        printf("\n");
        printf("  Options:\n");
        printf("  -ghisto FILENAME       Graph Histogram\n");
        printf("  -gcdf FILENAME         Graph Cumulative Distribution\n");
        printf("  -gfft FILENAME         Graph FFT plot\n");
        printf("  -color n               Reduce color scale to n\n");
        printf("  -spatial WIDTH-HEIGHT  Perform spacial reduction to Width and Height\n");
        printf("  -level n               Perform level slicing from graylevel n to graylevel n+10\n");
        printf("  -con LOW-HIGH          Scale image contrast from LOW graylevel percentage to HIGH graylevel percentage\n");
        printf("  -equ                   Histogram Eqaulization\n");
        printf("  -medianf n             Simple Median Filter of window size n*n\n");
        printf("  -meanf n               Simple Mean Filter of window size n*n\n");
        printf("  -cmf n                 Component Median Filter of window size n*n\n");
        printf("  -vmf n                 Vector Median Filter of window n*n\n");
        printf("  -sf                    Spacial Filter\n");
        printf("  -vos n v               Vector Order Stat of window size n*n and value v\n");
        printf("  -vmos n m [01]         Vector Median Order Stat of window size n*n, m threshold, and 0 or 1(True) replace with m\n");
        printf("  -vsos n m [01]         Vector Spacial Order Stat of window size n*n, m threshold, and 0 or 1(True) replace with m\n");
        printf("  -brightf n             Perform an Brightness filter using HSV colorspace on size n*n window.\n");
        printf("  -bright %%              Set brightness to %% percent\n");
        printf("  -sat %%                 Set saturation to %% percent\n");
        printf("  -hp %%                  Highpass filter of %% percent\n");
        printf("  -lp %%                  Lowpass filter of %% percent\n");
        printf("  -ma NxM R              Perform Minkowski Addition using NxM mask, repeated R times.\n");
        printf("  -ms NxM R              Perform Minkowski Subtraction using NxM mask, repeated R times.\n");
        printf("  -mo NxM R              Perform Minkowski Opening using NxM mask, repeated R times.\n");
        printf("  -mc NxM R              Perform Minkowski Closing using NxM mask, repeated R times.\n");
        printf("  -e1                    Perform Edge Detection using X/(X – B)\n");
        printf("  -e2                    Perform Edge Detection using (X + B)/X\n");
        printf("  -e3                    Perform Edge Detection using [(X+B)/(X-B)]-B\n");
        printf("  -e4 n                  Experimental Edge Detection on Color Images using n*n window.\n");
        printf("  -noiseG p s            Add Gaussian noise to p (0 to 1 floating) percent of image with s sigma noise.\n");
        printf("  -noiseSP p             Add Salt and Pepper noise to p (0 to 1 floating) percent of image.\n");
        printf("\n");
        return(1);
    }

    if (strcmp(argv[commandArgs], "-") != 0) {
        in = fopen(argv[1],"r");

        if (in == NULL) {
            fprintf(stderr, "File '%s' failed to open for reading.\n", argv[1]);
            exit(1);
        }
    }
    commandArgs++;

    if (strcmp(argv[commandArgs], "-") != 0 && argv[commandArgs][0] != '-') {
        commandArgs++;
        out = fopen(argv[2],"w");

        if (out == NULL) {
            fprintf(stderr, "File '%s' failed to open for writing.\n", argv[2]);
            exit(1);
        }
    }

    for (; commandArgs < argc; commandArgs++) {
        if (strcmp(argv[commandArgs], "-color") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performColorScale);
        }

        if (strcmp(argv[commandArgs], "-spatial") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d%c%d", &performSpatialReduceWidth, &x, &performSpatialReduceHeigth);
        }

        if (strcmp(argv[commandArgs], "-level") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performLevelSlicing);
        }

        if (strcmp(argv[commandArgs], "-con") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%f%c%f", &contrastLow, &performContrast, &contrastHigh);
        }

        if (strcmp(argv[commandArgs], "-vos") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performVectorOrderStatistic);
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &m);
        }

        if (strcmp(argv[commandArgs], "-vmf") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performVectorMedianFilter);
        }

        if (strcmp(argv[commandArgs], "-sf") == 0) {
            imageWriteNecessary = 1;
            performSpacialFilter = 1;
        }

        if (strcmp(argv[commandArgs], "-vmos") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performVectorMedianOrderStatistic);
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &m);
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &replaceWithM);
        }

        if (strcmp(argv[commandArgs], "-vsos") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performVectorSpacialOrderStatistic);
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &m);
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &replaceWithM);
        }

        if (strcmp(argv[commandArgs], "-cmf") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performComponentMedianFilter);
        }

        if (strcmp(argv[commandArgs], "-medianf") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performMedianFilter);
        }

        if (strcmp(argv[commandArgs], "-meanf") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performMeanFilter);
        }

        if (strcmp(argv[commandArgs], "-equ") == 0) {
            imageWriteNecessary = 1;
            performEqualize = 1;
        }

        if (strcmp(argv[commandArgs], "-hp") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            performHighpass = 1;
            sscanf(argv[commandArgs], "%f", &highpasslevel);
        }

        if (strcmp(argv[commandArgs], "-lp") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            performLowpass = 1;
            sscanf(argv[commandArgs], "%f", &lowpasslevel);
        }

        if (strcmp(argv[commandArgs], "-brightf") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performBrightFilter);
        }

       if (strcmp(argv[commandArgs], "-bright") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            performSetBrightness = 1;
            sscanf(argv[commandArgs], "%f", &brightness);
        }

        if (strcmp(argv[commandArgs], "-sat") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            performSetSaturation = 1;
            sscanf(argv[commandArgs], "%f", &sat);
        }

        if (strcmp(argv[commandArgs], "-ghisto") == 0) {
            commandArgs++;
            performHistogram = 1;
            strncpy(histo_filename, argv[commandArgs], FILENAME_LENGTH);
        }

        if (strcmp(argv[commandArgs], "-gcdf") == 0) {
            commandArgs++;
            performCDF = 1;
            strncpy(cdf_filename, argv[commandArgs], FILENAME_LENGTH);
        }

        if (strcmp(argv[commandArgs], "-gfft") == 0) {
            commandArgs++;
            performFFT = 1;
            strncpy(fft_filename, argv[commandArgs], FILENAME_LENGTH);
        }

        if (strcmp(argv[commandArgs], "-ma") == 0) {
            imageWriteNecessary = 1;
            performMinkowskiAddition = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d%c%d", &maskwidth, &x, &maskheight);
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &maskrepeat);
        }

        if (strcmp(argv[commandArgs], "-ms") == 0) {
            imageWriteNecessary = 1;
            performMinkowskiSubtraction = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d%c%d", &maskwidth, &x, &maskheight);
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &maskrepeat);
        }

        if (strcmp(argv[commandArgs], "-mo") == 0) {
            imageWriteNecessary = 1;
            performMinkowskiOpening = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d%c%d", &maskwidth, &x, &maskheight);
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &maskrepeat);
        }

        if (strcmp(argv[commandArgs], "-mc") == 0) {
            imageWriteNecessary = 1;
            performMinkowskiClosing = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d%c%d", &maskwidth, &x, &maskheight);
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &maskrepeat);
        }

        if (strcmp(argv[commandArgs], "-e1") == 0) {
            imageWriteNecessary = 1;
            performEdgeDetectOne = 1;
        }

        if (strcmp(argv[commandArgs], "-e2") == 0) {
            imageWriteNecessary = 1;
            performEdgeDetectTwo = 1;
        }

        if (strcmp(argv[commandArgs], "-e3") == 0) {
            imageWriteNecessary = 1;
            performEdgeDetectThree = 1;
        }

        if (strcmp(argv[commandArgs], "-e4") == 0) {
            imageWriteNecessary = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%d", &performEdgeDetectFour);
        }

        if (strcmp(argv[commandArgs], "-noiseG") == 0) {
            imageWriteNecessary = 1;
            performAddGaussianNoise = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%f", &percentCorrupt);
            commandArgs++;
            sscanf(argv[commandArgs], "%f", &sigma);
        }

        if (strcmp(argv[commandArgs], "-noiseSP") == 0) {
            imageWriteNecessary = 1;
            performAddSaltPepperNoise = 1;
            commandArgs++;
            sscanf(argv[commandArgs], "%f", &percentCorrupt);
        }
    }

    pi = readImage(in);

    if (performHighpass || performLowpass || performFFT) {
        FFT2D(pi);
        if (performHighpass)  highpass(pi, highpasslevel);
        if (performLowpass)   lowpass(pi, lowpasslevel);
        if (performFFT)       graph_fftlogplot(pi, fft_filename);
        IFFT2D(pi);
    }

    if (performEdgeDetectOne || performEdgeDetectTwo || performEdgeDetectThree ||
        performMinkowskiAddition || performMinkowskiSubtraction || performMinkowskiOpening || performMinkowskiClosing)
        thresholdImage(pi);

    if (performAddGaussianNoise)             addGaussianNoise(pi, percentCorrupt, sigma);
    if (performAddSaltPepperNoise)           addSaltPepperNoise(pi, percentCorrupt);
    if (performMedianFilter)                 simpleMedianFilter(pi, performMedianFilter);
    if (performMeanFilter)                   simpleMeanFilter(pi, performMeanFilter);
    if (performComponentMedianFilter)        componentMedianFilter(pi, performComponentMedianFilter);
    if (performVectorOrderStatistic)         vectorOrderStatistic(pi, performVectorOrderStatistic, m);
    if (performVectorSpacialOrderStatistic)  vectorSpacialOrderStatistic(pi, performVectorSpacialOrderStatistic, m, replaceWithM);
    if (performVectorMedianOrderStatistic)   vectorMedianOrderStatistic(pi, performVectorMedianOrderStatistic, m, replaceWithM);
    if (performVectorMedianFilter)           vectorMedianFilter(pi, performVectorMedianFilter);
    if (performSpacialFilter)                spacialFilter(pi);
    if (performBrightFilter)                 HSV_ValueFilter(pi, performBrightFilter);
    if (performColorScale)                   scale_reduce(pi,performColorScale);
    if (performSetBrightness)                setBrightness(pi,brightness);
    if (performSetSaturation)                setSaturation(pi,sat);
    if (performSpatialReduceWidth)           spacial_reduce(pi,performSpatialReduceWidth, performSpatialReduceHeigth);
    if (performContrast)                     contrast_stretching(pi, contrastLow, contrastHigh);
    if (performLevelSlicing)                 level_slice(pi, performLevelSlicing);
    if (performEqualize)                     equalize(pi);
    if (performHistogram)                    graph_histogram(pi, histo_filename);
    if (performCDF)                          graph_cdf(pi, cdf_filename);

    if (performMinkowskiAddition)
        for (i = 0; i < maskrepeat; i++)
            minkowskiAddition(pi, maskwidth, maskheight);

    if (performMinkowskiSubtraction)
        for (i = 0; i < maskrepeat; i++)
            minkowskiSubtraction(pi, maskwidth, maskheight);

    if (performMinkowskiOpening)
        for (i = 0; i < maskrepeat; i++)
            minkowskiOpening(pi, maskwidth, maskheight);

    if (performMinkowskiClosing)
        for (i = 0; i < maskrepeat; i++)
            minkowskiClosing(pi, maskwidth, maskheight);

    if (performEdgeDetectOne) {
        struct portImage *pc = copyImage(pi);
        imageWriteNecessary = 1;

        minkowskiSubtraction(pc, 3, 3);
        minkowskiDivision(pi, pc);

        freeImage(pc);
    }

    if (performEdgeDetectTwo) {
        struct portImage *pc = copyImage(pi);
        imageWriteNecessary = 1;

        minkowskiAddition(pi, 3, 3);
        minkowskiDivision(pi, pc);

        freeImage(pc);
    }

    if (performEdgeDetectThree) {
        struct portImage *pd = copyImage(pi);
        maskrepeat = 3;
        imageWriteNecessary = 1;

        for (i = 0; i < maskrepeat; i++) {
            minkowskiAddition(pi, 3, 3);
            minkowskiSubtraction(pd, 3, 3);
        }

        minkowskiDivision(pi, pd);
        minkowskiSubtraction(pi, 3, 3);

        freeImage(pd);
    }

    if (imageWriteNecessary)
        writeImage(pi, out);

    freeImage(pi);
    if (in  != stdin)  fclose(in);
    if (out != stdout) fclose(out);
    return 0;
} /* End Main */
示例#23
0
int hrt_main (int argc, char **argv) 
{
    int flag;

    int i;

    // detection parameters
    float scaleFactor = 1.2;
    int minNeighbours = 3;
    int size;

    printf("-- entering main function --\r\n");

    printf("-- loading image --\r\n");

    MyImage imageObj;
    MyImage *image = &imageObj;

    flag = readPgm((char *)INPUT_FILENAME, image);
    if (flag == -1)
    {
        printf( "Unable to open input image\n");
        return 1;
    }

    printf("-- loading cascade classifier --\r\n");

    myCascade cascadeObj;
    myCascade *cascade = &cascadeObj;
    MySize minSize = {20, 20};
    MySize maxSize = {0, 0};

    // classifier properties
    cascade->n_stages=25;
    cascade->total_nodes=2913;
    cascade->orig_window_size.height = 24;
    cascade->orig_window_size.width = 24;

    readTextClassifier(cascade);

    struct MyRect *result[NUM] = {};

    //Load the program 
    hrt_cell_load_program_id(CELL, haar);

    hrt_scalar_store(CELL, MyImage, myimage, image);
    hrt_indexed_store(CELL, MySize, mysize, 0, minSize);
    hrt_indexed_store(CELL, MySize, mysize, 1, maxSize);
    hrt_scalar_store(CELL, myCascade, mycascade, cascade);
    hrt_scalar_store(CELL, float, scalefactor, scaleFactor);
    hrt_scalar_store(CELL, int, minneighbours, minNeighbours); 
    hrt_scalar_store(CELL, MyRect, myrect, result); 

    printf("-- detecting faces --\r\n");
    
    //size = detectObjects(image, minSize, maxSize, cascade, scaleFactor, minNeighbours, result);
    detectObjects();
    size = hrt_scalar_load(CELL, int, size);


    printf("-- drawing boxes --\r\n");
    for(i = 0; i < NUM; i++ )
    {
        if ( result[i] != NULL) {
            struct MyRect *r = result[i];
            drawRectangle(image, r);
        }
        else
            break;
    }

    printf("-- saving output --\r\n");
    flag = writePgm((char *)OUTPUT_FILENAME, image);

    printf("-- image saved --\r\n");

    //    delete image and free classifier
    releaseTextClassifier(cascade);
    freeImage(image);

    

    return 0;
}
示例#24
0
int main(int argc, char** argv) {

	PPMImage *image;
        
	if(argc > 1) {
		image = readPPM("flower.ppm");
	} else {
		image = readStreamPPM(stdin);
	}

	AccurateImage *imageUnchanged = convertImageToNewFormat(image); // save the unchanged image from input image
	AccurateImage *imageBuffer = createEmptyImage(image);
	AccurateImage *imageSmall = createEmptyImage(image);
	AccurateImage *imageBig = createEmptyImage(image);
	
	PPMImage *imageOut;
	imageOut = (PPMImage *)malloc(sizeof(PPMImage));
	imageOut->data = (PPMPixel*)malloc(image->x * image->y * sizeof(PPMPixel));

	// Process the tiny case:
	performNewIdeaIteration(imageSmall, imageUnchanged, 2);
	performNewIdeaIteration(imageBuffer, imageSmall, 2);
	performNewIdeaIteration(imageSmall, imageBuffer, 2);
	performNewIdeaIteration(imageBuffer, imageSmall, 2);
	performNewIdeaIteration(imageSmall, imageBuffer, 2);
	
	// Process the small case:
	performNewIdeaIteration(imageBig, imageUnchanged,3);
	performNewIdeaIteration(imageBuffer, imageBig,3);
	performNewIdeaIteration(imageBig, imageBuffer,3);
	performNewIdeaIteration(imageBuffer, imageBig,3);
	performNewIdeaIteration(imageBig, imageBuffer,3);
	
	// save tiny case result
	performNewIdeaFinalization(imageSmall,  imageBig, imageOut);
	if(argc > 1) {
		writePPM("flower_tiny.ppm", imageOut);
	} else {
		writeStreamPPM(stdout, imageOut);
	}

	
	// Process the medium case:
	performNewIdeaIteration(imageSmall, imageUnchanged, 5);
	performNewIdeaIteration(imageBuffer, imageSmall, 5);
	performNewIdeaIteration(imageSmall, imageBuffer, 5);
	performNewIdeaIteration(imageBuffer, imageSmall, 5);
	performNewIdeaIteration(imageSmall, imageBuffer, 5);
	
	// save small case
	performNewIdeaFinalization(imageBig,  imageSmall,imageOut);
	if(argc > 1) {
		writePPM("flower_small.ppm", imageOut);
	} else {
		writeStreamPPM(stdout, imageOut);
	}

	// process the large case
	performNewIdeaIteration(imageBig, imageUnchanged, 8);
	performNewIdeaIteration(imageBuffer, imageBig, 8);
	performNewIdeaIteration(imageBig, imageBuffer, 8);
	performNewIdeaIteration(imageBuffer, imageBig, 8);
	performNewIdeaIteration(imageBig, imageBuffer, 8);

	// save the medium case
	performNewIdeaFinalization(imageSmall,  imageBig, imageOut);
	if(argc > 1) {
		writePPM("flower_medium.ppm", imageOut);
	} else {
		writeStreamPPM(stdout, imageOut);
	}
	
	// free all memory structures
	freeImage(imageUnchanged);
	freeImage(imageBuffer);
	freeImage(imageSmall);
	freeImage(imageBig);
	free(imageOut->data);
	free(imageOut);
	free(image->data);
	free(image);
	
	return 0;
}
	void
		Java_java_awt_Toolkit_imgFreeImage( JNIEnv* env, jclass clazz, Image * img)
	{
		freeImage( X, img);
	}	
void main()
{
	int iServerSock;
	int iClientSock;

	struct sockaddr_in ServerAddr;
	struct sockaddr_in ClientAddr;


	int sin_size;

	WSADATA WSAData;

	if (WSAStartup(MAKEWORD(1, 1), &WSAData))
	{

		printf("initializationing error!\n");
		WSACleanup();
		exit(0);
	}
	printf("Initialization\n");

	if ((iServerSock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
	{
		printf("Fail to create socket!\n");
		WSACleanup();
		exit(0);
	}
	printf("Create Socket!\n");

	ServerAddr.sin_family = AF_INET;
	//ServerAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	ServerAddr.sin_addr.s_addr = inet_addr("172.20.233.1");
	ServerAddr.sin_port = htons((u_short)PORT);
	//ServerAddr.sin_port = 0;

	memset(&(ServerAddr.sin_zero), 0, sizeof(ServerAddr.sin_zero));

	if (bind(iServerSock, (struct sockaddr *)&ServerAddr, sizeof(struct sockaddr)) == -1)
	{
		printf("bind fail!\n");
		WSACleanup();
		exit(0);
	}
	printf("Bind success!\n");

	if (listen(iServerSock, BACKLOG) == -1)
	{
		printf("listen fail!\n");
		WSACleanup();
		exit(0);
	}
	printf("Listen Success!\n");

	for (;;)
	{
		sin_size = sizeof(struct sockaddr_in);
		iClientSock = accept(iServerSock, (struct sockaddr *)&ClientAddr, &sin_size);

		if (iClientSock == -1)
		{
			printf("accept调用失败!\n");
			exit(0);
		}
		printf("Accept Success\n");

		printf("Server is connected to%s\n", inet_ntoa(ClientAddr.sin_addr));


		//接受来自客户端的数据存入recvques
		//char recvques[100];//用户选择的文件号
		//memset(recvques, 0, sizeof(recvques));
		//recv(iClientSock, recvques, 100, 0);
		//printf("Receive %c from Client\n", recvques[0]);
		//

		int getSize;

		char* recvImage = receiveImageFromClient(iClientSock, &getSize);

		size_t length = getSize;

		if (recvImage == NULL)
		{
			printf("从client接收失败!\n");
			WSACleanup();
			exit(0);
		}
		else
		{
			printf("Successfully receive from Client!\n");
		}


		//第一次传输结束
		printf("\n");
		printf("opencv running。。。。\n");
		printf("\n");
		printf("\n");

		int stat;
		char buffer[50] = "Opencv is processing the Image...";
		const char* opencvSignal = buffer;
		//Send our verification signal
		do{
			stat = send(iClientSock, opencvSignal, strlen(opencvSignal) + 1, 0);
		} while (stat<0);


		int imageSendSize;
		printf("start image processing\n");
		printf("\n");
		printf("\n");

		void *sendImageVoid = FundusSegmentServer(recvImage, getSize, &imageSendSize);
		char *sendImage = (char *)sendImageVoid;


		char buffer2[100] = "Image processing is finished, start Transmit image to Client!";
		const char* opencvfinishSignal = buffer2;
		//Send our verification signal
		do{
			stat = send(iClientSock, opencvfinishSignal, strlen(opencvfinishSignal) + 1, 0);
		} while (stat<0);

		//第二次传输开始
		printf("Start send the segmentation Image to Client!\n");


		int sendStatus = sendImageToClient(iClientSock, sendImage, imageSendSize);
		if (sendStatus != 1)
		{
			printf("Send to Client失败!\n");
			WSACleanup();
			exit(0);
		}
		if (sendStatus == 1)
		{
			printf("Send to Client success!\n");
		}

		freeImage(sendImage);


		closesocket(iClientSock);

	}
}
void convertImages(Arguments* args){
    char** mask = NULL;
    TwoPoints source, dest;
    FILE* eyeList;
    char line[ FILE_LINE_LENGTH ];
    char filename[MAX_FILENAME_LENGTH];
    char imagename[MAX_FILENAME_LENGTH];
    char suffix[MAX_FILENAME_LENGTH];
    int i;

    scaleArgs(args, args->scale);

    dest.x1 = args->eyeLx;
    dest.y1 = args->eyeLy;
    dest.x2 = args->eyeRx;
    dest.y2 = args->eyeRy;

    /* Prepare file suffix encoding preprocessing settings, blank if not requested */
    if (args->configSuffix) {
        sprintf(suffix,"_%s", imageSuffix(args)); }
    else {
        suffix[0] = '\0'; }	

    if(args->maskType == CL_YES){
        MESSAGE("Creating Mask.");
        mask = generateMask(args->sizeWidth, args->sizeHeight, args->ellipseX, args->ellipseY, args->ellipseA, args->ellipseB);
    }

    eyeList = fopen(args->eyeFile,"r");
    DEBUG_CHECK(eyeList,"Error opening eye coordinates file");

    for(i = 1;;i++){
        Image pgm;
        Image geo;
        Matrix transform;

        fgets(line, FILE_LINE_LENGTH, eyeList);
        if(feof(eyeList)) break;

        if(sscanf(line,"%s %lf %lf %lf %lf",filename, &(source.x1), &(source.y1), &(source.x2), &(source.y2)) != 5){
            printf("Error parsing line %d of eye coordinate file. Exiting...",i);
            exit(1);
        }

        /* shift the eye coordinates if neccessary */
        source.x1 += args->shiftX;
        source.y1 += args->shiftY;
        source.x2 += args->shiftX;
        source.y2 += args->shiftY;

        sprintf(imagename,"%s\\%s.pgm",args->inputDir,filename);

        MESSAGE1ARG("Processing image: %s",filename);

        pgm = readPGMImage(imagename);

        if(args->histType == HIST_PRE){
            DEBUG(1,"   Performing Pre Histogram Equalization.");
            histEqual(pgm,256);
        }

        if(args->preNormType == CL_YES){
            DEBUG(1,"   Performing Pre Pixel Normalization.");
            ZeroMeanOneStdDev(pgm);
        }

        if(args->preEdge){
            smoothImageEdge(pgm, args->preEdge);
        }

        if(args->geoType == CL_YES){
            DEBUG(1,"   Performing Geometric Normalization.");
            transform = generateTransform(&source,&dest,args->reflect);
            geo = transformImage(pgm,args->sizeWidth,args->sizeHeight,transform);
        }
        else{
            transform = makeIdentityMatrix(3);
            geo = transformImage(pgm,args->sizeWidth,args->sizeHeight,transform);
        }

        if(args->noise != 0.0){
            DEBUG(1,"   Adding Gausian Noise.");
            gaussianNoise(geo,args->noise);
        }


        if(args->histType == HIST_POST){
            DEBUG(1,"   Performing Post Histogram Equalization.");
            histEqualMask(geo,256, (const char**) mask);
        }

        if(args->nrmType == CL_YES){
            DEBUG(1,"   Performing final value normalization and Applying Mask.");
            ZeroMeanOneStdDevMasked(geo, (const char **) mask);
        }
        else{
            DEBUG(1,"   No Value Normalization. Just Applying Mask.");
            applyMask(geo, (const char **) mask);
        }

        if(args->postEdge){
            smoothImageEdge(geo, args->postEdge);
        }

        if(args->nrmDir){
            sprintf(imagename,"%s\\%s%s.nrm", args->nrmDir, filename, suffix);
            DEBUG_STRING(1,"   Saving nrm: %s",imagename);
            writeFeretImage(geo,imagename);
        }
        if(args->pgmDir){
            sprintf(imagename,"%s\\%s%s.pgm", args->pgmDir, filename, suffix);
            DEBUG_STRING(1,"   Saving pgm: %s",imagename);
            writePGMImage(geo,imagename,0);
        }
        if(args->sfiDir){
            sprintf(imagename,"%s\\%s%s.sfi", args->sfiDir, filename, suffix);
            DEBUG_STRING(1,"   Saving sfi: %s",imagename);
            writeRawImage(geo,imagename);
        }

        freeImage(geo);
        freeImage(pgm);
        freeMatrix(transform);
    }

    fclose(eyeList);

}
示例#28
0
文件: main.c 项目: dyjhhh/dong28
int main(int argc,char *argv[])
{
  //Handles user input
  if(argc<4 || argc>5)
  {
    printf("Incorrect number of arguments\n");
    printf("Number of arguments: %d\n",argc);
    exit(1);
  }

  //const char *inputFilename=argv[1];
  const char *inputFilename=argv[1];
  printf("Inputfile: %s\n",inputFilename);
  const char *outputFilename=argv[2];
  char garbage[2];
  int command;
  double sigma=3;

  if(1!=sscanf(argv[3],"%d%1s",&command,garbage) || command<0 || command>11)
  {
    printf("Incorrect command\n");
    exit(1);
  }

  if(command>0 && command<11 && argc==5)
  {
    printf("Incorrect number of arguments, exclude the sigma value");
    exit(1);
  }

  if(((command==0 || command==11) && argc==5 && 1!=sscanf(argv[4],"%lf%1s",&sigma,garbage)) || sigma<0)
  {
    printf("Incorrect sigma value\n");
    exit(1);
  }

  Filter *filters=initializeFilters(sigma);
  Image *inputImage=decode(inputFilename);
  printf("Width: %d, height: %d\n",inputImage->width,inputImage->height);
  Image *outputImage=generateOutput(inputImage);

  uint8_t *inRed=inputImage->redChannel;
  uint8_t *inBlue=inputImage->blueChannel;
  uint8_t *inGreen=inputImage->greenChannel;
  uint8_t *inAlpha=inputImage->alphaChannel;
  uint8_t *outRed=outputImage->redChannel;
  uint8_t *outBlue=outputImage->blueChannel;
  uint8_t *outGreen=outputImage->greenChannel;
  uint8_t *outAlpha=outputImage->alphaChannel;
  int height=inputImage->height;
  int width=inputImage->width;
  switch(command)
  {
    case(0):
    {
      convolveImage(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
                    outAlpha,filters[0].filter,filters[0].radius,width,height);
      break;
    }
    case(1):
    {
      convolveImage(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
                    outAlpha,filters[1].filter,filters[1].radius,width,height);
      break;
    }
    case(2):
    {
      convolveImage(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
                    outAlpha,filters[2].filter,filters[2].radius,width,height);
      break;
    }
    case(3):
    {
      convolveImage(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
                    outAlpha,filters[3].filter,filters[3].radius,width,height);
      break;
    }
    case(4):
    {
      convolveImage(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
                    outAlpha,filters[4].filter,filters[4].radius,width,height);
      break;
    }
    case(5):
    {
      convolveImage(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
                    outAlpha,filters[5].filter,filters[5].radius,width,height);
      break;
    }
    case(6):
    {
      convolveImage(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
                    outAlpha,filters[6].filter,filters[6].radius,width,height);
      break;
    }
    case(7):
    {
      convertToGray(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
                    outAlpha,gMonoMult,width,height);
      break;
     }
    case(8):
    {
      invertImage(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
                  outAlpha,width,height);
      break;
    }
    case(9):
    {
      flipImage(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
                outAlpha,width,height);
      break;
    }
    case(10):
    {
      pixelate(inRed,inBlue,inGreen,inAlpha,outRed,outBlue,outGreen,
               outAlpha,8,8,width,height);
      break;
    }
    case(11):
    {
      Image *invImage=generateOutput(inputImage);
      Image *blurImage=generateOutput(inputImage);
      pencilSketch(inRed,inBlue,inGreen,inAlpha,invImage->redChannel,
                   invImage->blueChannel,invImage->greenChannel,
                   invImage->alphaChannel,blurImage->redChannel,
                   blurImage->blueChannel,blurImage->greenChannel,
                   blurImage->alphaChannel,outRed,outBlue,outGreen,
                   outAlpha,filters[0].filter,filters[0].radius,width,height,
                   gMonoMult);
      //NOTE THAT I NEED TO FREE EACH OF THE CHANNEL INDIVIDUALLY
      //MAKE A FREE IMAGE FUNCTION
      freeImage(invImage);
      freeImage(blurImage);
      break;
    }
    default:
      exit(1);
  }

  if(command!=12)
    encode(outputFilename,outputImage);

  free((double*)filters[0].filter);
  free(filters);
  freeImage(inputImage);
  freeImage(outputImage);
  return 0;
}
示例#29
0
int main_thread(SceSize args, void *argp)
{
	#ifdef DEBUG
	pspDebugScreenInit();
	printf("Free Memory: %u KB\n",sceKernelTotalFreeMemSize()/1024);
	#else
	initGraphics();
	loadTheme();
	background = loadImageFromMemory(images[BACKGROUND].data, images[BACKGROUND].hdr.size);
	sceKernelFreePartitionMemory(images[BACKGROUND].blockid);
	images[BACKGROUND].blockid = -1;
	mask = loadImageFromMemory(images[MASK].data, images[MASK].hdr.size);
	sceKernelFreePartitionMemory(images[MASK].blockid);
	images[MASK].blockid = -1;
	#endif

	int firstUse = 0;
	int recovery = 0;
	int bytesRead = 0;
	Config cfg;
	char input[11];

	if ((args == 9) && (strcmp(argp, "recovery") == 0))
	{
		recovery = 1;
	}

	SceUID fp;
	fp = sceIoOpen("flash0:/buttons.ini", PSP_O_RDONLY, 0777);

	if (fp < 0)
	{
		#ifdef DEBUG
		printf("\nflash0:/buttons.ini could not be opned. Assuming first usage.");
		#endif
		firstUse = 1;
	}
	else
	{
		bytesRead = sceIoRead(fp, &cfg, sizeof(cfg));
		sceIoClose(fp);

		if(bytesRead != sizeof(cfg))
		{
			firstUse = 1;
		}
	}

	if (firstUse)
	{
		setPassword();
	}
	else if (((args == 0) || (recovery != 0)) || !(cfg.onlyBoot))
	{
		int len;
main_password:
		#ifndef DEBUG
		footer_pressselect = loadImageFromMemory(images[FOOTER_PRESSSELECT].data, images[FOOTER_PRESSSELECT].hdr.size);
		title_password = loadImageFromMemory(images[TITLE_PASSWORD].data, images[TITLE_PASSWORD].hdr.size);
		#endif
		while(1)
		{
			selectEnabled = 1;

			#ifdef DEBUG
			printf("\nPress START to accept.\nPress SELECT to change password.\nEnter password: "******"\nPassword OK.");
				#else
				int temp;
				blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
				blitAlphaImageToScreen(0, 0, images[FOOTER_PRESSSELECT].hdr.w, images[FOOTER_PRESSSELECT].hdr.h, footer_pressselect, images[FOOTER_PRESSSELECT].hdr.x, images[FOOTER_PRESSSELECT].hdr.y);
				blitAlphaImageToScreen(0, 0, images[TITLE_PASSWORD].hdr.w, images[TITLE_PASSWORD].hdr.h, title_password, images[TITLE_PASSWORD].hdr.x, images[TITLE_PASSWORD].hdr.y);
				msg_passwordok = loadImageFromMemory(images[MSG_PASSWORDOK].data, images[MSG_PASSWORDOK].hdr.size);
				blitAlphaImageToScreen(0, 0, images[MSG_PASSWORDOK].hdr.w, images[MSG_PASSWORDOK].hdr.h, msg_passwordok, images[MSG_PASSWORDOK].hdr.x, images[MSG_PASSWORDOK].hdr.y);
				freeImage(msg_passwordok);
				for(temp = 0; temp < len; temp++)
				{
					blitAlphaImageToScreen(0, 0, images[MASK].hdr.w, images[MASK].hdr.h, mask, images[MASK].hdr.x+(temp*images[MASK].hdr.w), images[MASK].hdr.y);
				}
				sceDisplayWaitVblankStart();
				flipScreen();
				#endif
				sceKernelDelayThread(1000*1000);
				break;
			}
			else
			{
				#ifdef DEBUG
				printf("\nIncorrect password.");
				#else
				int temp;
				blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
				blitAlphaImageToScreen(0, 0, images[FOOTER_PRESSSELECT].hdr.w, images[FOOTER_PRESSSELECT].hdr.h, footer_pressselect, images[FOOTER_PRESSSELECT].hdr.x, images[FOOTER_PRESSSELECT].hdr.y);
				blitAlphaImageToScreen(0, 0, images[TITLE_PASSWORD].hdr.w, images[TITLE_PASSWORD].hdr.h, title_password, images[TITLE_PASSWORD].hdr.x, images[TITLE_PASSWORD].hdr.y);
				msg_passwordincorrect = loadImageFromMemory(images[MSG_PASSWORDINCORRECT].data, images[MSG_PASSWORDINCORRECT].hdr.size);
				blitAlphaImageToScreen(0, 0, images[MSG_PASSWORDINCORRECT].hdr.w, images[MSG_PASSWORDINCORRECT].hdr.h, msg_passwordincorrect, images[MSG_PASSWORDINCORRECT].hdr.x, images[MSG_PASSWORDINCORRECT].hdr.y);
				freeImage(msg_passwordincorrect);
				for(temp = 0; temp < len; temp++)
				{
					blitAlphaImageToScreen(0, 0, images[MASK].hdr.w, images[MASK].hdr.h, mask, images[MASK].hdr.x+(temp*images[MASK].hdr.w), images[MASK].hdr.y);
				}
				sceDisplayWaitVblankStart();
				flipScreen();
				#endif
				sceKernelDelayThread(3000*1000);
			}
		}
		#ifndef DEBUG
		freeImage(footer_pressselect);
		freeImage(title_password);
		#endif

		if(len == -1)
		{
			#ifndef DEBUG
			footer_changemode = loadImageFromMemory(images[FOOTER_CHANGEMODE].data, images[FOOTER_CHANGEMODE].hdr.size);
			title_oldpassword = loadImageFromMemory(images[TITLE_OLDPASSWORD].data, images[TITLE_OLDPASSWORD].hdr.size);
			#endif
			while(1)
			{
				#ifdef DEBUG
				printf("\nChange password mode.\nEnter old password: "******"\nPassword OK.");
					#else
					int temp;
					blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
					blitAlphaImageToScreen(0, 0, images[FOOTER_CHANGEMODE].hdr.w, images[FOOTER_CHANGEMODE].hdr.h, footer_changemode, images[FOOTER_CHANGEMODE].hdr.x, images[FOOTER_CHANGEMODE].hdr.y);
					blitAlphaImageToScreen(0, 0, images[TITLE_OLDPASSWORD].hdr.w, images[TITLE_OLDPASSWORD].hdr.h, title_oldpassword, images[TITLE_OLDPASSWORD].hdr.x, images[TITLE_OLDPASSWORD].hdr.y);
					msg_passwordok = loadImageFromMemory(images[MSG_PASSWORDOK].data, images[MSG_PASSWORDOK].hdr.size);
					blitAlphaImageToScreen(0, 0, images[MSG_PASSWORDOK].hdr.w, images[MSG_PASSWORDOK].hdr.h, msg_passwordok, images[MSG_PASSWORDOK].hdr.x, images[MSG_PASSWORDOK].hdr.y);
					freeImage(msg_passwordok);
					for(temp = 0; temp < len; temp++)
					{
						blitAlphaImageToScreen(0, 0, images[MASK].hdr.w, images[MASK].hdr.h, mask, images[MASK].hdr.x+(temp*images[MASK].hdr.w), images[MASK].hdr.y);
					}
					sceDisplayWaitVblankStart();
					flipScreen();
					#endif
					sceKernelDelayThread(3000*1000);
					break;
				}
				else
				{
					#ifdef DEBUG
					printf("\nIncorrect password.");
					#else
					int temp;
					blitImageToScreen(0, 0, images[BACKGROUND].hdr.w, images[BACKGROUND].hdr.h, background, images[BACKGROUND].hdr.x, images[BACKGROUND].hdr.y);
					blitAlphaImageToScreen(0, 0, images[FOOTER_CHANGEMODE].hdr.w, images[FOOTER_CHANGEMODE].hdr.h, footer_changemode, images[FOOTER_CHANGEMODE].hdr.x, images[FOOTER_CHANGEMODE].hdr.y);
					blitAlphaImageToScreen(0, 0, images[TITLE_OLDPASSWORD].hdr.w, images[TITLE_OLDPASSWORD].hdr.h, title_oldpassword, images[TITLE_OLDPASSWORD].hdr.x, images[TITLE_OLDPASSWORD].hdr.y);
					msg_passwordincorrect = loadImageFromMemory(images[MSG_PASSWORDINCORRECT].data, images[MSG_PASSWORDINCORRECT].hdr.size);
					blitAlphaImageToScreen(0, 0, images[MSG_PASSWORDINCORRECT].hdr.w, images[MSG_PASSWORDINCORRECT].hdr.h, msg_passwordincorrect, images[MSG_PASSWORDINCORRECT].hdr.x, images[MSG_PASSWORDINCORRECT].hdr.y);
					freeImage(msg_passwordincorrect);
					for(temp = 0; temp < len; temp++)
					{
						blitAlphaImageToScreen(0, 0, images[MASK].hdr.w, images[MASK].hdr.h, mask, images[MASK].hdr.x+(temp*images[MASK].hdr.w), images[MASK].hdr.y);
					}
					sceDisplayWaitVblankStart();
					flipScreen();
					#endif
					sceKernelDelayThread(3000*1000);
				}
			}
			#ifndef DEBUG
			freeImage(footer_changemode);
			freeImage(title_oldpassword);
			#endif
			if(len == -1)
			{
				goto main_password;
			}
			selectEnabled = 0;
			setPassword();
		}
	}

	#ifndef DEBUG
	freeImage(background);
	freeImage(mask);
	sceGuTerm();
	int i;
	for (i = 0; i < NUMFILES; i++)
	{
		if (images[i].blockid != -1)
		{
			sceKernelFreePartitionMemory(images[i].blockid);
		}
	}
	#endif

	__psp_free_heap();
	#ifdef DEBUG
	printf("\n__psp_free_heap(): %u KB\n",sceKernelTotalFreeMemSize()/1024);
	sceKernelDelayThread(3000*1000);
	#endif

	#ifdef DEBUG
	printf("\nLoading loader.prx");
	#endif

	SceUID mod = sceKernelLoadModule("flash0:/loader.prx", 0, NULL);

	if (mod & 0x80000000)
	{
		#ifdef DEBUG
		printf("\nLoadModule failed 0x%x", mod);
		#endif
	}
	else
	{
		SceUID startmod;
		startmod = sceKernelStartModule(mod, args, argp, NULL, NULL);

		if (mod != startmod)
		{
			#ifdef DEBUG
			printf("\nStartModule failed 0x%x", startmod);
			#endif
		}
	}

	return sceKernelExitDeleteThread(0);
}
示例#30
0
文件: maskimg.c 项目: intgr/sc2-uqm
int main(int argc, char *argv[])
{
	struct options opts;
	image_t* img;
	image_t* mask;

	parse_arguments(argc, argv, &opts);
	verbose_level = opts.verbose;

	img = readImage(opts.infile);
	if (!img)
		return EXIT_FAILURE;
	if (img->color_type != PNG_COLOR_TYPE_RGB)
	{
		verbose(1, "Input image must be RGB, 8 bits per channel (or fix the code)\n");
		freeImage(img);
		return EXIT_FAILURE;
	}
	if (!img->trans_values)
	{
		verbose(2, "%s has no tRNS chunk, assuming transparent black (RBG 0,0,0)\n",
				opts.infile);
		img->trans_values = &img->trans_values_buf;
	}
	img->num_trans = 0;

	mask = readImage(opts.maskfile);
	if (!mask)
	{
		freeImage(img);
		return EXIT_FAILURE;
	}
	if (mask->w < img->w || mask->h < img->h)
	{
		verbose(1, "Mask image dimensions are smaller than input image\n");
		freeImage(img);
		freeImage(mask);
		return EXIT_FAILURE;
	}
	else if (mask->w != img->w || mask->h != img->h)
		verbose(2, "Warning: input image and mask have different dimensions\n");

	if (mask->color_type != PNG_COLOR_TYPE_GRAY && mask->color_type != PNG_COLOR_TYPE_PALETTE)
	{
		verbose(1, "Mask image must be grayscale or paletted (or fix the code)\n");
		freeImage(img);
		freeImage(mask);
		return EXIT_FAILURE;
	}
	if (opts.alpha && (mask->color_type & PNG_COLOR_MASK_PALETTE))
	{
		verbose(2, "Warning: ignoring palette in mask image; using indices\n");
	}
	if (opts.alpha && mask->bit_depth != 8)
	{
		verbose(1, "Mask image for the alpha channel must be 8bpp\n");
		freeImage(img);
		freeImage(mask);
		return EXIT_FAILURE;
	}
	if (!opts.alpha && mask->trans)
	{
		mask->trans_index = getImageTransIndex(mask);
		verbose(2, "Using mask image transparency info; trans index %d\n", mask->trans_index);
	}
	else if (!opts.alpha)
	{
		mask->trans_index = 0;
		verbose(2, "Mask image has no transparency info; using index %d\n", mask->trans_index);
	}

	if (!opts.maskon && !opts.maskoff && !opts.alpha)
	{
		freeImage(img);
		freeImage(mask);
		verbose(1, "Nothing to do; specify -0 or -1, or use -a\n");
		return EXIT_SUCCESS;
	}

	if (opts.alpha && (opts.maskon || opts.maskoff))
	{
		verbose(2, "Options -0 and -1 have no effect when -a specified\n");
	}

	if (opts.alpha)
		alphaImage(img, mask);
	else
		maskImage(img, mask, opts.maskon, opts.maskoff);
	
	writeImage(img, opts.outfile);

	freeImage(img);
	freeImage(mask);

	return EXIT_SUCCESS;
}