Ejemplo n.º 1
0
/*
 * Save the rendered image to disk.
 */
static void renderio(scenedef * scene) {
    flt iotime;
    char msgtxt[256];
    rt_timerhandle ioth; /* I/O timer handle */

    ioth=rt_timer_create();
    rt_timer_start(ioth);

    if (scene->imgbufformat == RT_IMAGE_BUFFER_RGB96F) {
        if (scene->imgprocess & RT_IMAGE_NORMALIZE) {
            normalize_rgb96f(scene->hres, scene->vres, (float *) scene->img);
            rt_ui_message(MSG_0, "Post-processing: normalizing pixel values.");
        }

        if (scene->imgprocess & RT_IMAGE_GAMMA) {
            gamma_rgb96f(scene->hres, scene->vres, (float *) scene->img,
                         scene->imggamma);
            rt_ui_message(MSG_0, "Post-processing: gamma correcting pixel values.");
        }
    } else if (scene->imgbufformat == RT_IMAGE_BUFFER_RGB24) {
        if (scene->imgprocess & (RT_IMAGE_NORMALIZE | RT_IMAGE_GAMMA))
            rt_ui_message(MSG_0, "Can't post-process 24-bit integer image data");
    }

    /* support cropping of output images for SPECMPI benchmarks */
    if (scene->imgcrop.cropmode == RT_CROP_DISABLED) {
        writeimage(scene->outfilename, scene->hres, scene->vres,
                   scene->img, scene->imgbufformat, scene->imgfileformat);
    } else {
        /* crop image before writing if necessary */
        if (scene->imgbufformat == RT_IMAGE_BUFFER_RGB96F) {
            float *imgcrop;
            imgcrop = image_crop_rgb96f(scene->hres, scene->vres, scene->img,
                                        scene->imgcrop.xres, scene->imgcrop.yres,
                                        scene->imgcrop.xstart, scene->imgcrop.ystart);
            writeimage(scene->outfilename, scene->imgcrop.xres, scene->imgcrop.yres,
                       imgcrop, scene->imgbufformat, scene->imgfileformat);
            free(imgcrop);
        } else if (scene->imgbufformat == RT_IMAGE_BUFFER_RGB24) {
            unsigned char *imgcrop;
            imgcrop = image_crop_rgb24(scene->hres, scene->vres, scene->img,
                                       scene->imgcrop.xres, scene->imgcrop.yres,
                                       scene->imgcrop.xstart, scene->imgcrop.ystart);
            writeimage(scene->outfilename, scene->imgcrop.xres, scene->imgcrop.yres,
                       imgcrop, scene->imgbufformat, scene->imgfileformat);
            free(imgcrop);
        }
    }

    rt_timer_stop(ioth);
    iotime = rt_timer_time(ioth);
    rt_timer_destroy(ioth);

    sprintf(msgtxt, "    Image I/O Time: %10.4f seconds", iotime);
    rt_ui_message(MSG_0, msgtxt);
}
Ejemplo n.º 2
0
int	main(int argc, char *argv[]) {
	// parse command line arguments
	int	c;
	while (EOF != (c = getopt(argc, argv, "d")))
		switch (c) {
		case 'd':
			debuglevel = LOG_DEBUG;
			break;
		}

	// create a camera instance
	SimCamera	camera;
	CcdPtr	ccd = camera.getCcd(0);
	GuiderPortPtr	guiderport = camera.getGuiderPort();

	// we will always use 1 sec exposures
	Exposure	exposure(ImageRectangle(ImagePoint(160,120),
		ImageSize(320, 240)), 1);

	// make 10 images 1 second appart (should give small drift)
	counter = 0;
	while (counter < 10) {
		ccd->startExposure(exposure);
		ImagePtr	image = ccd->getImage();
		writeimage(image);
	}

	// now move for 5 seconds
	guiderport->activate(5, 0, 0, 0);
	sleep(5);
	ccd->startExposure(exposure);
	writeimage(ccd->getImage());

	guiderport->activate(0, 5, 0, 0);
	sleep(5);
	ccd->startExposure(exposure);
	writeimage(ccd->getImage());
	
	guiderport->activate(0, 0, 5, 0);
	sleep(5);
	ccd->startExposure(exposure);
	writeimage(ccd->getImage());
	
	guiderport->activate(0, 0, 0, 5);
	sleep(5);
	ccd->startExposure(exposure);
	writeimage(ccd->getImage());
	

	return EXIT_SUCCESS;
}
Ejemplo n.º 3
0
int main(int argc, char *argv[])
{	
	char *src_path,*dst_path;
	
	int row=0,col=0,max_value=255;
	char* loc;//int i,j;
	
	// <a.out> <src_file> <destination_file>
		
		if (argc != 3)
		{
			printf("Usage <a.out> <src_file> <destination_file> \n");
			return -1;
		}
		src_path=argv[1];
		dst_path=argv[2];
			unsigned int **new_image = readimage(src_path,&row,&col,&max_value,&loc);
		new_image=contrast_stretch(new_image,&row,&col,max_value);
		writeimage(new_image,row,col,dst_path,max_value);


		
		
	return 0;
}
int p3b(void)
{
	// initialize data of input
	const char *inputname = "boat.raw";
	int SizeW = 512;
	int SizeH = 512;
	int BytesPerPixel = 1;
	unsigned char inputdata[SizeH][SizeW][BytesPerPixel];

	// initialize data of output
	const char *outputname = "3b boat_ED_ans.raw";
	int newSizeW = SizeW;
	int newSizeH = SizeH;
	int newBytesPerPixel = BytesPerPixel;
	unsigned char outputdata[newSizeH][newSizeW][newBytesPerPixel];

	// read input
	readimage(inputname, &inputdata[0][0][0], SizeH, SizeW, BytesPerPixel);

	// Error Diffusion
	int color = 255;
	FSErrorDiff(color, SizeH, SizeW, &inputdata[0][0][0], &outputdata[0][0][0]);
	writeimage(outputname, &outputdata[0][0][0], newSizeH, newSizeW, newBytesPerPixel);

	return 0;
}
Ejemplo n.º 5
0
char*
writebitmap(void)
{
	char basename[64];
	char name[64+30];
	static char result[200];
	char *p, *q;
	int fd;

	if(im == nil)
		return "no image";

	memset(basename, 0, sizeof basename);
	if(doc->docname)
		strncpy(basename, doc->docname, sizeof(basename)-1);
	else if((p = menugen(page)) && p[0] != '\0')
		strncpy(basename, p+1, sizeof(basename)-1);

	if(basename[0]) {
		if((q = strrchr(basename, '/')) != nil)
			q++;
		else
			q = basename;
		if((p = strchr(q, '.')) != nil)
			*p = 0;

		memset(name, 0, sizeof name);
		snprint(name, sizeof(name)-1, "%s.%d.bit", q, page+1);
		if(access(name, 0) >= 0) {
			strcat(name, "XXXX");
			mktemp(name);
		}
		if(access(name, 0) >= 0)
			return "couldn't think of a name for bitmap";
	} else {
		strcpy(name, "bitXXXX");
		mktemp(name);
		if(access(name, 0) >= 0)
			return "couldn't think of a name for bitmap";
	}

	if((fd = create(name, OWRITE, 0666)) < 0) {
		snprint(result, sizeof result, "cannot create %s: %r", name);
		return result;
	}

	if(writeimage(fd, im, 0) < 0) {
		snprint(result, sizeof result, "cannot writeimage: %r");
		close(fd);
		return result;
	}
	close(fd);

	snprint(result, sizeof result, "wrote %s", name);
	return result;
}
int p3a(void)
{
	// initialize data of input
	const char *inputname = "boat.raw";
	int SizeW = 512;
	int SizeH = 512;
	int BytesPerPixel = 1;
	unsigned char inputdata[SizeH][SizeW][BytesPerPixel];

	// initialize data of output
	const char *outputname1 = "3a boat_FT_ans.raw";
	const char *outputname2 = "3a boat_RT_ans.raw";
	const char *outputname3a = "3a boat_DM2_ans.raw";
	const char *outputname3b = "3a boat_DM4_ans.raw";
	int newSizeW = SizeW;
	int newSizeH = SizeH;
	int newBytesPerPixel = BytesPerPixel;
	unsigned char outputdata1[newSizeH][newSizeW][newBytesPerPixel];
	unsigned char outputdata2[newSizeH][newSizeW][newBytesPerPixel];
	unsigned char outputdata3a[newSizeH][newSizeW][newBytesPerPixel];
	unsigned char outputdata3b[newSizeH][newSizeW][newBytesPerPixel];

	// read input
	readimage(inputname, &inputdata[0][0][0], SizeH, SizeW, BytesPerPixel);

	//*** Fixed thresholding ***
	float FixedT = 128.0;
	Fixedthre(FixedT, SizeH, SizeW, &inputdata[0][0][0], &outputdata1[0][0][0]);
	writeimage(outputname1, &outputdata1[0][0][0], newSizeH, newSizeW, newBytesPerPixel);

	//*** Random thresholding ***
	RandomThre(SizeH, SizeW, &inputdata[0][0][0], &outputdata2[0][0][0]);
	writeimage(outputname2, &outputdata2[0][0][0], newSizeH, newSizeW, newBytesPerPixel);

	//*** Dithering Matrix
	Dithering(2, SizeH, SizeW, &inputdata[0][0][0], &outputdata3a[0][0][0]);
	Dithering(4, SizeH, SizeW, &inputdata[0][0][0], &outputdata3b[0][0][0]);
	writeimage(outputname3a, &outputdata3a[0][0][0], newSizeH, newSizeW, newBytesPerPixel);
	writeimage(outputname3b, &outputdata3b[0][0][0], newSizeH, newSizeW, newBytesPerPixel);

	return 0;
}
Ejemplo n.º 7
0
MvthReplyCode writeframe_cmd(Command *cmd)
{
	char *iname;
	Arg *a;
	char filename[2048];
	char *basename;
	image_t *img;

	if (cmd->narg==2 && strncmp(cmd->arglist->next->str,"-h",2)==0)
	{
		usage();
		return S_HANDLED;
	}
	if (cmd->narg!=3)
	{
		return S_USAGE;
	}
	a=cmd->arglist->next;
	
	/* get the image number */
	iname=a->str;

	if (strcmp(iname,"-1")==0)
	{
		framenum=0;
		return S_SUCCESS;
	}

	/* get the basename of the image */
	a=a->next;
	basename=a->str;
	if (basename==NULL)
	{
		mvthprint(stderr,"writeframe_cmd(): Error setting basename.\n");
		return S_ARGS;
	}

	if ((img=get_image_var(iname))==NULL)
	{
		return S_NOEXIST;
	}

	/* constructing file name */
	snprintf(filename,sizeof(filename),"%s%04d.ppm",basename,framenum);

	writeimage(img->data,
			img->w,img->h,img->bands,filename);

	framenum++;

	mvthprint(stdout,"Wrote image \"%s\" to file `%s',\n",iname, filename);

	return S_SUCCESS;
}
Ejemplo n.º 8
0
Archivo: opt.c Proyecto: hacxman/mandel
void test_fill() {
  int w = 1024, h = 1024;
  color_dt * img = malloc(sizeof(color_dt) * w * h);
  int i,j;
  for (i = 0; i < w; i++) {
    for (j = 0; j < h; j++) {
      img[i*h+j].r = (double)i / (double)w; //0.3;
      img[i*h+j].g = 0;
      img[i*h+j].b = 0;
    }
  }

  writeimage("test.pnm", img, 16, w, h);
}
Ejemplo n.º 9
0
void
domask(Icon *icon)
{
	int rv;
	char file[64];
	int fd;

	rv = -1;
	snprint(file, sizeof(file), "%dx%d.mask", icon->w, icon->h);
	fd = create(file, OWRITE, 0664);
	if(fd >= 0){
		rv = writeimage(fd, icon->mask, 0);
		close(fd);
	}
	if(rv < 0)
		mesg("error writing %s: %r", file);
	else
		mesg("created %s", file);
}
int p1a(void)
{
	// initialize data of input
	const char *filename1 = "Tiffany.raw";
	int SizeW1 = 512;
	int SizeH1 = 512;
	int BytesPerPixel1 = 3;
	unsigned char ImageData1[SizeH1][SizeW1][BytesPerPixel1];
	const char *filename2 = "Components.raw";
	int SizeW2 = 350;
	int SizeH2 = 350;
	int BytesPerPixel2 = 3;
	unsigned char ImageData2[SizeH2][SizeW2][BytesPerPixel2];

	// read input
	readimage(filename1, &ImageData1[0][0][0], SizeH1, SizeW1, BytesPerPixel1);
	readimage(filename2, &ImageData2[0][0][0], SizeH2, SizeW2, BytesPerPixel2);

	// find the center coordinates and the dimension of holes
	FindHoleInfo(&ImageData1[0][0][0], SizeH1, SizeW1);

	// find the center coordinates, the orientation angle and the dimension of the components
	FindPiecesInfo(&ImageData2[0][0][0], SizeH2, SizeW2);

	float mholeH = (60+4), mholeW = (110+4);
	float mholeI = 338, mholeJ = 320;
	float mouthH = 65.069191, mouthW = 127.279221;
	float mouthI = 107.620117, mouthJ = 106.122902;
	float mangle = 0 - 0.785398;
	float eholeH = (35+4), eholeW = (80+4);
	float eholeI = 211.5, eholeJ = 258;
	float eyeH = 52, eyeW = 112.946892;
	float eyeI = 251.533356, eyeJ = 226.533356;
	float eangle = 0.352553 - 3.14159;

	// rotation
	unsigned char rmImage[SizeH2][SizeW2][BytesPerPixel2];
	memset(rmImage, 255, SizeH2*SizeW2*3*(sizeof(unsigned char)));
	rotation(&ImageData2[0][0][0], &rmImage[0][0][0], SizeH2, SizeW2, mouthH, mouthW, mouthI, mouthJ, mangle);
	writeimage("1a rotatedmouth.raw", &rmImage[0][0][0], SizeH2, SizeW2, 3);
	unsigned char reImage[SizeH2][SizeW2][BytesPerPixel2];
	memset(reImage, 255, SizeH2*SizeW2*3*(sizeof(unsigned char)));
	rotation(&ImageData2[0][0][0], &reImage[0][0][0], SizeH2, SizeW2, eyeH, eyeW, eyeI, eyeJ, eangle);
	writeimage("1a rotatedeye.raw", &reImage[0][0][0], SizeH2, SizeW2, 3);

	// scaling
	unsigned char smImage[SizeH2][SizeW2][BytesPerPixel2];
	memset(smImage, 255, SizeH2*SizeW2*3*(sizeof(unsigned char)));
	scaling(&rmImage[0][0][0], &smImage[0][0][0], SizeH2, SizeW2, mouthH, mouthW, mholeH, mholeW, mouthI, mouthJ);
	writeimage("1a scaledmouth.raw", &smImage[0][0][0], SizeH2, SizeW2, 3);
	unsigned char seImage[SizeH2][SizeW2][BytesPerPixel2];
	memset(seImage, 255, SizeH2*SizeW2*3*(sizeof(unsigned char)));
	scaling(&reImage[0][0][0], &seImage[0][0][0], SizeH2, SizeW2, eyeH, eyeW, eholeH, eholeW, eyeI, eyeJ);
	writeimage("1a scaledeye.raw", &seImage[0][0][0], SizeH2, SizeW2, 3);

	// shift
	unsigned char shiftm[SizeH1][SizeW1][BytesPerPixel1];
	memset(shiftm, 255, SizeH1*SizeW1*3*(sizeof(unsigned char)));
	shift(&smImage[0][0][0], &shiftm[0][0][0], SizeW2, SizeW1, mholeH, mholeW, mouthI, mouthJ, mholeI, mholeJ);
	writeimage("1a shiftedmouth.raw", &shiftm[0][0][0], SizeH1, SizeW1, 3);
	unsigned char shifte[SizeH1][SizeW1][BytesPerPixel1];
	memset(shifte, 255, SizeH1*SizeW1*3*(sizeof(unsigned char)));
	shift(&seImage[0][0][0], &shifte[0][0][0], SizeW2, SizeW1, eholeH, eholeW, eyeI, eyeJ, eholeI, eholeJ);
	writeimage("1a shiftedeye.raw", &shifte[0][0][0], SizeH1, SizeW1, 3);

	// combine mouth & eye
	unsigned char MandE[SizeH1][SizeW1][BytesPerPixel1];
	memset(MandE, 255, SizeH1*SizeW1*3*(sizeof(unsigned char)));
	combination(&shifte[0][0][0], &shiftm[0][0][0], &MandE[0][0][0], SizeH1, SizeW1);
	writeimage("1a mouth and eye.raw", &MandE[0][0][0], SizeH1, SizeW1, 3);

	// final combination
	unsigned char fullT[SizeH1][SizeW1][BytesPerPixel1];
	memset(fullT, 255, SizeH1*SizeW1*3*(sizeof(unsigned char)));
	combination(&MandE[0][0][0], &ImageData1[0][0][0], &fullT[0][0][0], SizeH1, SizeW1);
	writeimage("1a fullTiffany.raw", &fullT[0][0][0], SizeH1, SizeW1, 3);

	return 0;
}
int p1c(void)
{
	// initialize data of input
	const char *filename = "fruits.raw";
	int SizeW = 512;
	int SizeH = 512;
	int BytesPerPixel = 3;
	unsigned char ImageData[SizeH][SizeW][BytesPerPixel];

	// read input
	readimage(filename, &ImageData[0][0][0], SizeH, SizeW, BytesPerPixel);

	unsigned char output[SizeH][SizeW][BytesPerPixel];
	memset(output, 0, SizeH*SizeW*3*(sizeof(unsigned char)));
	float oldx, oldy, midi, midj;
	float diffi, diffj;
	int midi0, midj0, midi1, midj1, midi2, midj2, midi3, midj3;
	int R0, G0, B0, R1, G1, B1, R2, G2, B2, R3, G3, B3;
	for(int i=0; i<256; i++)
	{
		for(int j=256; (j <= 511-i) && (j <= 255 + i/0.4142); j++)
		{
			float x = j - 255;
			float y = 256 -i;

			oldx = 1.4142*x;
			oldy = 0.4142*x + y;
			midj = oldx + 255;
			midi = 256 - oldy;
			diffi = midi - ((int)midi);
			diffj = midj - ((int)midj);

			midi0 = midi;
			midj0 = midj;
			midi1 = midi0 + 1;
			midj1 = midj0;
			midi2 = midi0;
			midj2 = midj0 + 1;
			midi3 = midi0 + 1;
			midj3 = midj0 + 1;

			R0 = ImageData[midi0][midj0][0];
			G0 = ImageData[midi0][midj0][1];
			B0 = ImageData[midi0][midj0][2];
			R1 = ImageData[midi1][midj1][0];
			G1 = ImageData[midi1][midj1][1];
			B1 = ImageData[midi1][midj1][2];
			R2 = ImageData[midi2][midj2][0];
			G2 = ImageData[midi2][midj2][1];
			B2 = ImageData[midi2][midj2][2];
			R3 = ImageData[midi3][midj3][0];
			G3 = ImageData[midi3][midj3][1];
			B3 = ImageData[midi3][midj3][2];

			output[i][j][0] = (int)((1.0-diffj)*(1-diffi)*R0 + diffj*(1-diffi)*R1 + diffi*(1-diffj)*R2 + diffj*diffi*R3);
			output[i][j][1] = (int)((1.0-diffj)*(1-diffi)*G0 + diffj*(1-diffi)*G1 + diffi*(1-diffj)*G2 + diffj*diffi*G3);
			output[i][j][2] = (int)((1.0-diffj)*(1-diffi)*B0 + diffj*(1-diffi)*B1 + diffi*(1-diffj)*B2 + diffj*diffi*B3);
		}
	}
	for(int j=256; j<512; j++)
	{
		for(int i=255; (i >= 2.4142*j - 977.6593) && (i >= 511-j); i--)
		{
			float x = j - 255;
			float y = 256 -i;

//			printf("i = %d , j = %d, x = %f, y = %f\n", i, j, x, y);
			oldx = x + 0.4142*y;
			oldy = 1.4142*y;
			midj = oldx + 255;
			midi = 256 - oldy;
			diffi = midi - ((int)midi);
			diffj = midj - ((int)midj);

			midi0 = midi;
			midj0 = midj;
			midi1 = midi0 + 1;
			midj1 = midj0;
			midi2 = midi0;
			midj2 = midj0 + 1;
			midi3 = midi0 + 1;
			midj3 = midj0 + 1;

			R0 = ImageData[midi0][midj0][0];
			G0 = ImageData[midi0][midj0][1];
			B0 = ImageData[midi0][midj0][2];
			R1 = ImageData[midi1][midj1][0];
			G1 = ImageData[midi1][midj1][1];
			B1 = ImageData[midi1][midj1][2];
			R2 = ImageData[midi2][midj2][0];
			G2 = ImageData[midi2][midj2][1];
			B2 = ImageData[midi2][midj2][2];
			R3 = ImageData[midi3][midj3][0];
			G3 = ImageData[midi3][midj3][1];
			B3 = ImageData[midi3][midj3][2];

			output[i][j][0] = (int)((1.0-diffj)*(1-diffi)*R0 + diffj*(1-diffi)*R1 + diffi*(1-diffj)*R2 + diffj*diffi*R3);
			output[i][j][1] = (int)((1.0-diffj)*(1-diffi)*G0 + diffj*(1-diffi)*G1 + diffi*(1-diffj)*G2 + diffj*diffi*G3);
			output[i][j][2] = (int)((1.0-diffj)*(1-diffi)*B0 + diffj*(1-diffi)*B1 + diffi*(1-diffj)*B2 + diffj*diffi*B3);

		}
	}
	for(int j=256; j<512; j++)
	{
		for(int i=255; (i <= j) && (i <= 1488.6593 - 2.4142*j); i++)
		{
			float x = j - 255;
			float y = 255 -i;
			oldx = x - 0.4142*y;
			oldy = 1.4142*y;
			midj = oldx + 255;
			midi = 255 - oldy;

//			printf("i = %d , j = %d, x = %f, y = %f, midi = %f, midj = %f\n", i, j, x, y, midi, midj);
			diffi = midi - ((int)midi);
			diffj = midj - ((int)midj);

			midi0 = midi;
			midj0 = midj;
			midi1 = midi0 + 1;
			midj1 = midj0;
			midi2 = midi0;
			midj2 = midj0 + 1;
			midi3 = midi0 + 1;
			midj3 = midj0 + 1;

			R0 = ImageData[midi0][midj0][0];
			G0 = ImageData[midi0][midj0][1];
			B0 = ImageData[midi0][midj0][2];
			R1 = ImageData[midi1][midj1][0];
			G1 = ImageData[midi1][midj1][1];
			B1 = ImageData[midi1][midj1][2];
			R2 = ImageData[midi2][midj2][0];
			G2 = ImageData[midi2][midj2][1];
			B2 = ImageData[midi2][midj2][2];
			R3 = ImageData[midi3][midj3][0];
			G3 = ImageData[midi3][midj3][1];
			B3 = ImageData[midi3][midj3][2];

			output[i][j][0] = (int)((1.0-diffj)*(1-diffi)*R0 + diffj*(1-diffi)*R1 + diffi*(1-diffj)*R2 + diffj*diffi*R3);
			output[i][j][1] = (int)((1.0-diffj)*(1-diffi)*G0 + diffj*(1-diffi)*G1 + diffi*(1-diffj)*G2 + diffj*diffi*G3);
			output[i][j][2] = (int)((1.0-diffj)*(1-diffi)*B0 + diffj*(1-diffi)*B1 + diffi*(1-diffj)*B2 + diffj*diffi*B3);

		}
	}
	for(int i=256; i<512; i++)
	{
		for(int j=256; (j <= i) && (j <= 255 + (511-i)/0.4142); j++)
		{
			float x = j - 255;
			float y = 255 -i;

			oldx = 1.4142*x;
			oldy = y - 0.4142*x;
			midj = oldx + 255;
			midi = 255 - oldy;
			diffi = midi - ((int)midi);
			diffj = midj - ((int)midj);

			midi0 = midi;
			midj0 = midj;
			midi1 = midi0 + 1;
			midj1 = midj0;
			midi2 = midi0;
			midj2 = midj0 + 1;
			midi3 = midi0 + 1;
			midj3 = midj0 + 1;

			R0 = ImageData[midi0][midj0][0];
			G0 = ImageData[midi0][midj0][1];
			B0 = ImageData[midi0][midj0][2];
			R1 = ImageData[midi1][midj1][0];
			G1 = ImageData[midi1][midj1][1];
			B1 = ImageData[midi1][midj1][2];
			R2 = ImageData[midi2][midj2][0];
			G2 = ImageData[midi2][midj2][1];
			B2 = ImageData[midi2][midj2][2];
			R3 = ImageData[midi3][midj3][0];
			G3 = ImageData[midi3][midj3][1];
			B3 = ImageData[midi3][midj3][2];

			output[i][j][0] = (int)((1.0-diffj)*(1-diffi)*R0 + diffj*(1-diffi)*R1 + diffi*(1-diffj)*R2 + diffj*diffi*R3);
			output[i][j][1] = (int)((1.0-diffj)*(1-diffi)*G0 + diffj*(1-diffi)*G1 + diffi*(1-diffj)*G2 + diffj*diffi*G3);
			output[i][j][2] = (int)((1.0-diffj)*(1-diffi)*B0 + diffj*(1-diffi)*B1 + diffi*(1-diffj)*B2 + diffj*diffi*B3);
		}
	}
	for(int i=256; i<512; i++)
	{
		for(int j=255; (j >= 511-i) && (j >= 256 - (511-i)/0.4142); j--)
		{
			float x = j - 256;
			float y = 255 -i;

			oldx = 1.4142*x;
			oldy = 0.4142*x + y;
			midj = oldx + 256;
			midi = 255 - oldy;
			diffi = midi - ((int)midi);
			diffj = midj - ((int)midj);

			midi0 = midi;
			midj0 = midj;
			midi1 = midi0 + 1;
			midj1 = midj0;
			midi2 = midi0;
			midj2 = midj0 + 1;
			midi3 = midi0 + 1;
			midj3 = midj0 + 1;

			R0 = ImageData[midi0][midj0][0];
			G0 = ImageData[midi0][midj0][1];
			B0 = ImageData[midi0][midj0][2];
			R1 = ImageData[midi1][midj1][0];
			G1 = ImageData[midi1][midj1][1];
			B1 = ImageData[midi1][midj1][2];
			R2 = ImageData[midi2][midj2][0];
			G2 = ImageData[midi2][midj2][1];
			B2 = ImageData[midi2][midj2][2];
			R3 = ImageData[midi3][midj3][0];
			G3 = ImageData[midi3][midj3][1];
			B3 = ImageData[midi3][midj3][2];

			output[i][j][0] = (int)((1.0-diffj)*(1-diffi)*R0 + diffj*(1-diffi)*R1 + diffi*(1-diffj)*R2 + diffj*diffi*R3);
			output[i][j][1] = (int)((1.0-diffj)*(1-diffi)*G0 + diffj*(1-diffi)*G1 + diffi*(1-diffj)*G2 + diffj*diffi*G3);
			output[i][j][2] = (int)((1.0-diffj)*(1-diffi)*B0 + diffj*(1-diffi)*B1 + diffi*(1-diffj)*B2 + diffj*diffi*B3);
		}
	}
	for(int j=0; j<256; j++)
	{
		for(int i=256; (i <= 511-j) && (i <= 2.4142*j+255.0031); i++)
		{
			float x = j - 256;
			float y = 255 -i;

//			printf("i = %d , j = %d, x = %f, y = %f\n", i, j, x, y);
			oldx = x + 0.4142*y;
			oldy = 1.4142*y;
			midj = oldx + 256;
			midi = 255 - oldy;
			diffi = midi - ((int)midi);
			diffj = midj - ((int)midj);

			midi0 = midi;
			midj0 = midj;
			midi1 = midi0 + 1;
			midj1 = midj0;
			midi2 = midi0;
			midj2 = midj0 + 1;
			midi3 = midi0 + 1;
			midj3 = midj0 + 1;

			R0 = ImageData[midi0][midj0][0];
			G0 = ImageData[midi0][midj0][1];
			B0 = ImageData[midi0][midj0][2];
			R1 = ImageData[midi1][midj1][0];
			G1 = ImageData[midi1][midj1][1];
			B1 = ImageData[midi1][midj1][2];
			R2 = ImageData[midi2][midj2][0];
			G2 = ImageData[midi2][midj2][1];
			B2 = ImageData[midi2][midj2][2];
			R3 = ImageData[midi3][midj3][0];
			G3 = ImageData[midi3][midj3][1];
			B3 = ImageData[midi3][midj3][2];

			output[i][j][0] = (int)((1.0-diffj)*(1-diffi)*R0 + diffj*(1-diffi)*R1 + diffi*(1-diffj)*R2 + diffj*diffi*R3);
			output[i][j][1] = (int)((1.0-diffj)*(1-diffi)*G0 + diffj*(1-diffi)*G1 + diffi*(1-diffj)*G2 + diffj*diffi*G3);
			output[i][j][2] = (int)((1.0-diffj)*(1-diffi)*B0 + diffj*(1-diffi)*B1 + diffi*(1-diffj)*B2 + diffj*diffi*B3);

		}
	}
	for(int j=0; j<256; j++)
	{
		for(int i=255; (i >= j) && (i >= 255.9969 - 2.4142*j); i--)
		{
			float x = j - 256;
			float y = 256 -i;
			oldx = x - 0.4142*y;
			oldy = 1.4142*y;
			midj = oldx + 256;
			midi = 256 - oldy;

//			printf("i = %d , j = %d, x = %f, y = %f, midi = %f, midj = %f\n", i, j, x, y, midi, midj);
			diffi = midi - ((int)midi);
			diffj = midj - ((int)midj);

			midi0 = midi;
			midj0 = midj;
			midi1 = midi0 + 1;
			midj1 = midj0;
			midi2 = midi0;
			midj2 = midj0 + 1;
			midi3 = midi0 + 1;
			midj3 = midj0 + 1;

			R0 = ImageData[midi0][midj0][0];
			G0 = ImageData[midi0][midj0][1];
			B0 = ImageData[midi0][midj0][2];
			R1 = ImageData[midi1][midj1][0];
			G1 = ImageData[midi1][midj1][1];
			B1 = ImageData[midi1][midj1][2];
			R2 = ImageData[midi2][midj2][0];
			G2 = ImageData[midi2][midj2][1];
			B2 = ImageData[midi2][midj2][2];
			R3 = ImageData[midi3][midj3][0];
			G3 = ImageData[midi3][midj3][1];
			B3 = ImageData[midi3][midj3][2];

			output[i][j][0] = (int)((1.0-diffj)*(1-diffi)*R0 + diffj*(1-diffi)*R1 + diffi*(1-diffj)*R2 + diffj*diffi*R3);
			output[i][j][1] = (int)((1.0-diffj)*(1-diffi)*G0 + diffj*(1-diffi)*G1 + diffi*(1-diffj)*G2 + diffj*diffi*G3);
			output[i][j][2] = (int)((1.0-diffj)*(1-diffi)*B0 + diffj*(1-diffi)*B1 + diffi*(1-diffj)*B2 + diffj*diffi*B3);

		}
	}
	for(int i=0; i<256; i++)
	{
		for(int j=255; (j >= i) && (j >= 256 - i/0.4142); j--)
		{
			float x = j - 256;
			float y = 256 -i;

			oldx = 1.4142*x;
			oldy = y - 0.4142*x;
			midj = oldx + 256;
			midi = 256 - oldy;
			diffi = midi - ((int)midi);
			diffj = midj - ((int)midj);

			midi0 = midi;
			midj0 = midj;
			midi1 = midi0 + 1;
			midj1 = midj0;
			midi2 = midi0;
			midj2 = midj0 + 1;
			midi3 = midi0 + 1;
			midj3 = midj0 + 1;

			R0 = ImageData[midi0][midj0][0];
			G0 = ImageData[midi0][midj0][1];
			B0 = ImageData[midi0][midj0][2];
			R1 = ImageData[midi1][midj1][0];
			G1 = ImageData[midi1][midj1][1];
			B1 = ImageData[midi1][midj1][2];
			R2 = ImageData[midi2][midj2][0];
			G2 = ImageData[midi2][midj2][1];
			B2 = ImageData[midi2][midj2][2];
			R3 = ImageData[midi3][midj3][0];
			G3 = ImageData[midi3][midj3][1];
			B3 = ImageData[midi3][midj3][2];

			output[i][j][0] = (int)((1.0-diffj)*(1-diffi)*R0 + diffj*(1-diffi)*R1 + diffi*(1-diffj)*R2 + diffj*diffi*R3);
			output[i][j][1] = (int)((1.0-diffj)*(1-diffi)*G0 + diffj*(1-diffi)*G1 + diffi*(1-diffj)*G2 + diffj*diffi*G3);
			output[i][j][2] = (int)((1.0-diffj)*(1-diffi)*B0 + diffj*(1-diffi)*B1 + diffi*(1-diffj)*B2 + diffj*diffi*B3);
		}
	}

	writeimage("1c warped fruits.raw", &output[0][0][0], SizeH, SizeW, 3);

	return 0;
}
int p1b(void)
{
	// initialize data of input
	const char *filename = "Scarlett.raw";
	int SizeW = 400;
	int SizeH = 300;
	int BytesPerPixel = 3;
	unsigned char ImageData[SizeH][SizeW][BytesPerPixel];
	unsigned char R[SizeH][SizeW];
	unsigned char G[SizeH][SizeW];
	unsigned char B[SizeH][SizeW];
	double dImageData[SizeH][SizeW][BytesPerPixel];

	// initialize data of output
	const char *BGfilename = "1b Scarlett_lab_bf.raw";
	const char *BGfilename1 = "1b Scarlett_rgb_bf.raw";
	const char *Exfilename = "1b Scarlett_ex.raw";
	const char *newfilename = "1b Scarlett_ans.raw";
	int newSizeW = SizeW;
	int newSizeH = SizeH;
	int newBytesPerPixel = BytesPerPixel;
	double MBGImageData[newSizeH][newSizeW][newBytesPerPixel];
	double MCImageData[newSizeH][newSizeW][newBytesPerPixel];
	unsigned char BGImageData[newSizeH][newSizeW][newBytesPerPixel];
	unsigned char BGImageData1[newSizeH][newSizeW][newBytesPerPixel];
	unsigned char CBGImageData[newSizeH][newSizeW][newBytesPerPixel];
	unsigned char newImageData[newSizeH][newSizeW][newBytesPerPixel];

	// input
	readimage(filename, &ImageData[0][0][0], SizeH, SizeW, BytesPerPixel);

	double L[SizeH][SizeW];
	double a[SizeH][SizeW];
	double b[SizeH][SizeW];

	for(int i = 0; i<SizeH; i++)
	{
		for(int j = 0; j < SizeW; j++)
		{
			R[i][j] = ImageData[i][j][0];
			G[i][j] = ImageData[i][j][1];
			B[i][j] = ImageData[i][j][2];
			dImageData[i][j][0] = ((double) ImageData[i][j][0]/255.0);
			dImageData[i][j][1] = ((double) ImageData[i][j][1]/255.0);
			dImageData[i][j][2] = ((double) ImageData[i][j][2]/255.0);
			Rgb2Lab(&L[i][j], &a[i][j], &b[i][j], dImageData[i][j][0], dImageData[i][j][1], dImageData[i][j][2]);
//			printf("%d, %f = %u, %f = %u, %f = %u\n", i,dImageData[i][j][0], ImageData[i][j][0], dImageData[i][j][1],ImageData[i][j][1], dImageData[i][j][2], ImageData[i][j][2]);
//			printf("%d, %f, %f, %f\n", i,L[i][j], a[i][j],b[i][j]);
		}
	}

	// Bilateral Filter
	double newL[SizeH][SizeW];
	double newa[SizeH][SizeW];
	double newb[SizeH][SizeW];
	double newnewL[SizeH][SizeW];
	double newnewa[SizeH][SizeW];
	double newnewb[SizeH][SizeW];
	unsigned char newR[SizeH][SizeW];
	unsigned char newG[SizeH][SizeW];
	unsigned char newB[SizeH][SizeW];
	unsigned char newnewR[SizeH][SizeW];
	unsigned char newnewG[SizeH][SizeW];
	unsigned char newnewB[SizeH][SizeW];

	int FilterSize = 5;
	int sigmaC = 3;
	int sigmaC1 = 10;
	double sigmaS = 4.25;
	double sigmaS1 = 10.0;

	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &R[0][0], SizeH, SizeW, &newR[0][0]);
	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &G[0][0], SizeH, SizeW, &newG[0][0]);
	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &B[0][0], SizeH, SizeW, &newB[0][0]);
	BFiforLab(FilterSize, sigmaC, sigmaS, &L[0][0], SizeH, SizeW, &newL[0][0]);
	BFiforLab(FilterSize, sigmaC, sigmaS, &a[0][0], SizeH, SizeW, &newa[0][0]);
	BFiforLab(FilterSize, sigmaC, sigmaS, &b[0][0], SizeH, SizeW, &newb[0][0]);

	for(int i = 0; i<SizeH; i++)
	{
		for(int j = 0; j < SizeW; j++)
		{
			Lab2Rgb(&MCImageData[i][j][0], &MCImageData[i][j][1], &MCImageData[i][j][2], newL[i][j], newa[i][j], newb[i][j]);
			CBGImageData[i][j][0] = (int) (MCImageData[i][j][0]*255);
			CBGImageData[i][j][1] = (int) (MCImageData[i][j][1]*255);
			CBGImageData[i][j][2] = (int) (MCImageData[i][j][2]*255);
		}
	}


	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &newR[0][0], SizeH, SizeW, &newnewR[0][0]);
	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &newG[0][0], SizeH, SizeW, &newnewG[0][0]);
	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &newB[0][0], SizeH, SizeW, &newnewB[0][0]);
	BFiforLab(FilterSize, sigmaC, sigmaS, &newL[0][0], SizeH, SizeW, &newnewL[0][0]);
	BFiforLab(FilterSize, sigmaC, sigmaS, &newa[0][0], SizeH, SizeW, &newnewa[0][0]);
	BFiforLab(FilterSize, sigmaC, sigmaS, &newb[0][0], SizeH, SizeW, &newnewb[0][0]);

	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &newnewR[0][0], SizeH, SizeW, &newR[0][0]);
	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &newnewG[0][0], SizeH, SizeW, &newG[0][0]);
	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &newnewB[0][0], SizeH, SizeW, &newB[0][0]);
	BFiforLab(FilterSize, sigmaC, sigmaS, &newnewL[0][0], SizeH, SizeW, &newL[0][0]);
	BFiforLab(FilterSize, sigmaC, sigmaS, &newnewa[0][0], SizeH, SizeW, &newa[0][0]);
	BFiforLab(FilterSize, sigmaC, sigmaS, &newnewb[0][0], SizeH, SizeW, &newb[0][0]);

//	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &newR[0][0], SizeH, SizeW, &newnewR[0][0]);
//	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &newG[0][0], SizeH, SizeW, &newnewG[0][0]);
//	BilateralFilter(FilterSize, sigmaC1, sigmaS1, &newB[0][0], SizeH, SizeW, &newnewB[0][0]);

	for(int i = 0; i<SizeH; i++)
	{
		for(int j = 0; j < SizeW; j++)
		{
			Lab2Rgb(&MBGImageData[i][j][0], &MBGImageData[i][j][1], &MBGImageData[i][j][2], newL[i][j], newa[i][j], newb[i][j]);
			BGImageData[i][j][0] = (int) (MBGImageData[i][j][0]*255);
			BGImageData[i][j][1] = (int) (MBGImageData[i][j][1]*255);
			BGImageData[i][j][2] = (int) (MBGImageData[i][j][2]*255);
			BGImageData1[i][j][0] = newR[i][j];
			BGImageData1[i][j][1] = newG[i][j];
			BGImageData1[i][j][2] = newB[i][j];
//			printf("%d, %f, %f, %f\n", i,newL[i][j], newa[i][j],newb[i][j]);
//			printf("%d, %u = %f, %u = %f, %u = %f\n", i,newImageData[i][j][0], MImageData[i][j][0],newImageData[i][j][1], MImageData[i][j][1], newImageData[i][j][2], MImageData[i][j][2]);
		}
	}

	writeimage(BGfilename, &BGImageData[0][0][0], newSizeH, newSizeW, newBytesPerPixel);
	writeimage(BGfilename1, &BGImageData1[0][0][0], newSizeH, newSizeW, newBytesPerPixel);

	// XDoG
	// convert to gray-scale image
	unsigned char GrayImageData[newSizeH][newSizeW];
	for(int i = 0; i<SizeH; i++)
	{
		for(int j = 0; j < SizeW; j++)
		{
			float Y = 0.21*CBGImageData[i][j][0] + 0.72*CBGImageData[i][j][1] +0.07*CBGImageData[i][j][2];
			GrayImageData[i][j] = (int) Y;
//			printf("%d %u = %f\n", i, GrayImageData[i][j], Y);
		}
	}

	unsigned char GrayImageData0[newSizeH][newSizeW];
	for(int i = 0; i<SizeH; i++)
	{
		for(int j = 0; j < SizeW; j++)
		{
			float Y = 0.21*ImageData[i][j][0] + 0.72*ImageData[i][j][1] +0.07*ImageData[i][j][2];
			GrayImageData0[i][j] = (int) Y;
		}
	}


	//compute Ex
	int windowsize = 11;
	float sigma = 1.5;
	float k = sqrt(1.6);
	float t = 0.98, e = 0.5, f = 4;
	unsigned char ExImageData[newSizeH][newSizeW];

	XDoG(windowsize, sigma, k, t, e, f, &GrayImageData[0][0], &ExImageData[0][0], SizeH, SizeW);
	writeimage(Exfilename, &ExImageData[0][0], newSizeH, newSizeW, 1);

	// Integration of Portrait Background and Contour
	for(int i=0; i<SizeH; i++)
	{
		for(int j=0; j<SizeW; j++)
		{
			newImageData[i][j][0] = (ExImageData[i][j]/255) * BGImageData[i][j][0];
			newImageData[i][j][1] = (ExImageData[i][j]/255) * BGImageData[i][j][1];
			newImageData[i][j][2] = (ExImageData[i][j]/255) * BGImageData[i][j][2];
		}
	}

	writeimage(newfilename, &newImageData[0][0][0], newSizeH, newSizeW, newBytesPerPixel);

	// DoG
	unsigned char DoGExImageData[newSizeH][newSizeW];
	unsigned char DoGImageData[newSizeH][newSizeW][newBytesPerPixel];
	DoG(windowsize, sigma, k, e, f, &GrayImageData[0][0], &DoGExImageData[0][0], SizeH, SizeW);
	writeimage("1b Scarlett_DoG_ex.raw", &DoGExImageData[0][0], newSizeH, newSizeW, 1);
	for(int i=0; i<SizeH; i++)
	{
		for(int j=0; j<SizeW; j++)
		{
			DoGImageData[i][j][0] = (DoGExImageData[i][j]/255) * BGImageData[i][j][0];
			DoGImageData[i][j][1] = (DoGExImageData[i][j]/255) * BGImageData[i][j][1];
			DoGImageData[i][j][2] = (DoGExImageData[i][j]/255) * BGImageData[i][j][2];
		}
	}
	writeimage("1b Scarlett_DoG_ans.raw", &DoGImageData[0][0][0], newSizeH, newSizeW, newBytesPerPixel);
	return 0;
}
// ******************  Problem 1: Edge Detection ***********************
int p1a(void)
{
	// initialize data of input
	const char *filename1 = "elaine.raw";
	const char *filename2 = "noisy_elaine.raw";
	int SizeW = 256;
	int SizeH = 256;
	int BytesPerPixel = 1;
	unsigned char ImageData1[SizeH][SizeW][BytesPerPixel];
	unsigned char ImageData2[SizeH][SizeW][BytesPerPixel];

	// initialize data of output
	const char *newfilename1a = "1a elaine_soble_ans.raw";
	const char *newfilename1b = "1a elaine_LoG_ans.raw";
	const char *newfilename2a = "1a noisyelaine_soble_ans.raw";
	const char *newfilename2b = "1a noisyelaine_LoG_ans.raw";
	int newSizeW = SizeW;
	int newSizeH = SizeH;
	int newBytesPerPixel = BytesPerPixel;
	unsigned char newImageData1a[newSizeH][newSizeW][newBytesPerPixel];
	unsigned char newImageData1b[newSizeH][newSizeW][newBytesPerPixel];
	unsigned char newImageData2a[newSizeH][newSizeW][newBytesPerPixel];
	unsigned char newImageData2b[newSizeH][newSizeW][newBytesPerPixel];

	// read input
	readimage(filename1, &ImageData1[0][0][0], SizeH, SizeW, BytesPerPixel);
	readimage(filename2, &ImageData2[0][0][0], SizeH, SizeW, BytesPerPixel);

	// --------------------Sobel Detector------------------------
	int extend = 2;
	int thr1a = 24;
	int thr2a = 37;
	unsigned char Gradient1aR[SizeH][SizeW];
	unsigned char Gradient1aC[SizeH][SizeW];
	unsigned char Gradient1a[SizeH][SizeW];
	const char *gradient1aR = "1a elaine_s_R_grad.raw";
	const char *gradient1aC = "1a elaine_s_C_grad.raw";
	const char *gradient1a = "1a elaine_soble_grad.raw";
	unsigned char Gradient2aR[SizeH][SizeW];
	unsigned char Gradient2aC[SizeH][SizeW];
	unsigned char Gradient2a[SizeH][SizeW];
	const char *gradient2aR = "1a noisingelaine_s_R_grad.raw";
	const char *gradient2aC = "1a noisingelaine_s_C_grad.raw";
	const char *gradient2a = "1a noisingelaine_soble_grad.raw";

	GetSobleGradient(thr1a, &ImageData1[0][0][0], SizeH, SizeW, extend, &Gradient1aR[0][0], &Gradient1aC[0][0], &Gradient1a[0][0], &newImageData1a[0][0][0]);
	GetSobleGradient(thr2a, &ImageData2[0][0][0], SizeH, SizeW, extend, &Gradient2aR[0][0], &Gradient2aC[0][0], &Gradient2a[0][0], &newImageData2a[0][0][0]);

	// output
	writeimage(gradient1aR, &Gradient1aR[0][0], SizeH, SizeW, BytesPerPixel);
	writeimage(gradient1aC, &Gradient1aC[0][0], SizeH, SizeW, BytesPerPixel);
	writeimage(gradient1a, &Gradient1a[0][0], SizeH, SizeW, BytesPerPixel);
	writeimage(newfilename1a, &newImageData1a[0][0][0], newSizeH, newSizeW, newBytesPerPixel);
	writeimage(gradient2aR, &Gradient2aR[0][0], SizeH, SizeW, BytesPerPixel);
	writeimage(gradient2aC, &Gradient2aC[0][0], SizeH, SizeW, BytesPerPixel);
	writeimage(gradient2a, &Gradient2a[0][0], SizeH, SizeW, BytesPerPixel);
	writeimage(newfilename2a, &newImageData2a[0][0][0], newSizeH, newSizeW, newBytesPerPixel);

	// ----------------------LoG Detector------------------------------
	int Dfiltersize = 9;
	float sigma = 1.0;
	float thr1b = 0.9;
	float thr2b = 1.5;
	unsigned char Gradient1b[SizeH][SizeW];
	unsigned char ternarymap1[SizeH][SizeW];
	unsigned char Gradient2b[SizeH][SizeW];
	unsigned char ternarymap2[SizeH][SizeW];
	const char *gradient1b = "1a elaine_LoG_grad.raw";
	const char *ternary1 = "1a elaine_LoG_ter.raw";
	const char *gradient2b = "1a noisingelaine_LoG_grad.raw";
	const char *ternary2 = "1a noisingelaine_LoG_ter.raw";

	LoG(Dfiltersize, sigma, thr1b, &ImageData1[0][0][0], SizeH, SizeW, &Gradient1b[0][0], &ternarymap1[0][0], &newImageData1b[0][0][0]);
	LoG(Dfiltersize, sigma, thr2b, &ImageData2[0][0][0], SizeH, SizeW, &Gradient2b[0][0], &ternarymap2[0][0], &newImageData2b[0][0][0]);

	writeimage(gradient1b, &Gradient1b[0][0], SizeH, SizeW, BytesPerPixel);
	writeimage(ternary1, &ternarymap1[0][0], SizeH, SizeW, BytesPerPixel);
	writeimage(newfilename1b, &newImageData1b[0][0][0], newSizeH, newSizeW, newBytesPerPixel);
	writeimage(gradient2b, &Gradient2b[0][0], SizeH, SizeW, BytesPerPixel);
	writeimage(ternary2, &ternarymap2[0][0], SizeH, SizeW, BytesPerPixel);
	writeimage(newfilename2b, &newImageData2b[0][0][0], newSizeH, newSizeW, newBytesPerPixel);

	return 0;
}
Ejemplo n.º 14
0
/* ==================================== */
int32_t ldynamique_ldynamique(struct xvimage *image, struct xvimage *order, int32_t connex)
/* ==================================== */
/*! \fn int32_t ldynamique_ldynamique(struct xvimage *image, struct xvimage *order, int32_t connex)
    \param image (entrée/sortie) : une image
    \param order (entrée) : labels définissant un ordre sur les maxima (de 1 à nbmaxima)
    \param connex (entrée) : 4 ou 8 (2D), 6, 18 ou 26 (3D) 
    \return code erreur : 0 si échec, 1 sinon
    \brief calcule la dynamique ordonnée des maxima
*/
#undef F_NAME
#define F_NAME "ldynamique_ldynamique"
{
  register int32_t i, j, k, x;      /* index muet */
  int32_t rs = rowsize(image);      /* taille ligne */
  int32_t cs = colsize(image);      /* taille colonne */
  int32_t ds = depth(image);        /* nb plans */
  int32_t ps = rs * cs;             /* taille plan */
  int32_t N = ps * ds;              /* taille image */
  uint8_t *F = UCHARDATA(image);      /* l'image de depart */
  int32_t *O = SLONGDATA(order);      /* l'image de labels */
  Fahs * FAHS;                    /* la file d'attente hierarchique */
  int32_t *CM;                      /* etat d'un pixel */
  ctree * CT;                   /* resultat : l'arbre des composantes */
  int32_t *mu;                      /* pour représenter l'ordre */
  int32_t *alpha;                   /* pour certains calculs intermédiaires */
  int32_t *dyn;                     /* pour représenter la dynamique */
  
  if ((rowsize(order) != rs) || (colsize(order) != cs) || (depth(order) != ds))
  {
    fprintf(stderr, "%s: incompatible image sizes\n", F_NAME);
    exit(0);
  }

  FAHS = CreeFahsVide(N);
  if (FAHS == NULL)
  {   fprintf(stderr, "%s() : CreeFahsVide failed\n", F_NAME);
      return 0;
  }
  if ((connex == 4) || (connex == 8))
  {
    if (!ComponentTree(F, rs, N, connex, &CT, &CM))
    {   fprintf(stderr, "%s() : ComponentTree failed\n", F_NAME);
        return 0;
    }
  }
  else if ((connex == 6) || (connex == 18) || (connex == 26))
  {
    if (!ComponentTree3d(F, rs, ps, N, connex, &CT, &CM))
    {   fprintf(stderr, "%s() : ComponentTree failed\n", F_NAME);
        return 0;
    }
  }
  else
  { fprintf(stderr, "%s() : bad value for connex : %d\n", F_NAME, connex);
    return 0;
  }

#ifdef DEBUG
  ComponentTreePrint(CT);
  writeimage(order, "_o");
#endif

  mu = (int32_t *)calloc(CT->nbleafs+1, sizeof(int32_t)); // 0 non utilise
  dyn = (int32_t *)calloc(CT->nbleafs+1, sizeof(int32_t)); // 0 non utilise
  alpha = (int32_t *)calloc(CT->nbnodes, sizeof(int32_t));
  if ((mu == NULL) || (dyn == NULL) || (alpha == NULL)) 
  {
    fprintf(stderr, "%s : malloc failed\n", F_NAME);
    return 0;
  }

  for (x = 0; x < N; x++)
  {
    k = CM[x];
    i = O[x]; // label donnant l'ordre
    if (CT->tabnodes[k].nbsons == 0) // feuille
      mu[i] = k; 
  } // for (x = 0; x < N; x++)

  for (i = CT->nbleafs; i >= 1; i--)
  {
    j = k = mu[i];
#ifdef DEBUG
    printf("node %d : %d ", i, k);
#endif
    while ((k != -1) && (alpha[k] == 0))
    {
      alpha[k] = i;
      k = CT->tabnodes[k].father;
    } 
    if (k == -1)
      dyn[i] = 255;
    else
      dyn[i] = CT->tabnodes[j].data - CT->tabnodes[k].data;
#ifdef DEBUG
    printf("  ancestor %d, level %d\n", k, dyn[i]);
#endif
  } // for (i = CT->nbleafs; i >= 1; i--)

  for (x = 0; x < N; x++)
    if (O[x]) F[x] = dyn[O[x]]; else F[x] = 0;

  /* ================================================ */
  /* UN PEU DE MENAGE                                 */
  /* ================================================ */

  FahsTermine(FAHS);
  ComponentTreeFree(CT);
  free(CM);
  free(mu);
  free(dyn);
  free(alpha);
  return(1);
} /* ldynamique_ldynamique() */
Ejemplo n.º 15
0
/*----------------------------------------------------------------
 * prism2_fwapply
 *
 * Apply the firmware loaded into memory
 *
 * Arguments:
 *	rfptr	firmware image in kernel memory
 *	wlandev device
 *
 * Returns:
 *	0	- success
 *	~0	- failure
 *----------------------------------------------------------------
 */
static int prism2_fwapply(const struct ihex_binrec *rfptr,
			  struct wlandevice *wlandev)
{
	signed int result = 0;
	struct p80211msg_dot11req_mibget getmsg;
	struct p80211itemd *item;
	u32 *data;

	/* Initialize the data structures */
	ns3data = 0;
	s3data = kcalloc(S3DATA_MAX, sizeof(*s3data), GFP_KERNEL);
	if (!s3data) {
		result = -ENOMEM;
		goto out;
	}

	ns3plug = 0;
	memset(s3plug, 0, sizeof(s3plug));
	ns3crc = 0;
	memset(s3crc, 0, sizeof(s3crc));
	ns3info = 0;
	memset(s3info, 0, sizeof(s3info));
	startaddr = 0;

	nfchunks = 0;
	memset(fchunk, 0, sizeof(fchunk));
	memset(&nicid, 0, sizeof(nicid));
	memset(&rfid, 0, sizeof(rfid));
	memset(&macid, 0, sizeof(macid));
	memset(&priid, 0, sizeof(priid));

	/* clear the pda and add an initial END record */
	memset(&pda, 0, sizeof(pda));
	pda.rec[0] = (struct hfa384x_pdrec *)pda.buf;
	pda.rec[0]->len = cpu_to_le16(2);	/* len in words */
	pda.rec[0]->code = cpu_to_le16(HFA384x_PDR_END_OF_PDA);
	pda.nrec = 1;

	/*-----------------------------------------------------*/
	/* Put card into fwload state */
	prism2sta_ifstate(wlandev, P80211ENUM_ifstate_fwload);

	/* Build the PDA we're going to use. */
	if (read_cardpda(&pda, wlandev)) {
		netdev_err(wlandev->netdev, "load_cardpda failed, exiting.\n");
		result = 1;
		goto out;
	}

	/* read the card's PRI-SUP */
	memset(&getmsg, 0, sizeof(getmsg));
	getmsg.msgcode = DIDmsg_dot11req_mibget;
	getmsg.msglen = sizeof(getmsg);
	strcpy(getmsg.devname, wlandev->name);

	getmsg.mibattribute.did = DIDmsg_dot11req_mibget_mibattribute;
	getmsg.mibattribute.status = P80211ENUM_msgitem_status_data_ok;
	getmsg.resultcode.did = DIDmsg_dot11req_mibget_resultcode;
	getmsg.resultcode.status = P80211ENUM_msgitem_status_no_value;

	item = (struct p80211itemd *)getmsg.mibattribute.data;
	item->did = DIDmib_p2_p2NIC_p2PRISupRange;
	item->status = P80211ENUM_msgitem_status_no_value;

	data = (u32 *)item->data;

	/* DIDmsg_dot11req_mibget */
	prism2mgmt_mibset_mibget(wlandev, &getmsg);
	if (getmsg.resultcode.data != P80211ENUM_resultcode_success)
		netdev_err(wlandev->netdev, "Couldn't fetch PRI-SUP info\n");

	/* Already in host order */
	priid.role = *data++;
	priid.id = *data++;
	priid.variant = *data++;
	priid.bottom = *data++;
	priid.top = *data++;

	/* Read the S3 file */
	result = read_fwfile(rfptr);
	if (result) {
		netdev_err(wlandev->netdev,
			   "Failed to read the data exiting.\n");
		goto out;
	}

	result = validate_identity();
	if (result) {
		netdev_err(wlandev->netdev, "Incompatible firmware image.\n");
		goto out;
	}

	if (startaddr == 0x00000000) {
		netdev_err(wlandev->netdev,
			   "Can't RAM download a Flash image!\n");
		result = 1;
		goto out;
	}

	/* Make the image chunks */
	result = mkimage(fchunk, &nfchunks);
	if (result) {
		netdev_err(wlandev->netdev, "Failed to make image chunk.\n");
		goto free_chunks;
	}

	/* Do any plugging */
	result = plugimage(fchunk, nfchunks, s3plug, ns3plug, &pda);
	if (result) {
		netdev_err(wlandev->netdev, "Failed to plug data.\n");
		goto free_chunks;
	}

	/* Insert any CRCs */
	result = crcimage(fchunk, nfchunks, s3crc, ns3crc);
	if (result) {
		netdev_err(wlandev->netdev, "Failed to insert all CRCs\n");
		goto free_chunks;
	}

	/* Write the image */
	result = writeimage(wlandev, fchunk, nfchunks);
	if (result) {
		netdev_err(wlandev->netdev, "Failed to ramwrite image data.\n");
		goto free_chunks;
	}

	netdev_info(wlandev->netdev, "prism2_usb: firmware loading finished.\n");

free_chunks:
	/* clear any allocated memory */
	free_chunks(fchunk, &nfchunks);
	free_srecs();

out:
	return result;
}
Ejemplo n.º 16
0
int prism2_fwapply(const struct ihex_binrec *rfptr, wlandevice_t *wlandev)
{
	signed int result = 0;
	struct p80211msg_dot11req_mibget getmsg;
	p80211itemd_t *item;
	u32 *data;

	
	ns3data = 0;
	memset(s3data, 0, sizeof(s3data));
	ns3plug = 0;
	memset(s3plug, 0, sizeof(s3plug));
	ns3crc = 0;
	memset(s3crc, 0, sizeof(s3crc));
	ns3info = 0;
	memset(s3info, 0, sizeof(s3info));
	startaddr = 0;

	nfchunks = 0;
	memset(fchunk, 0, sizeof(fchunk));
	memset(&nicid, 0, sizeof(nicid));
	memset(&rfid, 0, sizeof(rfid));
	memset(&macid, 0, sizeof(macid));
	memset(&priid, 0, sizeof(priid));

	
	memset(&pda, 0, sizeof(pda));
	pda.rec[0] = (hfa384x_pdrec_t *) pda.buf;
	pda.rec[0]->len = cpu_to_le16(2);	
	pda.rec[0]->code = cpu_to_le16(HFA384x_PDR_END_OF_PDA);
	pda.nrec = 1;

	
	
	prism2sta_ifstate(wlandev, P80211ENUM_ifstate_fwload);

	
	if (read_cardpda(&pda, wlandev)) {
		printk(KERN_ERR "load_cardpda failed, exiting.\n");
		return 1;
	}

	
	memset(&getmsg, 0, sizeof(getmsg));
	getmsg.msgcode = DIDmsg_dot11req_mibget;
	getmsg.msglen = sizeof(getmsg);
	strcpy(getmsg.devname, wlandev->name);

	getmsg.mibattribute.did = DIDmsg_dot11req_mibget_mibattribute;
	getmsg.mibattribute.status = P80211ENUM_msgitem_status_data_ok;
	getmsg.resultcode.did = DIDmsg_dot11req_mibget_resultcode;
	getmsg.resultcode.status = P80211ENUM_msgitem_status_no_value;

	item = (p80211itemd_t *) getmsg.mibattribute.data;
	item->did = DIDmib_p2_p2NIC_p2PRISupRange;
	item->status = P80211ENUM_msgitem_status_no_value;

	data = (u32 *) item->data;

	
	prism2mgmt_mibset_mibget(wlandev, &getmsg);
	if (getmsg.resultcode.data != P80211ENUM_resultcode_success)
		printk(KERN_ERR "Couldn't fetch PRI-SUP info\n");

	
	priid.role = *data++;
	priid.id = *data++;
	priid.variant = *data++;
	priid.bottom = *data++;
	priid.top = *data++;

	
	result = read_fwfile(rfptr);
	if (result) {
		printk(KERN_ERR "Failed to read the data exiting.\n");
		return 1;
	}

	result = validate_identity();

	if (result) {
		printk(KERN_ERR "Incompatible firmware image.\n");
		return 1;
	}

	if (startaddr == 0x00000000) {
		printk(KERN_ERR "Can't RAM download a Flash image!\n");
		return 1;
	}

	
	result = mkimage(fchunk, &nfchunks);

	
	result = plugimage(fchunk, nfchunks, s3plug, ns3plug, &pda);
	if (result) {
		printk(KERN_ERR "Failed to plug data.\n");
		return 1;
	}

	
	if (crcimage(fchunk, nfchunks, s3crc, ns3crc)) {
		printk(KERN_ERR "Failed to insert all CRCs\n");
		return 1;
	}

	
	result = writeimage(wlandev, fchunk, nfchunks);
	if (result) {
		printk(KERN_ERR "Failed to ramwrite image data.\n");
		return 1;
	}

	
	free_chunks(fchunk, &nfchunks);
	free_srecs();

	printk(KERN_INFO "prism2_usb: firmware loading finished.\n");

	return result;
}
Ejemplo n.º 17
0
/*----------------------------------------------------------------
* prism2_fwapply
*
* Apply the firmware loaded into memory
*
* Arguments:
*	rfptr	firmware image in kernel memory
*	wlandev device
*
* Returns:
*	0	- success
*	~0	- failure
----------------------------------------------------------------*/
int prism2_fwapply(const struct ihex_binrec *rfptr, wlandevice_t *wlandev)
{
	signed int result = 0;
	struct p80211msg_dot11req_mibget getmsg;
	p80211itemd_t *item;
	u32 *data;

	/* Initialize the data structures */
	ns3data = 0;
	memset(s3data, 0, sizeof(s3data));
	ns3plug = 0;
	memset(s3plug, 0, sizeof(s3plug));
	ns3crc = 0;
	memset(s3crc, 0, sizeof(s3crc));
	ns3info = 0;
	memset(s3info, 0, sizeof(s3info));
	startaddr = 0;

	nfchunks = 0;
	memset(fchunk, 0, sizeof(fchunk));
	memset(&nicid, 0, sizeof(nicid));
	memset(&rfid, 0, sizeof(rfid));
	memset(&macid, 0, sizeof(macid));
	memset(&priid, 0, sizeof(priid));

	/* clear the pda and add an initial END record */
	memset(&pda, 0, sizeof(pda));
	pda.rec[0] = (hfa384x_pdrec_t *) pda.buf;
	pda.rec[0]->len = cpu_to_le16(2);	/* len in words */
	pda.rec[0]->code = cpu_to_le16(HFA384x_PDR_END_OF_PDA);
	pda.nrec = 1;

	/*-----------------------------------------------------*/
	/* Put card into fwload state */
	prism2sta_ifstate(wlandev, P80211ENUM_ifstate_fwload);

	/* Build the PDA we're going to use. */
	if (read_cardpda(&pda, wlandev)) {
;
		return 1;
	}

	/* read the card's PRI-SUP */
	memset(&getmsg, 0, sizeof(getmsg));
	getmsg.msgcode = DIDmsg_dot11req_mibget;
	getmsg.msglen = sizeof(getmsg);
	strcpy(getmsg.devname, wlandev->name);

	getmsg.mibattribute.did = DIDmsg_dot11req_mibget_mibattribute;
	getmsg.mibattribute.status = P80211ENUM_msgitem_status_data_ok;
	getmsg.resultcode.did = DIDmsg_dot11req_mibget_resultcode;
	getmsg.resultcode.status = P80211ENUM_msgitem_status_no_value;

	item = (p80211itemd_t *) getmsg.mibattribute.data;
	item->did = DIDmib_p2_p2NIC_p2PRISupRange;
	item->status = P80211ENUM_msgitem_status_no_value;

	data = (u32 *) item->data;

	/* DIDmsg_dot11req_mibget */
	prism2mgmt_mibset_mibget(wlandev, &getmsg);
	if (getmsg.resultcode.data != P80211ENUM_resultcode_success)
;

	/* Already in host order */
	priid.role = *data++;
	priid.id = *data++;
	priid.variant = *data++;
	priid.bottom = *data++;
	priid.top = *data++;

	/* Read the S3 file */
	result = read_fwfile(rfptr);
	if (result) {
;
		return 1;
	}

	result = validate_identity();

	if (result) {
;
		return 1;
	}

	if (startaddr == 0x00000000) {
;
		return 1;
	}

	/* Make the image chunks */
	result = mkimage(fchunk, &nfchunks);

	/* Do any plugging */
	result = plugimage(fchunk, nfchunks, s3plug, ns3plug, &pda);
	if (result) {
;
		return 1;
	}

	/* Insert any CRCs */
	if (crcimage(fchunk, nfchunks, s3crc, ns3crc)) {
;
		return 1;
	}

	/* Write the image */
	result = writeimage(wlandev, fchunk, nfchunks);
	if (result) {
;
		return 1;
	}

	/* clear any allocated memory */
	free_chunks(fchunk, &nfchunks);
	free_srecs();

;

	return result;
}
Ejemplo n.º 18
0
/* ==================================== */
int32_t lsquelval(struct xvimage *image, // entree/sortie: image originale / squelette
              struct xvimage *dx,    // entree/sortie: distance / distance topologique
              int32_t connex, 
              int32_t val_inhibit)
/* ==================================== */
#undef F_NAME
#define F_NAME "lsquelval"
{ 
  int32_t k;
  int32_t x;                       /* index muet de pixel */
  int32_t y;                       /* index muet (generalement un voisin de x) */
  int32_t rs = rowsize(image);     /* taille ligne */
  int32_t cs = colsize(image);     /* taille colonne */
  int32_t N = rs * cs;             /* taille image */
  struct xvimage *dt;          /* pour le calcul de la "distance topologique" */
  uint8_t *IM = UCHARDATA(image);      /* l'image de depart */
  uint32_t *DX;           /* fonction distance au complementaire de IM */
  uint32_t *DT;                    /* fonction "distance topologique" */
  uint32_t d;
  Rbt * RBT;
  int32_t taillemaxrbt;

  IndicsInit(N);
  if ((rowsize(dx) != rs) || (colsize(dx) != cs) || (depth(dx) != 1))
  {
    fprintf(stderr, "%s() : bad size for dx\n", F_NAME);
    return(0);
  }
  if (datatype(dx) != VFF_TYP_4_BYTE)
  {
    fprintf(stderr, "%s() : datatype(dx) must be uint32_t\n", F_NAME);
    return(0);
  }
  DX = ULONGDATA(dx); 
  dt = copyimage(dx);
  DT = ULONGDATA(dt); 
  taillemaxrbt = 2 * rs + 2 * cs ;
  /* cette taille est indicative, le RBT est realloue en cas de depassement */
  RBT = mcrbt_CreeRbtVide(taillemaxrbt);
  if (RBT == NULL)
  {
    fprintf(stderr, "%s() : mcrbt_CreeRbtVide failed\n", F_NAME);
    return(0);
  }

  /* ================================================ */
  /*               PREMIERE PHASE                     */
  /* ================================================ */

#ifdef VERBOSE
    printf("1ere etape\n");
#endif

  // INITIALISATION DT
  for (x = 0; x < N; x++) if (IM[x]) DT[x] = INFINI; else DT[x] = 0;

  // INITIALISATION DU RBT
  for (x = 0; x < N; x++)
    if (IM[x] && (DX[x] != val_inhibit) && bordext8(IM, x, rs, N))
    {
      mcrbt_RbtInsert(&RBT, DX[x], x);
      Set(x, EN_RBT);
    } // if, for

  d = 1;
  if (connex == 4)
  {
    while (!mcrbt_RbtVide(RBT))
    {
      x = RbtPopMin(RBT);
      UnSet(x, EN_RBT);
#ifdef DEBUG
      printf("pop x = %d,%d, im = %d, dx = %ld\n", x%rs, x/rs, IM[x], DX[x]);
#endif
      if (simple4(IM, x, rs, N))
      {
        DT[x] = d;
        IM[x] = 0;
        d++;
        for (k = 0; k < 8; k += 1)         /* parcourt les voisins en 8-connexite  */
        {                                              /* pour empiler les voisins */
          y = voisin(x, k, rs, N);                             /* non deja empiles */
          if ((y != -1) && (IM[y]) && (DX[y] != val_inhibit) && (! IsSet(y, EN_RBT)))
          {
            mcrbt_RbtInsert(&RBT, DX[y], y);
            Set(y, EN_RBT);
          } /* if y */
        } /* for k */      
      } // if (simple4(IM, x, rs, N))
    } /* while (!mcrbt_RbtVide(RBT)) */
  } /* if (connex == 4) */
  else
  if (connex == 8)
  {
    while (!mcrbt_RbtVide(RBT))
    {
      x = RbtPopMin(RBT);
      UnSet(x, EN_RBT);
#ifdef DEBUG
      printf("pop x = %d,%d, im = %d, dx = %ld\n", x%rs, x/rs, IM[x], DX[x]);
#endif
      if (simple8(IM, x, rs, N))
      {
        DT[x] = d;
        IM[x] = 0;
        d++;
        for (k = 0; k < 8; k += 1)         /* parcourt les voisins en 8-connexite  */
        {                                              /* pour empiler les voisins */
          y = voisin(x, k, rs, N);                             /* non deja empiles */
          if ((y != -1) && (IM[y]) && (DX[y] != val_inhibit) && (! IsSet(y, EN_RBT)))
          {
            mcrbt_RbtInsert(&RBT, DX[y], y);
            Set(y, EN_RBT);
          } /* if y */
        } /* for k */      
      } // if (simple8(IM, x, rs, N))
    } /* while (!mcrbt_RbtVide(RBT)) */
  } /* if (connex == 8) */

#ifdef DEBUG
  writeimage(dt, "_dt");
#endif

  /* ================================================ */
  /*               SECONDE PHASE                      */
  /* ================================================ */

#ifdef SECONDE_PHASE

  stabilite = 0;
  while (!stabilite)
  {
#ifdef VERBOSE
    printf("2eme etape\n");
#endif
    stabilite = 1;

    // INITIALISATION DU RBT
    for (j = 1; j < cs-1; j++) 
      for (i = 1; i < rs-1; i++) 
      {
        x = j * rs + i;
        if (DT[x] && (DT[x] != INFINI)) mcrbt_RbtInsert(&RBT, DT[x], x);
      }

    if (connex == 4)
    {
      while (!mcrbt_RbtVide(RBT))
      {
        x = RbtPopMin(RBT);
#ifdef DEBUG
        printf("pop x = %d,%d, dt = %ld\n", x%rs, x/rs, DT[x]);
#endif
        if (abaisse4(x, DT, rs, N)) 
        {
          stabilite = 0;
#ifdef DEBUG
          printf("abaisse a %ld\n", DT[x]);
#endif
	} // if (abaisse4(x, DT, rs, N)) 
      } // while (!mcrbt_RbtVide(RBT))
    } // if (connex == 4)
    else
    if (connex == 8)
    {
      int32_t abaisse;
      while (!mcrbt_RbtVide(RBT))
      {
        x = RbtPopMin(RBT);
#ifdef DEBUG
        printf("pop x = %d,%d, dt = %d\n", x%rs, x/rs, DT[x]);
#endif
        if (abaisse8(x, DT, rs, N)) 
        {
          stabilite = 0;
#ifdef DEBUG
          printf("abaisse a %ld\n", DT[x]);
#endif
	} // if (abaisse8(x, DT, rs, N)) 
      } // while (!mcrbt_RbtVide(RBT))
    } // if (connex == 8)
  } // while (!stabilite)

#endif

  // RECUPERATION DU RESULTAT
  d = 0; // valeur pour l'infini: plus grande valeur finie + 1
  for (x = 0; x < N; x++) if ((DT[x] > d) && (DT[x] < INFINI)) d = DT[x];
  d += 1;
  for (x = 0; x < N; x++) if (DT[x] == INFINI) DX[x] = d; else DX[x] = DT[x];
  
  /* ================================================ */
  /* UN PEU DE MENAGE                                 */
  /* ================================================ */

  IndicsTermine();
  mcrbt_RbtTermine(RBT);
  freeimage(dt);
  return(1);
} /* lsquelval() */
int FindPiecesInfo(unsigned char *ImageData, int SizeH, int SizeW)
{
    unsigned char piecemap[SizeH][SizeW];

    for(int i=0; i<SizeH; i++)
    {
        for(int j=0; j<SizeW; j++)
        {
            if((ImageData[i*SizeW*3+j*3+0] <= 220) || (ImageData[i*SizeW*3+j*3+1] <= 220) || (ImageData[i*SizeW*3+j*3+2] <= 220))
            {
                piecemap[i][j] = 255;
            }
            else
                piecemap[i][j] = 0;
        }
    }
    writeimage("1a piecemap.raw", &piecemap[0][0], SizeH, SizeW, 1);

    int labeledmap[SizeH][SizeW];
//	float hist[256];
    memset(labeledmap, 0, SizeH*SizeW*(sizeof(int)));
    TwoPassLable(SizeH, SizeW, &piecemap[0][0], &labeledmap[0][0]);
//	GetHG(&labeledmap[0][0], &hist[0], SizeH, SizeW, 256);
//	OutputHG("1a piecelabeledmap_hist.txt", &hist[0], 256);

    unsigned char fortest[SizeH][SizeW];
    for(int i=0; i<SizeH; i++)
    {
        for(int j=0; j<SizeW; j++)
        {
            fortest[i][j] = labeledmap[i][j]*50;
        }
    }
    writeimage("1a piecelabeledmap.raw", &fortest[0][0], SizeH, SizeW, 1);

    int x1, y1, x2, y2, x3, y3, x4, y4;
    int a1, b1, a2, b2, a3, b3, a4, b4;
    float x, y, a, b, mW, mH, eW, eH, mAngle, eAngle;
    for(int i=0; i<SizeH; i++)
    {
        for(int j=0; j<SizeW; j++)
        {
            if(labeledmap[i][j] == 1)
            {
                x2 = j;
                y2 = SizeH - (i+1);
//				y2 = y2 - 1;
                break;
            }
        }
    }
    for(int j=0; j<SizeW; j++)
    {
        for(int i=0; i<SizeH; i++)
        {
            if(labeledmap[i][j] == 1)
            {
                x3 = j;
//				x3 = x3 + 1;
                y3 = SizeH - (i+1);
                break;
            }
        }
    }
    for(int i=(SizeH-1); i>=0; i--)
    {
        for(int j=(SizeW-1); j>=0; j--)
        {
            if(labeledmap[i][j] == 1)
            {
                x1 = j;
                y1 = SizeH - (i+1);
//				y1 = y1 + 1;
                break;
            }
        }
    }
    for(int j=(SizeW-1); j>=0; j--)
    {
        for(int i=(SizeH-1); i>=0; i--)
        {
            if(labeledmap[i][j] == 1)
            {
                x4 = j;
//				x4 = x4 - 1;
                y4 = SizeH - (i+1);
                break;
            }
        }
    }

    for(int i=0; i<SizeH; i++)
    {
        for(int j=0; j<SizeW; j++)
        {
            if(labeledmap[i][j] != 0 && labeledmap[i][j] != 1)
            {
                a2 = j;
                b2 = SizeH - (i+1);
//				b2 = b2 - 1;
                break;
            }
        }
    }
    for(int j=0; j<SizeW; j++)
    {
        for(int i=0; i<SizeH; i++)
        {
            if(labeledmap[i][j] != 0 && labeledmap[i][j] != 1)
            {
                a3 = j;
//				a3 = a3 + 1;
                b3 = SizeH - (i+1);
                break;
            }
        }
    }
    for(int i=(SizeH-1); i>=0; i--)
    {
        for(int j=(SizeW-1); j>=0; j--)
        {
            if(labeledmap[i][j] != 0 && labeledmap[i][j] != 1)
            {
                a1 = j;
                b1 = SizeH - (i+1);
//				b1 = b1 + 1;
                break;
            }
        }
    }
    for(int j=(SizeW-1); j>=0; j--)
    {
        for(int i=(SizeH-1); i>=0; i--)
        {
            if(labeledmap[i][j] != 0 && labeledmap[i][j] != 1)
            {
                a4 = j;
//				a4 = a4 - 1;
                b4 = SizeH - (i+1);
                break;
            }
        }
    }

//	printf("%d, %d, %d, %d, %d, %d, %d, %d\n", a1, b1, a2, b2, a3, b3, a4, b4);

    float mtemp1, mtemp2, etemp1, etemp2;
    mtemp1 = 1.0*(y2 - y1)/(x2 - x1);
    mtemp2 = 1.0*(y4 - y3)/(x4 - x3);
    etemp1 = 1.0*(b2 - b1)/(a2 - a1);
    etemp2 = 1.0*(b4 - b3)/(a4 - a3);

    x = (y3 - mtemp2*x3 + mtemp1*x1 - y1)/(mtemp1 - mtemp2);
    y = mtemp1*(x - x1) + y1;
    a = (b3 - etemp2*a3 + etemp1*a1 - b1)/(etemp1 - etemp2);
    b = etemp1*(a - a1) + b1;
    mW = sqrt((x2 - x3)*(x2 - x3) + (y2 - y3)*(y2 - y3));
    mH = sqrt((x4 - x2)*(x4 - x2) + (y2 - y4)*(y2 - y4));
    eH = sqrt((a2 - a3)*(a2 - a3) + (b2 - b3)*(b2 - b3));
    eW = sqrt((a4 - a2)*(a4 - a2) + (b2 - b4)*(b2 - b4));
    mAngle = atan(1.0*(y4-y1)/(x4-x1));
    eAngle = atan(1.0*(b4-b2)/(a4-a2));

    printf(" mouth height = %f,\n mouth width = %f,\n center coordinate of mouth (i, j) = (%f, %f),\n the orientation angle = %f;\n", mH, mW, (SizeH-y-1), x, mAngle);
    printf(" eye height = %f,\n eye width = %f,\n center coordinate of eye (i, j) = (%f, %f),\n the orientation angle = %f.\n", eH, eW, (SizeH-b-1), a, eAngle);

    return 0;
}
int FindHoleInfo(unsigned char *ImageData, int SizeH, int SizeW)
{
    unsigned char holemap[SizeH][SizeW];

    for(int i=0; i<SizeH; i++)
    {
        for(int j=0; j<SizeW; j++)
        {
            if(ImageData[i*SizeW*3+j*3+0] > 235 && ImageData[i*SizeW*3+j*3+1] > 225 && ImageData[i*SizeW*3+j*3+2] > 218)
            {
                holemap[i][j] = 255;
            }
            else
                holemap[i][j] = 0;
        }
    }
    writeimage("1a holemap.raw", &holemap[0][0], SizeH, SizeW, 1);

    int labeledmap[SizeH][SizeW];
    memset(labeledmap, 0, SizeH*SizeW*(sizeof(int)));
    TwoPassLable(SizeH, SizeW, &holemap[0][0], &labeledmap[0][0]);

    unsigned char fortest[SizeH][SizeW];
    for(int i=0; i<SizeH; i++)
    {
        for(int j=0; j<SizeW; j++)
        {
            fortest[i][j] = labeledmap[i][j]*50;
        }
    }
    writeimage("1a labeledmap.raw", &fortest[0][0], SizeH, SizeW, 1);

    unsigned char finalmap[SizeH][SizeW];
    memset(finalmap, 0, SizeH*SizeW*(sizeof(unsigned char)));
//	for(int i=1; i<(SizeH-3); i++)
//	{
//		for(int j=1; j<(SizeW-3); j++)
//		{
//			if(labeledmap[i][j] != 0)
//			{
//				if(labeledmap[i-1][j-1]==0 && labeledmap[i-1][j]==0 && labeledmap[i-1][j+1]==0 &&
//				labeledmap[i-1][j+2]==0 && labeledmap[i-1][j+3]==0 && labeledmap[i][j-1]==0 &&
//				labeledmap[i+1][j-1]==0 && labeledmap[i+2][j-1]==0 && labeledmap[i+3][j-1]==0 &&
//				labeledmap[i][j+1]!=0 && labeledmap[i][j+2]!=0 && labeledmap[i][j+3]!=0 &&
//				labeledmap[i+1][j]!=0 && labeledmap[i+2][j]!=0 && labeledmap[i+3][j]!=0)
//				{
//					for(int u=0; u<SizeH; u++)
//					{
//						for(int v=0; v<SizeW; v++)
//						{
//							if(labeledmap[u][v] == labeledmap[i][j])
//								finalmap[u][v] = labeledmap[i][j];
//						}
//					}
//				}
//			}
//		}
//	}
    int mark = 1;
    for(int i=(SizeH-2); i>=3; i--)
    {
        for(int j=(SizeW-2); j>=3; j--)
        {
            if(labeledmap[i][j] != 0)
            {
                if(labeledmap[i-3][j+1]==0 && labeledmap[i-2][j+1]==0 && labeledmap[i-1][j+1]==0 &&
                        labeledmap[i][j+1]==0 && labeledmap[i+1][j+1]==0 && labeledmap[i+1][j]==0 &&
                        labeledmap[i+1][j-3]==0 && labeledmap[i+1][j-2]==0 && labeledmap[i+1][j-1]==0 &&
                        labeledmap[i][j-1]!=0 && labeledmap[i][j-2]!=0 && labeledmap[i][j-3]!=0 &&
                        labeledmap[i-1][j]!=0 && labeledmap[i-2][j]!=0 && labeledmap[i-3][j]!=0)
                {
                    for(int u=0; u<SizeH; u++)
                    {
                        for(int v=0; v<SizeW; v++)
                        {
                            if(labeledmap[u][v] == labeledmap[i][j])
                                finalmap[u][v] = mark*100;
                        }
                    }
//					printf("%d\n", mark);
                    mark++;
                }
            }
        }
    }
    writeimage("1a finalmap.raw", &finalmap[0][0], SizeH, SizeW, 1);

    int mouthH=0, mouthW=0, eyeH=0, eyeW=0;
    float mouthI, mouthJ, eyeI, eyeJ;
    for(int i=0; i<SizeH; i++)
    {
        int check = 0;
        for(int j=0; j<SizeW; j++)
        {
            if(finalmap[i][j] == 1*100)
            {
                for(int u=0; u<SizeW; u++)
                {
                    if(finalmap[i][u] == 1*100)
                    {
                        mouthW++;
                    }
                }
                for(int u=0; u<SizeH; u++)
                {
                    if(finalmap[u][j] == 1*100)
                    {
                        mouthH++;
                    }
                }
                mouthI = (i-1)+(mouthH/2.0);
                mouthJ = (j-1)+(mouthW/2.0);
                check = 1;
                break;
            }
        }
        if(check == 1)
            break;
    }

    for(int i=(SizeH-1); i>=0; i--)
    {
        int check = 0;
        for(int j=(SizeW-1); j>=0; j--)
        {
            if(finalmap[i][j] == 2*100)
            {
                for(int u=0; u<SizeW; u++)
                {
                    if(finalmap[i][u] == 2*100)
                    {
                        eyeW++;
                    }
                }
                for(int u=0; u<SizeH; u++)
                {
                    if(finalmap[u][j] == 2*100)
                    {
                        eyeH++;
                    }
                }
                eyeI = i-(eyeH/2.0);
                eyeJ = j-(eyeW/2.0);
                check = 1;
                break;
            }
        }
        if(check == 1)
            break;
    }

    printf(" height of hole of mouth = %d,\n width of hole of mouth = %d,\n center coordinate of hole of mouth (i, j)= (%f, %f);\n", mouthH, mouthW, mouthI, mouthJ);
    printf(" height of hole of eye = %d,\n width of hole of eye = %d,\n center coordinate of hole of eye (i, j)= (%f, %f).\n\n", eyeH, eyeW, eyeI, eyeJ);

    return 0;
}
int p1b(void)
{
	// initialize data of input
	const char *filename = "jennifer.raw";
	int SizeW = 512;
	int SizeH = 512;
	int BytesPerPixel = 3;
	unsigned char ImageData[SizeH][SizeW][BytesPerPixel];

	// read input
	readimage(filename, &ImageData[0][0][0], SizeH, SizeW, BytesPerPixel);

//	int scaleW1 = 512 - (128*(576-512)/512);
//	int scaleH1 = 512;
//	unsigned char scaledImage1[scaleH1][scaleW1][3];
//	resizeimage(&ImageData[0][0][0], &scaledImage1[0][0][0], SizeH, SizeW, scaleH1, scaleW1);
//	int scaleH2 = 512 - (128*(576-512)/512);
//	int scaleW2 = 512;
//	unsigned char scaledImage2[scaleH2][scaleW2][3];
//	resizeimage(&ImageData[0][0][0], &scaledImage2[0][0][0], SizeH, SizeW, scaleH2, scaleW2);
//	writeimage("1b horzscaledJ.raw", &scaledImage1[0][0][0], scaleH1, scaleW1, 3);

	int horzH = 512, horzW = 576;
	unsigned char horzoutput[horzH][horzW][BytesPerPixel];
	memset(horzoutput, 0, horzH*horzW*3*(sizeof(unsigned char)));
	int vertH = 576, vertW = 512;
	unsigned char vertoutput[vertH][vertW][BytesPerPixel];
	memset(vertoutput, 0, vertH*vertW*3*(sizeof(unsigned char)));

	for(int i=0; i<128; i++)
	{
		for(int j=0; j<SizeW; j++)
		{
			int s = (576-512)*(i+1)/128.0;
			horzoutput[i][j+s][0] = ImageData[i][j][0];
			horzoutput[i][j+s][1] = ImageData[i][j][1];
			horzoutput[i][j+s][2] = ImageData[i][j][2];
		}
	}
	for(int i=128; i<256; i++)
	{
		for(int j=0; j<SizeW; j++)
		{
			int s = (576-512)*((255-i)+1)/128.0;
			horzoutput[i][j+s][0] = ImageData[i][j][0];
			horzoutput[i][j+s][1] = ImageData[i][j][1];
			horzoutput[i][j+s][2] = ImageData[i][j][2];
		}
	}
	for(int i=256; i<384; i++)
	{
		for(int j=0; j<SizeW; j++)
		{
			int s = (576-512)*((i-256)+1)/128.0;
			horzoutput[i][j+s][0] = ImageData[i][j][0];
			horzoutput[i][j+s][1] = ImageData[i][j][1];
			horzoutput[i][j+s][2] = ImageData[i][j][2];
		}
	}
	for(int i=384; i<512; i++)
	{
		for(int j=0; j<SizeW; j++)
		{
			int s = (576-512)*((511-i)+1)/128.0;
			horzoutput[i][j+s][0] = ImageData[i][j][0];
			horzoutput[i][j+s][1] = ImageData[i][j][1];
			horzoutput[i][j+s][2] = ImageData[i][j][2];
		}
	}
	writeimage("1b horizontal shear J.raw", &horzoutput[0][0][0], horzH, horzW, 3);

	for(int j=0; j<128; j++)
	{
		for(int i=0; i<SizeW; i++)
		{
			int s = (576-512)*(j+1)/128.0;
			vertoutput[i+s][j][0] = ImageData[i][j][0];
			vertoutput[i+s][j][1] = ImageData[i][j][1];
			vertoutput[i+s][j][2] = ImageData[i][j][2];
		}
	}
	for(int j=128; j<256; j++)
	{
		for(int i=0; i<SizeW; i++)
		{
			int s = (576-512)*((255-j)+1)/128.0;
			vertoutput[i+s][j][0] = ImageData[i][j][0];
			vertoutput[i+s][j][1] = ImageData[i][j][1];
			vertoutput[i+s][j][2] = ImageData[i][j][2];
		}
	}
	for(int j=256; j<384; j++)
	{
		for(int i=0; i<SizeW; i++)
		{
			int s = (576-512)*((j-256)+1)/128.0;
			vertoutput[i+s][j][0] = ImageData[i][j][0];
			vertoutput[i+s][j][1] = ImageData[i][j][1];
			vertoutput[i+s][j][2] = ImageData[i][j][2];
		}
	}
	for(int j=384; j<512; j++)
	{
		for(int i=0; i<SizeW; i++)
		{
			int s = (576-512)*((511-j)+1)/128.0;
			vertoutput[i+s][j][0] = ImageData[i][j][0];
			vertoutput[i+s][j][1] = ImageData[i][j][1];
			vertoutput[i+s][j][2] = ImageData[i][j][2];
		}
	}
	writeimage("1b vertical shear J.raw", &vertoutput[0][0][0], vertH, vertW, 3);


	return 0;
}
Ejemplo n.º 22
0
int main(void) {
//time meassuring
  	struct timeval tvs;

//variables
	int 	Nx=1024;
	int		Ny=1024;
	int 	plotnum=0;
	int	  	Tmax=2;
	int 	plottime=0;
	int	  	plotgap=1;
	double	Lx=1.0;
	double 	Ly=1.0;
	double	dt=0.0;	
	double	A=0.0;
	double	B=0.0;
	double	Du=0.0;
	double	Dv=0.0;
//splitting coefficients
	double	a=0.5;	
	double 	b=0.5;
	double 	c=1.0;
//loop counters	
	int i=0;
	int j=0;
	int n=0;

	double*umax=NULL;
	double*vmax=NULL;
	parainit(&Nx,&Ny,&Tmax,&plotgap,&Lx,&Ly,&dt,&Du,&Dv,&A,&B);
	plottime=plotgap;
	vmax=(double*)malloc((Tmax/plotgap+1)*sizeof(double));
	umax=(double*)malloc((Tmax/plotgap+1)*sizeof(double));
//openCL variables
    cl_platform_id *platform_id = NULL;
    cl_kernel frequencies = NULL, initialdata = NULL, linearpart=NULL;
	cl_kernel nonlinearpart_a=NULL, nonlinearpart_b=NULL;
    cl_int ret;
    cl_uint num_platforms;
// Detect how many platforms there are.
	ret = clGetPlatformIDs(0, NULL, &num_platforms);
// Allocate enough space for the number of platforms.
	platform_id = (cl_platform_id*) malloc(num_platforms*sizeof(cl_platform_id));
// Store the platforms
	ret = clGetPlatformIDs(num_platforms, platform_id, NULL);
	printf("Found %d platform(s)!\n",num_platforms);
    cl_uint *num_devices;
	num_devices=(cl_uint*) malloc(num_platforms*sizeof(cl_uint));
    cl_device_id **device_id = NULL;
	device_id =(cl_device_id**) malloc(num_platforms*sizeof(cl_device_id*));
// Detect number of devices in the platforms
	for(i=0;i<num_platforms;i++){
		char buf[65536];
		size_t size;
		ret = clGetPlatformInfo(platform_id[i],CL_PLATFORM_VERSION,sizeof(buf),buf,&size);
		printf("%s\n",buf);
		ret = clGetDeviceIDs(platform_id[i],CL_DEVICE_TYPE_ALL,0,NULL,num_devices);
		printf("Found %d device(s) on platform %d!\n", num_devices[i],i);
		ret = clGetPlatformInfo(platform_id[i],CL_PLATFORM_NAME,sizeof(buf),buf,&size);
		printf("%s ",buf);
// Store numDevices from platform
		device_id[i]=(cl_device_id*) malloc(num_devices[i]*sizeof(device_id));
		ret = clGetDeviceIDs(platform_id[i],CL_DEVICE_TYPE_ALL,num_devices[i],device_id[i],NULL);
		for(j=0;j<num_devices[i];j++){
			ret = clGetDeviceInfo(device_id[i][j],CL_DEVICE_NAME,sizeof(buf),buf,&size);
			printf("%s (%d,%d)\n",buf,i,j);
		}
	}
//create context and command_queue
    cl_context context = NULL;
   	cl_command_queue command_queue = NULL;
//Which platform and device do i choose?
	int	chooseplatform=0;
	int	choosedevice=0;	  
	printf("Choose platform %d and device %d!\n",chooseplatform,choosedevice);
	context = clCreateContext( NULL, num_devices[chooseplatform], device_id[chooseplatform], NULL, NULL, &ret);
	if(ret!=CL_SUCCESS){printf("createContext ret:%d\n",ret); exit(1); }
	command_queue = clCreateCommandQueue(context, device_id[chooseplatform][choosedevice], 0, &ret);
	if(ret!=CL_SUCCESS){printf("createCommandQueue ret:%d\n",ret); exit(1); }

//OpenCL arrays
    cl_mem cl_u = NULL,cl_v = NULL;
   	cl_mem cl_uhat = NULL, cl_vhat = NULL;
    cl_mem cl_kx = NULL, cl_ky = NULL;

//FFT
	clfftPlanHandle planHandle;
    cl_mem tmpBuffer = NULL;
	fftinit(&planHandle,&context, &command_queue, &tmpBuffer, Nx, Ny);

//allocate gpu memory/
	cl_u=clCreateBuffer(context, CL_MEM_READ_WRITE, 2*Nx* Ny* sizeof(double), NULL, &ret);
	cl_v=clCreateBuffer(context, CL_MEM_READ_WRITE, 2*Nx* Ny* sizeof(double), NULL, &ret);
	cl_uhat=clCreateBuffer(context, CL_MEM_READ_WRITE, 2*Nx * Ny* sizeof(double), NULL, &ret);
	cl_vhat=clCreateBuffer(context, CL_MEM_READ_WRITE, 2*Nx * Ny* sizeof(double), NULL, &ret);
	cl_kx = clCreateBuffer(context, CL_MEM_READ_WRITE, Nx * sizeof(double), NULL, &ret);
	cl_ky = clCreateBuffer(context, CL_MEM_READ_WRITE, Ny * sizeof(double), NULL, &ret);

	printf("allocated space\n");
//load the kernels
	loadKernel(&frequencies,&context,&device_id[chooseplatform][choosedevice],"frequencies");
	loadKernel(&initialdata,&context,&device_id[chooseplatform][choosedevice],"initialdata"); 
	loadKernel(&linearpart,&context,&device_id[chooseplatform][choosedevice],"linearpart"); 
	loadKernel(&nonlinearpart_a,&context,&device_id[chooseplatform][choosedevice],"nonlinearpart_a"); 
	loadKernel(&nonlinearpart_b,&context,&device_id[chooseplatform][choosedevice],"nonlinearpart_b"); 

	size_t global_work_size[1] = {Nx*Ny};
	size_t global_work_size_X[1] = {Nx};
	size_t global_work_size_Y[1] = {Ny};
//frequencies
    ret = clSetKernelArg(frequencies, 0, sizeof(cl_mem),(void *)&cl_kx);
	ret = clSetKernelArg(frequencies, 1, sizeof(double),(void* )&Lx);
	ret = clSetKernelArg(frequencies, 2, sizeof(int),(void* )&Nx);
    ret = clEnqueueNDRangeKernel(command_queue, frequencies, 1, NULL, global_work_size_X, NULL, 0, NULL, NULL);
	ret = clFinish(command_queue);
    ret = clSetKernelArg(frequencies, 0, sizeof(cl_mem),(void *)&cl_ky);
	ret = clSetKernelArg(frequencies, 1, sizeof(double),(void* )&Ly);
	ret = clSetKernelArg(frequencies, 2, sizeof(int),(void* )&Ny);
    ret = clEnqueueNDRangeKernel(command_queue, frequencies, 1, NULL, global_work_size_Y, NULL, 0, NULL, NULL);
	ret = clFinish(command_queue);
//printCL(&cl_kx,&command_queue,Nx,1);
//printCL(&cl_ky,&command_queue,1,Ny);
//inintial data
    ret = clSetKernelArg(initialdata, 0, sizeof(cl_mem),(void *)&cl_u);
	ret = clSetKernelArg(initialdata, 1, sizeof(cl_mem),(void* )&cl_v);
	ret = clSetKernelArg(initialdata, 2, sizeof(int),(void* )&Nx);
	ret = clSetKernelArg(initialdata, 3, sizeof(int),(void* )&Ny);
	ret = clSetKernelArg(initialdata, 4, sizeof(double),(void* )&Lx);
	ret = clSetKernelArg(initialdata, 5, sizeof(double),(void* )&Ly);
    ret = clEnqueueNDRangeKernel(command_queue, initialdata, 1, NULL, global_work_size, NULL, 0, NULL, NULL);
	ret = clFinish(command_queue);
//make output
    writedata_C(&cl_u, &command_queue,Nx,Ny,plotnum,"u");
    writedata_C(&cl_v, &command_queue,Nx,Ny,plotnum,"v");
    umax[plotnum]=writeimage(&cl_u, &command_queue,Nx,Ny,plotnum,"u");
    vmax[plotnum]=writeimage(&cl_v, &command_queue,Nx,Ny,plotnum,"v");
	printf("Got initial data, starting timestepping\n");
	mtime_s(&tvs);

	for(n=0;n<=Tmax;n++){
//nonlinearpart_a
    ret = clSetKernelArg(nonlinearpart_a, 0, sizeof(cl_mem),(void *)&cl_u);
	ret = clSetKernelArg(nonlinearpart_a, 1, sizeof(cl_mem),(void* )&cl_v);
	ret = clSetKernelArg(nonlinearpart_a, 2, sizeof(double),(void* )&A);
	ret = clSetKernelArg(nonlinearpart_a, 3, sizeof(double),(void* )&dt);
	ret = clSetKernelArg(nonlinearpart_a, 4, sizeof(double),(void* )&a);
    ret = clEnqueueNDRangeKernel(command_queue, nonlinearpart_a, 1, NULL, global_work_size, NULL, 0, NULL, NULL);
	ret = clFinish(command_queue);	

//nonlinearpart_b
    ret = clSetKernelArg(nonlinearpart_b, 0, sizeof(cl_mem),(void *)&cl_u);
	ret = clSetKernelArg(nonlinearpart_b, 1, sizeof(cl_mem),(void* )&cl_v);
	ret = clSetKernelArg(nonlinearpart_b, 2, sizeof(double),(void* )&A);
	ret = clSetKernelArg(nonlinearpart_b, 3, sizeof(double),(void* )&dt);
	ret = clSetKernelArg(nonlinearpart_b, 4, sizeof(double),(void* )&b);
    ret = clEnqueueNDRangeKernel(command_queue, nonlinearpart_b, 1, NULL, global_work_size, NULL, 0, NULL, NULL);
	ret = clFinish(command_queue);

//linear
	fft2dfor(&cl_u, &cl_uhat,&planHandle,&command_queue,&tmpBuffer);
	fft2dfor(&cl_v, &cl_vhat,&planHandle,&command_queue,&tmpBuffer);
//printf("A%f,B%f\n",A,B);
    ret = clSetKernelArg(linearpart, 0, sizeof(cl_mem),(void *)&cl_uhat);
    ret = clSetKernelArg(linearpart, 1, sizeof(cl_mem),(void *)&cl_vhat);
	ret = clSetKernelArg(linearpart, 2, sizeof(cl_mem),(void* )&cl_kx);
	ret = clSetKernelArg(linearpart, 3, sizeof(cl_mem),(void* )&cl_ky);
	ret = clSetKernelArg(linearpart, 4, sizeof(double),(void* )&Du);
	ret = clSetKernelArg(linearpart, 5, sizeof(double),(void* )&Dv);
	ret = clSetKernelArg(linearpart, 6, sizeof(double),(void* )&A);
	ret = clSetKernelArg(linearpart, 7, sizeof(double),(void* )&B);
	ret = clSetKernelArg(linearpart, 8, sizeof(double),(void* )&dt);
	ret = clSetKernelArg(linearpart, 9, sizeof(double),(void* )&c);
	ret = clSetKernelArg(linearpart, 10, sizeof(int),(void* )&Nx);
	ret = clSetKernelArg(linearpart, 11, sizeof(int),(void* )&Ny);
    ret = clEnqueueNDRangeKernel(command_queue, linearpart, 1, NULL, global_work_size, NULL, 0, NULL, NULL);
	ret = clFinish(command_queue);

	fft2dback(&cl_u, &cl_uhat,&planHandle,&command_queue,&tmpBuffer);
  	fft2dback(&cl_v, &cl_vhat,&planHandle,&command_queue,&tmpBuffer);

//nonlinearpart_b
    ret = clSetKernelArg(nonlinearpart_b, 0, sizeof(cl_mem),(void *)&cl_u);
	ret = clSetKernelArg(nonlinearpart_b, 1, sizeof(cl_mem),(void* )&cl_v);
	ret = clSetKernelArg(nonlinearpart_b, 2, sizeof(double),(void* )&A);
	ret = clSetKernelArg(nonlinearpart_b, 3, sizeof(double),(void* )&dt);
	ret = clSetKernelArg(nonlinearpart_b, 4, sizeof(double),(void* )&b);
    ret = clEnqueueNDRangeKernel(command_queue, nonlinearpart_b, 1, NULL, global_work_size, NULL, 0, NULL, NULL);
	ret = clFinish(command_queue);		
//nonlinearpart_a
    ret = clSetKernelArg(nonlinearpart_a, 0, sizeof(cl_mem),(void *)&cl_u);
	ret = clSetKernelArg(nonlinearpart_a, 1, sizeof(cl_mem),(void* )&cl_v);
	ret = clSetKernelArg(nonlinearpart_a, 2, sizeof(double),(void* )&A);
	ret = clSetKernelArg(nonlinearpart_a, 3, sizeof(double),(void* )&dt);
	ret = clSetKernelArg(nonlinearpart_a, 4, sizeof(double),(void* )&a);
    ret = clEnqueueNDRangeKernel(command_queue, nonlinearpart_a, 1, NULL, global_work_size, NULL, 0, NULL, NULL);
	ret = clFinish(command_queue);	
// done
	if(n==plottime){
		printf("time:%f, step:%d,%d,umax:%f,vmax:%f\n",n*dt,n,plotnum,umax[plotnum],vmax[plotnum]);
		plottime=plottime+plotgap;
		plotnum=plotnum+1;
   	 	writedata_C(&cl_u, &command_queue,Nx,Ny,plotnum,"u");
    	writedata_C(&cl_v, &command_queue,Nx,Ny,plotnum,"v");
        umax[plotnum]=writeimage(&cl_u, &command_queue,Nx,Ny,plotnum,"u");
        vmax[plotnum]=writeimage(&cl_v, &command_queue,Nx,Ny,plotnum,"v");
	}
}//end timestepping

	printf("Finished time stepping\n");
	mtime_e(&tvs,"Programm took:");
	writearray(umax,(Tmax/plotgap)+1,"u");
	writearray(vmax,(Tmax/plotgap)+1,"v");
	free(umax);
	free(vmax);	

	clReleaseMemObject(cl_u);
	clReleaseMemObject(cl_v);
	clReleaseMemObject(cl_uhat);
	clReleaseMemObject(cl_vhat);
	clReleaseMemObject(cl_kx);
	clReleaseMemObject(cl_ky);

    ret = clReleaseKernel(initialdata); 
    ret = clReleaseKernel(frequencies); 
    ret = clReleaseKernel(linearpart); 
    ret = clReleaseKernel(nonlinearpart_a);
    ret = clReleaseKernel(nonlinearpart_b);

	fftdestroy(&planHandle, &tmpBuffer);

	ret = clReleaseCommandQueue(command_queue);
    ret = clReleaseContext(context);

	for(i=0;i<num_platforms;i++){free(device_id[i]);}
	free(device_id);
	free(platform_id);
	free(num_devices);
	printf("Program execution complete\n");

	return 0;
}
int Segment(int SizeH, int SizeW, unsigned char *inputdata)
{
	int labeleddata[SizeH][SizeW];
	int count;
	memset(labeleddata, 0, SizeH*SizeW*(sizeof(int)));
	count = TwoPassLable(SizeH, SizeW, inputdata, &labeleddata[0][0]);

	unsigned char fortest[SizeH][SizeW];
	for(int i=0; i<SizeH; i++)
	{
		for(int j=0; j<SizeW; j++)
		{
			fortest[i][j] = labeleddata[i][j]*50;
		}
	}
	writeimage("2a labeledmap.raw", &fortest[0][0], SizeH, SizeW, 1);

	int label = 1;
	int check = 0;
	int top, botton, left, right;
	for(int i=0; i<SizeH; i++)
	{
		for(int j=0; j<SizeW; j++)
		{
			if(labeleddata[i][j] == label)
			{
//				printf("top = %d  ", i);
				top = i;
				check = 1;
				break;
			}
		}
		if(check == 1)
		{
			check = 0;
			break;
		}
	}
	for(int j=0; j<SizeW; j++)
	{
		for(int i=0; i<SizeH; i++)
		{
			if(labeleddata[i][j] == label)
			{
//				printf("left = %d  ", j);
				left = j;
				check = 1;
				break;
			}
		}
		if(check == 1)
		{
			check = 0;
			break;
		}
	}
	for(int i=SizeH-1; i>=0; i--)
	{
		for(int j=SizeW-1; j>=0; j--)
		{
			if(labeleddata[i][j] == label)
			{
//				printf("botton = %d  ", i);
				botton = i;
				check = 1;
				break;
			}
		}
		if(check == 1)
		{
			check = 0;
			break;
		}
	}
	for(int j=SizeW-1; j>=0; j--)
	{
		for(int i=0; i<SizeH; i++)
		{
			if(labeleddata[i][j] == label)
			{
//				printf("right = %d  \n", j);
				right = j;
				check = 1;
				break;
			}
		}
		if(check == 1)
		{
			check = 0;
			break;
		}
	}
	int testH, testW;
	testH = botton - top + 1;
	testW = right - left + 1;

	int mayH, mayW;
	while(label < SizeH)
	{
		for(int i=0; i<SizeH; i++)
		{
			for(int j=0; j<SizeW; j++)
			{
				if(labeleddata[i][j] == label)
				{
//					printf("top = %d  ", i);
					top = i;
					check = 1;
					break;
				}
			}
			if(check == 1)
			{
				check = 0;
				break;
			}
		}
		for(int j=0; j<SizeW; j++)
		{
			for(int i=0; i<SizeH; i++)
			{
				if(labeleddata[i][j] == label)
				{
//					printf("left = %d  ", j);
					left = j;
					check = 1;
					break;
				}
			}
			if(check == 1)
			{
				check = 0;
				break;
			}
		}
		for(int i=SizeH-1; i>=0; i--)
		{
			for(int j=SizeW-1; j>=0; j--)
			{
				if(labeleddata[i][j] == label)
				{
//					printf("botton = %d  ", i);
					botton = i;
					check = 1;
					break;
				}
			}
			if(check == 1)
			{
				check = 0;
				break;
			}
		}
		for(int j=SizeW-1; j>=0; j--)
		{
			for(int i=0; i<SizeH; i++)
			{
				if(labeleddata[i][j] == label)
				{
//					printf("right = %d  \n", j);
					right = j;
					check = 1;
					break;
				}
			}
			if(check == 1)
			{
				check = 0;
				break;
			}
		}
		mayH = botton - top + 1;
		mayW = right - left + 1;

		if(abs(mayH - testH)<=2 && abs(mayW - testW)<= 2)
		{
			printf("")
		}

		label++;
	}


	return 0;
}
Ejemplo n.º 24
0
int32_t main(int argc, char *argv[])
{
	struct xvimage *image, *edges;

	FILE *output, *amira_script;
	char output_format;
	double r, v, b;
	iv_scene* scene;
	list *ss_result, *ss_result2;
	complexe *temp, *intersect_edges, *point;
	uint32_t i, rs, ps, d, N, lim, erode, j, keep, k, max, num_pt, *tab_pt, kept;
	char name[BASE_ALLOC];


	//*******************************************
	//Checking input values
	//*******************************************
	if (argc!=4)
	{
		fprintf(stderr, "usage: %s %s\n", argv[0], USAGE);
		return(-1);
	}

	//We read input image
	image=readimage(argv[1]);
	if (image==NULL)
	{
		fprintf(stderr, "Error: Could not read %s.\n", argv[1]);
		return(-1);
	}
	else if(datatype(image)!=VFF_TYP_1_BYTE)
	{
		fprintf(stderr, "Error: only CC image supported\n");
		return(-1);
	}


	//We extract some info
	rs=rowsize(image1);
	cs=colsize(image1);
	d=depth(image1);
	N=rs*cs*d;


	//We produce the edges image
	edges=copyimage(image);
	if(edges==NULL)
	{
		fprintf(stderr, "Memory allocation error : not enough memory.\n");
		return(-1);
	}
	//And keep only intersection edges in this image
	pix=0;
	for(k=0; k<d; k++)
		for(j=0; j<cs; j++)
			for(i=0; i<rs; i++)
			{
				if( (UCHARDATA(image1)[pix] & CC_AX) != 0)
				{
					t=cca_cardinal_containers(image1, pix, i, j, k, CC_AX, rs, rs*cs);
					if(t<3)
						UCHARDATA(image1)[pix]&=(255-CC_AX);
				}

				if( (UCHARDATA(image1)[pix] & CC_AY) != 0)
				{
					t=cca_cardinal_containers(image1, pix, i, j, k, CC_AY, rs, rs*cs);
					if(t<3)
						UCHARDATA(image1)[pix]&=(255-CC_AY);
				}

				if( (UCHARDATA(image1)[pix] & CC_AZ) != 0)
				{
					t=cca_cardinal_containers(image1, pix, i, j, k, CC_AZ, rs, rs*cs);
					if(t<3)
						UCHARDATA(image1)[pix]&=(255-CC_AZ);
				}

				pix++;
			}

	for(i=0; i<N; i++)
		UCHARDATA(image1)[i]&=255-(CC_VOL | CC_FXY | CC_FYZ | CC_FXZ | CC_PT);

	cca_makecomplex(image1);



	if(strcmp(argv[6], "keep")==0)
	{
		strategy=KEEP;
	}
	else if(strcmp(argv[6], "reject")==0)
	{
		strategy=REJECT;
	}
	else
	{
		fprintf(stderr, "usage: %s %s\n", argv[0], USAGE);
		return(-1);
	}


	mode_amira=0;
	if(argc==9)
	{
		if(strcmp(argv[8], "-amira")!=0)
		{
			fprintf(stderr, "usage: %s %s\n", argv[0], USAGE);
			freeimage(image);
			freeimage(edges);
			return(-1);
		}
		else
		{
			mode_amira=1;
		}
	}

	if(strcmp(argv[4], "fusion")==0)
	{
		mode=FUSION;
	}
	else if(strcmp(argv[4], "split")==0)
	{
		mode=SPLIT;
	}
	else
	{
		fprintf(stderr, "usage: %s %s\n", argv[0], USAGE);
		freeimage(image);
		freeimage(edges);
		return(-1);
	}


	rs=rowsize(image);
	ps=colsize(image)*rs;

	if(mode==SPLIT)
	{
		//Each surface will be written in different Inventor File
		//Create an AVIZO script which will allow to open all of them
		sprintf(name, "%s_avizo_load_script.hx", argv[3]);
		amira_script=fopen(name, "wb");
		if(amira_script==NULL)
		{
			fprintf(stderr, "Error: could not create file %s. Check directory permission.\n", name);
			freeimage(image);
			freeimage(edges);
			return(-1);
		}
		amira_script_init(amira_script);
	}
	else
	{
		sprintf(name, "%s.iv", argv[3]);
		output = fopen(name, "wb");
		if(output==NULL)
		{
			fprintf(stderr, "Error: could not create output file %s (directory exists?).\n", name);
			freeimage(image);
			freeimage(edges);
			return(-1);
		}
	}


	if(strcmp(argv[7], "NULL")!=0)
	{
		cca_image=allocimage(NULL, rs, ps/rs, depth(image), VFF_TYP_1_BYTE);
		if(cca_image==NULL)
		{
			fprintf(stderr, "Error: could not allocate memory\n");
			freeimage(image);
			freeimage(edges);
			return(-1);
		}
	}
	else
	{
		cca_image=NULL;
	}




	//*******************************************************
	//Preparation of the image and the scene
	//*******************************************************

	//In case we don't have a complex, uncomment following
	//cca_makecomplex(image);

	scene=inventor_new_scene(10, NULL);

	//Initialize the scene...
	if(scene==NULL)
	{
		fprintf(stderr, "Error when creating new scene.\n");
		return(-1);
	}

	//We add to our object the main materials (keep the surfaces for later)
	inventor_add_material_to_scene(scene, "MatPoint", POS_PT, 0.0, 0.0, 0.0, 0.1, 0.4, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
	inventor_add_material_to_scene(scene, "MatAX", POS_AX, 0.0, 0.0, 0.0, 0.1, 0.1, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
	inventor_add_material_to_scene(scene, "MatAY", POS_AY, 0.0, 0.0, 0.0, 0.1, 0.1, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
	inventor_add_material_to_scene(scene, "MatAZ", POS_AZ, 0.0, 0.0, 0.0, 0.1, 0.1, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
	inventor_add_material_to_scene(scene, "MatVXY", POS_VXY, 0.0, 0.0, 0.0, 0.65, 0.65, 0.65, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
	inventor_add_material_to_scene(scene, "MatVXZ", POS_VXZ, 0.0, 0.0, 0.0, 0.50, 0.50, 0.50, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
	inventor_add_material_to_scene(scene, "MatVYZ", POS_VYZ, 0.0, 0.0, 0.0, 0.80, 0.80, 0.80, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);


	if(mode==FUSION)
	{
		scene->output=output;
		inventor_init_file(scene);
	}



	//********************************************************
	//Make surface segmentation
	//********************************************************

	//Get the intersection edges
	intersect_edges=cca_to_complexe(edges);
	freeimage(edges);
	if(intersect_edges==NULL)
	{
		fprintf(stderr, "Error in function cca_to_complexe()\n");
		inventor_delete_scene(scene);
		freeimage(image);
		return (-1);
	}


	//Make separation of the complex into surface components
	ss_result=cca_simple_surface_segmentation_with_intersection_edges_and_exclusion_inclusion_image(image, intersect_edges, filter, strategy);
	if(ss_result==NULL)
	{
		fprintf(stderr, "Error: cca_simple_surface_segmentation_with_intersection_edges_and_exclusion_inclusion_image() failed.\n");
		inventor_delete_scene(scene);
		freeimage(image);
		return(-1);
	}
	//We don't need the image anymore
	freeimage(image);

	fprintf(stdout, "Found %d surfaces\n", ss_result->cpt -2);


	//The first item is the set of all vertices...
	temp=(complexe*)list_pop(ss_result);
	if(mode==SPLIT)
	{
		//We don't care.
		complexe_free_complexe(temp);
		point=NULL;
		tab_pt=NULL;
		num_pt=0;
	}
	else if(mode==FUSION)
	{
		for(i=0; i<ss_result->cpt; i++)
		{
			//Choose a random color for surfaces
			r=((double)rand())/((double)RAND_MAX);
			v=((double)rand())/((double)RAND_MAX);
			b=((double)rand())/((double)RAND_MAX);
			sprintf(name, "SurfXY_%d", i);
			inventor_add_material_to_scene(scene, name, POS_FXY, r, v, b, r, v, b, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
			r+=0.05; v+=0.05; b+=0.05;
			if(r>1.0) r=1.0;
			if(b>1.0) b=1.0;
			if(v>1.0) v=1.0;
			sprintf(name, "SurfXZ_%d", i);
			inventor_add_material_to_scene(scene, name, POS_FXZ, r, v, b, r, v, b, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
			r+=0.05; v+=0.05; b+=0.05;
			if(r>1.0) r=1.0;
			if(b>1.0) b=1.0;
			if(v>1.0) v=1.0;
			sprintf(name, "SurfYZ_%d", i);
			inventor_add_material_to_scene(scene, name, POS_FYZ, r, v, b, r, v, b, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
			inventor_write_material_to_file(scene, POS_FXY);
			inventor_write_material_to_file(scene, POS_FXZ);
			inventor_write_material_to_file(scene, POS_FYZ);
		}

		//All the surfaces will go in the same file.
		//The array of points therefore interest us, we keep it and write it in the inventor file
		point=temp;
		tab_pt=point->tab_pt_obj;
		num_pt=point->num_pt_obj;
		inventor_new_object(scene);
		//inventor_set_drawstyle(scene, INVISIBLE, 1, 1);
		inventor_declare_points(scene, "Points", tab_pt, num_pt, rs, ps, mode_amira);

	}


	//The second item is the set of all intersect edges... We don't care.
	temp=(complexe*)list_pop(ss_result);
	complexe_free_complexe(temp);






	//*******************************************************
	//Send the surfaces to output file
	//*******************************************************

	i=0; //Will be used for the filename
	kept=0;
	while(!list_isempty(ss_result))
	{
		//Get the object to write
		temp=(complexe*)list_pop(ss_result);

		keep=1;
		if(keep==1)
		{
			if(cca_image!=NULL)
				complexe_add_to_cca(cca_image, temp);

/*			if(temp->num_fxy>0) {k=temp->tab_fxy[0]; f=CC_FXY;}
			else if(temp->num_fxz>0) {k=temp->tab_fxz[0]; f=CC_FXZ;}
			else if(temp->num_fyz>0) {k=temp->tab_fyz[0]; f=CC_FYZ;}
			else assert(0);

			l=cca_list_container(cca_image, k, getxfrompixnum(k, rs, ps), getyfrompixnum(k, rs, ps), getzfrompixnum(k, rs, ps), f, rs, ps);
			assert(l->cpt==2);
			while(!list_isempty(l))
			{
				g=(face_desc*)list_pop(l);
				surf[kept][l->cpt -1]=LONGDATA(labels)[g->pixnumber];
				free(g);
			}
			assert(surf[kept][0] != surf[kept][1]);
			if(surf[kept][0] > surf[kept][1])
			{
				k=surf[kept][1];
				surf[kept][1]=surf[kept][0];
				surf[kept][0]=k;
			}
*/
			kept++;

			if(mode==SPLIT)
				complexe_compute_vertex_array(temp, rs, ps);

			if(mode==SPLIT)
			{
				//Choose a random color for surfaces
				r=((double)rand())/((double)RAND_MAX);
				v=((double)rand())/((double)RAND_MAX);
				b=((double)rand())/((double)RAND_MAX);
				sprintf(name, "SurfXY_%d", i);
				inventor_add_material_to_scene(scene, name, POS_FXY, r, v, b, r, v, b, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
				r+=0.05; v+=0.05; b+=0.05;
				if(r>1.0) r=1.0;
				if(b>1.0) b=1.0;
				if(v>1.0) v=1.0;
				sprintf(name, "SurfXZ_%d", i);
				inventor_add_material_to_scene(scene, name, POS_FXZ, r, v, b, r, v, b, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
				r+=0.05; v+=0.05; b+=0.05;
				if(r>1.0) r=1.0;
				if(b>1.0) b=1.0;
				if(v>1.0) v=1.0;
				sprintf(name, "SurfYZ_%d", i);
				inventor_add_material_to_scene(scene, name, POS_FYZ, r, v, b, r, v, b, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);


				//Create an output file for the surface

				sprintf(name, "%s.surf%d.%d.iv", argv[3], temp->num_fxy+temp->num_fyz+temp->num_fxz, i);
				output = fopen(name, "wb");
				if(output==NULL)
				{
					fprintf(stderr, "Error: could not create output file %s (directory exists?).\n", name);
					while(!list_isempty(ss_result))
					{
						temp=(complexe*)list_pop(ss_result);
						complexe_free_complexe(temp);
					}
					list_delete(ss_result, NO_FREE_DATA);
					inventor_delete_scene(scene);
					return(-1);
				}

				//Link the output with the scene
				scene->output=output;

				//And initialise the scene and the points
				inventor_init_file(scene);
				inventor_new_object(scene);
				//inventor_set_drawstyle(scene, INVISIBLE, 1, 1);
				inventor_declare_points(scene, "Points", temp->tab_pt_obj, temp->num_pt_obj, rs, ps, mode_amira);

				tab_pt=temp->tab_pt_obj;
				num_pt=temp->num_pt_obj;
				temp->num_pt_obj=0;
				temp->tab_pt_obj=NULL;
			}

			inventor_new_object(scene);


			if(mode==FUSION)
			{
				sprintf(name, "SurfXY_%d", i);
				inventor_add_material_to_scene(scene, name, POS_FXY, r, v, b, r, v, b, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
				sprintf(name, "SurfXZ_%d", i);
				inventor_add_material_to_scene(scene, name, POS_FXZ, r, v, b, r, v, b, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
				sprintf(name, "SurfYZ_%d", i);
				inventor_add_material_to_scene(scene, name, POS_FYZ, r, v, b, r, v, b, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
			}

			//inventor_call_defined(scene, "Points");
			complexe_to_inventor(scene, temp, num_pt, tab_pt, rs, ps, mode_amira);

			inventor_close_object(scene);

			fflush(scene->output);

			if(mode==SPLIT)
			{
				inventor_close_object(scene);
				fclose(scene->output);

				//For the amira script
				k=0;
				max=0;
				while(name[k]!='\0')
				{
					if(name[k]=='/')
						max=k+1;

					k++;
				}

				amira_script_add_iv_file(amira_script, &name[max], 1, 30*(i+1));

				free(tab_pt);
			}



		}
		i++;
		complexe_free_complexe(temp);
	}

	if(mode==FUSION)
	{
		inventor_close_object(scene);
		fclose(scene->output);
	}


	fprintf(stdout, "Kept %d surfaces\n", kept);

	/*for(i=0; i<kept-1; i++)
		for(k=i+1; k<kept; k++)
		{
			if(
*/
	if(cca_image!=NULL)
	{
		writeimage(cca_image, argv[7]);
		freeimage(cca_image);
	}

	//****************************************************
	//Program ends
	//****************************************************
	inventor_delete_scene(scene);
	list_delete(ss_result, NO_FREE_DATA);
	if(filter!=NULL)
		freeimage(filter);

	if(mode==SPLIT)
		fclose(amira_script);


	return(0);
}
int p3c(void)
{
	// initialize data of input
	const char *inputname = "trees.raw";
	int SizeW = 350;
	int SizeH = 258;
	int BytesPerPixel = 3;
	unsigned char inputdata[SizeH][SizeW][BytesPerPixel];

	// initialize data of output
	const char *outputname1 = "3c tree_SED_ans.raw";
	const char *outputname2 = "3c tree_MBVQ_ans.raw";
	int newSizeW = SizeW;
	int newSizeH = SizeH;
	int newBytesPerPixel = BytesPerPixel;
	unsigned char outputdata1[newSizeH][newSizeW][newBytesPerPixel];

	// read input
	readimage(inputname, &inputdata[0][0][0], SizeH, SizeW, BytesPerPixel);


	double inputC[SizeH][SizeW];
	double inputM[SizeH][SizeW];
	double inputY[SizeH][SizeW];

	for(int i=0; i<SizeH; i++)
	{
		for(int j=0; j<SizeW; j++)
		{
			inputC[i][j] = 1 - (inputdata[i][j][0] / 255.0);
			inputM[i][j] = 1 - (inputdata[i][j][1] / 255.0);
			inputY[i][j] = 1 - (inputdata[i][j][2] / 255.0);
//			printf("%d  %f  %f  %f\n", i, inputC[i][j], inputM[i][j], inputY[i][j]);
		}
	}

	// Separable Error Diffusion
	double sedC[SizeH][SizeW];
	double sedM[SizeH][SizeW];
	double sedY[SizeH][SizeW];
	FSErrorDiffFord(SizeH, SizeW, &inputC[0][0], &sedC[0][0]);
	FSErrorDiffFord(SizeH, SizeW, &inputM[0][0], &sedM[0][0]);
	FSErrorDiffFord(SizeH, SizeW, &inputY[0][0], &sedY[0][0]);

	for(int i=0; i<SizeH; i++)
	{
		for(int j=0; j<SizeW; j++)
		{
			outputdata1[i][j][0] = 255*(1 - sedC[i][j]);
			outputdata1[i][j][1] = 255*(1 - sedM[i][j]);
			outputdata1[i][j][2] = 255*(1 - sedY[i][j]);

//			printf("%d  %f  %f  %f\n", i, sedC[i][j], sedM[i][j], sedY[i][j]);
		}
	}
	writeimage(outputname1, &outputdata1[0][0][0], newSizeH, newSizeW, newBytesPerPixel);

	// MBVQ-based Error diffusion
	MBVQErrorDiff(inputname, outputname2, SizeH, SizeW, BytesPerPixel);

	return 0;
}
Ejemplo n.º 26
0
int main( int argc, char *argv[] )
{
    int ret = 1;
    int win_main, win_zoom, zoom_factor = 2;
    double p_x = -1, p_y = -1;
    unsigned char *zoom_buf = NULL;
    unsigned char *img_buf = NULL;
    int img_width, img_height, img_msk;
    int crosshairs = 1;

    if ( argc < 2 ) {
	fprintf(stderr,"[USAGE]\n");
	fprintf(stderr,"%s filename.png\n",argv[0]);
	return 1;
    }

    /* zoom ウィンドゥ用の画像バッファ */
    zoom_buf = (unsigned char *)malloc(ZOOMWN_WIDTH * ZOOMWN_HEIGHT * 4);
    if ( zoom_buf == NULL ) goto quit;

    //img_buf = readimage(NULL,argv[1],&img_width,&img_height,&img_msk);
    //img_buf = readimage("xbmtopbm",argv[1],&img_width,&img_height,&img_msk);
#ifdef USE_IMAGEMAGICK
    img_buf = readimage("convert",argv[1],&img_width,&img_height,&img_msk);
#else
    img_buf = readimage("pngtopnm",argv[1],&img_width,&img_height,&img_msk);
#endif
    if ( img_buf == NULL ) {
	fprintf(stderr,"ERROR: cannot read file\n");
	goto quit;
    }
    printf("mask value = %d\n",img_msk);

    /* 属性設定(左上を原点にする) */
    gsetinitialattributes(DISABLE, BOTTOM_LEFT_ORIGIN);
    /* ウィンドゥのオープン */
    win_zoom = gopen(ZOOMWN_WIDTH*2, ZOOMWN_HEIGHT);
    win_main = gopen(img_width, img_height);
    layer(win_zoom,0,1);

    /* メインウィンドゥへの画像の転送 */
    gclr(win_main);
    gputimage(win_main, 0,0, img_buf, img_width, img_height, img_msk);

    /* カーソル描画のために,XOR での描画functionに設定 */
    newgcfunction(win_main, GXxor);
    newcolor(win_main, "red");

#if 0	/* 保存のテスト */
    //writeimage(img_buf,img_width,img_height,img_msk,"pnmtopng",256,"hoge.png");
    //writeimage(img_buf,img_width,img_height,img_msk,NULL,256,"hoge.pam");
    gsaveimage( win_main,0,0,0,1999,1999,"pnmtopng",256,"capt0.png");
    {
	int im_w, im_h;
	unsigned char *im = ggetimage(win_main,0,0,0,1999,1999,&im_w,&im_h);
	writeimage(im_w,im_h,im,0,"pnmtopng",256,"capt.png");
	if ( im != NULL ) free(im);
    }
#endif

    /* メインループ */
    while ( 1 ) {
	int win_ev, type, b;
	int needs_redraw = 0;
	double x, y;
	win_ev = ggetevent(&type,&b,&x,&y) ;
	if ( type == EnterNotify ) {
	    fprintf(stderr,"event type = EnterNotify wid=%d\n",win_ev);
	}
	else if ( type == LeaveNotify ) {
	    fprintf(stderr,"event type = LeaveNotify wid=%d\n",win_ev);
	}
	else {
	    fprintf(stderr,"event type = %d wid=%d\n",type,win_ev);
	}
	if ( win_ev == win_main ) {
	    if ( type == MotionNotify || 
		 type == EnterNotify || type == LeaveNotify ) {
		if ( type == LeaveNotify ) {
		    x = -32000;  y = -32000;
		}
		if ( crosshairs ) {
		    /* crosshairs カーソルを消す */
		    drawline(win_main, 0,p_y, img_width,p_y);
		    drawline(win_main, p_x,0, p_x,img_height);
		    /* crosshairs カーソルを表示する */
		    drawline(win_main, 0,y, img_width,y);
		    drawline(win_main, x,0, x,img_height);
		}
		needs_redraw = 1;
		p_x = x;
		p_y = y;
	    }
	    else if ( type == ButtonPress ) {
		if ( b == 1 ) zoom_factor++;
		else if ( b == 3 ) zoom_factor--;
		needs_redraw = 1;
	    }
	}
	if ( type == KeyPress ) {
	    if ( b == 'q' ) goto quit;
	    else if ( b == '>' || b == '+' ) zoom_factor++;
	    else if ( b == '<' || b == '-' ) zoom_factor--;
	    else if ( b == ' ' ) {
		if ( crosshairs ) {
		    /* crosshairs カーソルを消す */
		    drawline(win_main, 0,p_y, img_width,p_y);
		    drawline(win_main, p_x,0, p_x,img_height);
		    crosshairs = 0;
		}
		else {
		    /* crosshairs カーソルを表示する */
		    drawline(win_main, 0,p_y, img_width,p_y);
		    drawline(win_main, p_x,0, p_x,img_height);
		    crosshairs = 1;
		}
	    }
	    needs_redraw = 1;
	}
	if ( needs_redraw ) {
	    if ( zoom_factor < 2 ) zoom_factor = 2;
	    else if ( 32 < zoom_factor ) zoom_factor = 32;
	    get_zoom_image(img_width, img_height,
			   img_buf, p_x, p_y, zoom_factor,
			   ZOOMWN_WIDTH, ZOOMWN_HEIGHT, zoom_buf);
	    gclr(win_zoom);
	    /* 普通のコピー */
	    newgcfunction(win_zoom, GXcopy);
	    gputimage(win_zoom, 0, 0, 
		      zoom_buf, ZOOMWN_WIDTH, ZOOMWN_HEIGHT, img_msk);
	    /* 反転コピー */
	    newgcfunction(win_zoom, GXcopyInverted);
	    gputarea(win_zoom, ZOOMWN_WIDTH, 0, 
		     win_zoom,1, 0,0,ZOOMWN_WIDTH-1, ZOOMWN_HEIGHT-1);
	    /* ズームウィンドゥで,文字列を反転描画する */
	    newgcfunction(win_zoom, GXinvert);
	    drawstr(win_zoom,2,14,14,0,
		    "%dx zoom pos=(%g,%g)\n",zoom_factor,p_x,p_y);
	    copylayer(win_zoom,1,0);
	}
    }

    ret = 0;
 quit:
    gcloseall();
    if ( img_buf != NULL ) free(img_buf);
    if ( zoom_buf != NULL ) free(zoom_buf);
    return ret;
}
Ejemplo n.º 27
0
/**
 * \brief main function
 */
int	main(int argc, char *argv[]) {
	int	ierr;
	int	num_procs;
	int	tag = 1;
	double	h = 1;
	int	steps = 1;
	char	*basedir = NULL;

	udata_t	udata;
	udata.nx = 1;
	udata.ny = 1;
	udata.dimension = 16;
	udata.algorithm = 0;
	udata.picturesteps = 1;

	// initialize MPI
	ierr = MPI_Init(&argc, &argv);
	if (ierr) {
		fprintf(stderr, "cannot initialize MPI: %d\n", ierr);
		return EXIT_FAILURE;
	}

	// get MPI dimension parameters
	ierr = MPI_Comm_rank(MPI_COMM_WORLD, &udata.rank);
	ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
	char	rankprefix[10];
	snprintf(rankprefix, sizeof(rankprefix), "%d", udata.rank);

	if (debug) {
		fprintf(stderr, "%s:%d[%d]: process id %d\n",
			__FILE__, __LINE__, udata.rank, getpid());
	}

	// parse the command line
	int	c;
	while (EOF != (c = getopt(argc, argv, "b:dh:r:s:t:x:y:n:a:?")))
		switch (c) {
		case 'd':
			debug++;
			break;
		case 's':
			udata.picturesteps = atoi(optarg);
			break;
		case 't':
			udata.maxsteps = atof(optarg);
			break;
		case 'x':
			udata.nx = atoi(optarg);
			break;
		case 'y':
			udata.ny = atoi(optarg);
			break;
		case 'b':
			basedir = optarg;
			break;
		case 'n':
			udata.dimension = atoi(optarg);
			break;
		case 'a':
			udata.algorithm = atoi(optarg);
			break;
		case '?':
			usage(argv[0]);
			return EXIT_SUCCESS;
		}


	udata.maxsteps = udata.dimension + udata.dimension;
	udata.h = 1 / udata.dimension;

	// make sure the arguments are consistent
	if (num_procs != udata.nx * udata.ny) {
		fprintf(stderr, "number of processes does not match "
			"dimensions: %d != %d x %d\n", num_procs, udata.nx,
			udata.ny);
		usage(argv[0]);
		return EXIT_FAILURE;
	}

	// compute horizontal and vertical index of this rank
	udata.rh = udata.rank % udata.nx;
	udata.rv = udata.rank / udata.nx;
	if (debug) {
		fprintf(stderr, "%s:%d[%d]: rh = %d, rv = %d\n",
			__FILE__, __LINE__, udata.rank, udata.rh, udata.rv);
	}

	// next argument is image file name
	if (argc <= optind) {
		fprintf(stderr, "image file name argument missing\n");
		usage(argv[0]);
		return EXIT_FAILURE;
	}
	char	*imagefilename = argv[optind++];

	// next argument is output file name
	char	*netcdffilename = NULL;
	if (argc > optind) {
		netcdffilename = argv[optind++];
		if (debug) {
			fprintf(stderr, "%s:%d: netcdffilename: %s\n",
				__FILE__, __LINE__, netcdffilename);
		}
	}

	// image file and output file
	heatfile_t      *hf = NULL;
	image_t	*image = NULL;
	
	// process zero initializes and writes data
	if (udata.rank == 0) {
		// read the image file
		image = readimage(imagefilename);
		if (NULL == image) {
			fprintf(stderr, "cannot read image\n");
			return EXIT_FAILURE;
		}
		if (debug) {
			fprintf(stderr, "%s:%d[%d]: %d x %d image read\n",
				__FILE__, __LINE__, udata.rank,
				image->width, image->height);
		}

		// create the output file
		if (netcdffilename) {
			if (debug) {
				fprintf(stderr, "%s:%d: creating NetCDF %s\n",
					__FILE__, __LINE__, netcdffilename);
			}
			hf = output2_create(netcdffilename, h,
				steps * udata.ht, image->width, image->height);
			if (NULL == hf) {
				fprintf(stderr, "cannot create output file\n");
				return EXIT_FAILURE;
			}
		}
	}

	// write the first image
	if ((basedir) && (udata.rank == 0)) {
		char	outfilename[1024];
		snprintf(outfilename, sizeof(outfilename), "%s/00000.fits",
			basedir);
		writeimage(image, outfilename);
	}

	// index ranges for each rank
	udata.ranges = (int *)malloc(4 * num_procs * sizeof(int));
	if (udata.rank == 0) {
		partitiondomain(&udata, image);
	}

	// exchange range size information with all other ranks. The ranks
	// then pick the dimensions they need from the array, this is
	// the purpose of the range pointer
	MPI_Bcast(udata.ranges, 4 * num_procs, MPI_INT, 0, MPI_COMM_WORLD);
	int	*range = &udata.ranges[4 * udata.rank];
	if (debug) {
		fprintf(stderr, "%s:%d:[%d]: [%d,%d) x [%d,%d)\n",
			__FILE__, __LINE__, udata.rank,
			range[0], range[1], range[2], range[3]);
	}

	// allocate memory for the area we are responsible for
	udata.width = range[1] - range[0];
	udata.height = range[3] - range[2];
	allocate_u(&udata);
	double	*unew = (double *)malloc(udata.length * sizeof(double));
	if (debug) {
		fprintf(stderr, "%s:%d[%d]: arrays allocated, %d x %d\n",
			__FILE__, __LINE__,
			udata.rank, udata.width, udata.height);
	}

	// write initial data to the output file
	if ((hf) && (udata.rank == 0)) {
		output2_add(hf, 0, image->data);
	}

	// measure start time (after all allocations are done)
	double	start = gettime();

	// process 0 has to send the data to all the other processes
	if (udata.rank == 0) {
		for (int r = 1; r < num_procs; r++) {
			sendimagerange(&udata, image, r, tag);
		}
		copyfromimage(&udata, image);
	} else {
		// receive my part of the matrix
		receiverange(&udata, tag);
	}
	tag++;

	// make sure dimension is correct
	if (udata.dimension != udata.height + udata.width) {
		fprintf(stderr, "dimension does not match\n");
		return EXIT_FAILURE;
	}

	// start the solver algorithm
	int	stepcounter = 0;	// counter for time steps
	while (stepcounter < udata.maxsteps) {
		stepcounter++;

		// copy everything to unew as the initial approximation
		for (int i = 0; i < udata.length; i++) {
			unew[i] = udata.u[i];
		}

		// now perform <picturesteps> iterations
		for (int k = 0; k < udata.picturesteps; k++) {
			// synchronize current values of boundary with neighbors
			tag++;
			exchange_boundaries(&udata, tag);

			// perform iteration step
			iterate_u(unew, &udata);

			// copy the new u to the old u / only used for Jacobi
			if (udata.algorithm == 0) {
				for (int i = 0; i < udata.length; i++) {
					udata.u[i] = unew[i];
				}
			}
		}

		// decide whether we have to output something
		if (0) {
			// time value for this data output
			int	stepvalue = stepcounter / udata.picturesteps;

			// output needed, so we synchronize image data
			tag++;
			synchronize_image(&udata, image, tag);

			// write an image
			if ((basedir) && (udata.rank == 0)) {
				char	outfilename[1024];
				snprintf(outfilename, sizeof(outfilename),
					"%s/%05d.fits", basedir, stepvalue);
				writeimage(image, outfilename);
			}

			// write solution data
			if ((hf) && (udata.rank == 0)) {
				output2_add(hf, stepvalue, image->data);
			}
		}
	}

	// measure end time
	double	end = gettime();

	// we are now done, rank 0 displays the result
	if (udata.rank == 0) {
		printf("%.6f",end - start);
	}

	// close the netcdf file
	if ((udata.rank == 0) && (hf)) {
		output_close(hf);
	}

	// cleanup MPI
	MPI_Finalize();

	// cleanup the memory we have allocated
	free(udata.ranges); udata.ranges = NULL;
	free_u(&udata);

	return EXIT_SUCCESS;
}
Ejemplo n.º 28
0
int32_t MSF3d(struct xvimage *ga, struct xvimage *marqueurs)
#undef F_NAME
#define F_NAME "MSF3d"
{
  int32_t i;
  int32_t u,v;                                  /* une arete */
  int32_t x,y,z, x_1,y_1;                       /* des sommets */
  int32_t rs = rowsize(ga);                     /* taille ligne */
  int32_t cs = colsize(ga);                     /* taille colonne */
  int32_t ps = rs*cs;
  int32_t ds = depth(ga);                       /* taille plan */
  int32_t N = ds * ps;                          /* taille image */
  uint8_t *F = UCHARDATA(ga);         /* valuation des aretes de depart */
  int32_t *G =  SLONGDATA(marqueurs); /* labels des sommets du graph */
  int32_t N_t=3*N;                              /* index maximum d'une arete de ga */
  Rbt *L;                                   /* ensembles des aretes adjacentes à exactement un label */

  if (depth(ga) == 1){
    return MSF(ga, marqueurs);
  }
  if ((rowsize(marqueurs) != rs) || (colsize(marqueurs) != cs) || (depth(marqueurs) != ds)) 
  {
    fprintf(stderr, "%s: incompatible image sizes\n", F_NAME);
    return 0;
  }
  IndicsInit(N_t);
  L = mcrbt_CreeRbtVide(N_t);
  for(u = 0; u < N_t; u ++){
    if( ( (u < N) && (u%rs < rs-1)) ||
	((u >= N) && (u < 2*N) && ( (u%ps) < (ps-rs))) ||
	((u >= 2*N) && (((u- (2*N))/ps) < (ds-1)))){
      x = Sommetx3d(u,N,rs,ps);
      y = Sommety3d(u,N,rs,ps);
      if((mcmin(G[x],G[y]) == 0) && (mcmax(G[x],G[y]) > 0)){
	/* u est growing edge */
	/*	printf("Initialisation: ds Rbt: (%d,%d)\n", x,y);*/
	mcrbt_RbtInsert(&L, (TypRbtKey)F[u], u);
	Set(u, TRUE);
      }else Set(u, FALSE);
    }else Set(u,FALSE);
  }
  
  while(!mcrbt_RbtVide(L)){
    u = RbtPopMin(L);
#ifdef DEBUG
    printf("poped arete u no: %d de niveau %d\n",u,F[u]);
#endif
    x = Sommetx3d(u,N,rs,ps);
    y = Sommety3d(u,N,rs,ps);
    if(G[x] > G[y]){z=x; x=y; y=z;}
#ifdef DEBUG
    printf("extremites de u (%d,%d);(%d,%d) \n",x%rs, x/rs, y%rs, y/rs); 
#endif
    if((mcmin(G[x],G[y]) == 0) && (mcmax(G[x],G[y]) > 0)){
      /* si u est une growing edge */
#ifdef DEBUG
      printf("label x: %d, label y :%d\n", G[x], G[y]);
#endif
      G[x] = G[y];
      /* parcours des aretes incidente à x */
      for(i = 0; i < 6; i++){
	v = incidente3d(x,i,rs,N,ps);
	if((v != -1) && (!IsSet(v, TRUE))){
	  /* si v n'est pas dans L */
#ifdef DEBUG
	  printf("aretes incidentes F[%d] %d\n", v, F[v]);
#endif
	  x_1 = Sommetx3d(v,N,rs,ps);
	  y_1 = Sommety3d(v,N,rs,ps);
#ifdef DEBUG
	  printf("extremites de v (%d), incidente à u (%d,%d);(%d,%d) \n",v, x_1%rs, x_1/rs, y_1%rs, y_1/rs);
#endif
	  if((mcmin(G[x_1],G[y_1]) == 0) && (mcmax(G[x_1],G[y_1]) > 0)){
	    /* v est une growing edge */
	    mcrbt_RbtInsert(&L, (TypRbtKey)F[v], v);
	    Set(v,TRUE);
	  }	  
	}
      }
    }
    UnSet(u,TRUE);
  }  
  writeimage(marqueurs,"./toto1");
  for(u = 0; u < N_t; u++)
    if( ( (u < N) && (u%rs < rs-1)) ||
	((u >= N) && (u < 2*N) && ( (u%ps) < (ps-rs))) ||
	((u >= 2*N) && (((u- (2*N))/ps) < (ds-1)))){
      if(G[Sommetx3d(u,N,rs,ps)] != G[Sommety3d(u,N,rs,ps)]) F[u] = 255; else F[u] = 0;
    }
  /* Terminer indicateur + R&B tree ... */

  IndicsTermine();
  mcrbt_RbtTermine(L);
  return 1;
}
Ejemplo n.º 29
0
Archivo: main.c Proyecto: damora/ivr
//-----------------------------------------------------------------------------------------------------------------------//
// main
//-----------------------------------------------------------------------------------------------------------------------//
int main(int argc,  char * argv[])
{
    int rc=0;
    int rank=0;
#ifdef MPI
    int comsize;

    // init MPI
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &comsize);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    fprintf(stderr,"rank=%d\n", rank);
#ifdef BGQ
    install_signal_handler();
#endif
#endif

    args = parseargs(argc, argv);

    // init, initcamera, initvolattrs
    if ((rc=init(args, rank) != 0)) {
        fprintf(stderr, "initialization failed: %d\n", rc);
        return 0;
    };

    //---------------------------- Platform Specific Display and Interaction ----------------------------------------//
#if LOCAL

    resettransforms();
    mystate.alpha=0.25f;

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
    glutInitWindowSize(WINDOWWIDTH, WINDOWHEIGHT);
    glutCreateWindow("iVR");
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMouseFunc(mousebutton);
    glutMotionFunc(mousemotion);
//    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glDisable(GL_DEPTH_TEST);
    glutMainLoop();
#elif MPI		// BEGIN MPI CODE
#ifdef REMOTE 	// START OF REMOTE RENDERING HANDSHAKE

    // connect to relay server
    if (rank == 0) {
        sockfd = initconnection(HOSTNAME, PORT);
        if (sockfd == -1) {
            fprintf(stderr,"remote connection failed, sockfd=%d\n",sockfd);
            freeall();
            exit(0);
        }
        fprintf(stderr,"relay connection succeeded\n");
    }
    PRINTDEBUG("%3d: \n", rank);
    boolean_t connected = TRUE;
    int ctr = 0;
    while (connected) {  // main loop when steering
        fprintf(stderr,"%3d: before steering control\n", rank);
        if (rank == 0) {
            rc = recvstate(sockfd, &mystate);
            fprintf(stderr,"bytes recvd=%d\n", rc);
            if (mystate.finish) connected = 0;;
            winwidth = mystate.winwidth;
            winheight=mystate.winheight;
        } // end if rank == 0 for remote visualization
        // wait until we've completed the handshake with steering client before proceeding;
        MPI_Barrier(MPI_COMM_WORLD);
        MPI_Bcast(&connected, 1, MPI_INT, 0, MPI_COMM_WORLD);
        if (!connected) break;
        MPI_Bcast((float *)&winwidth, 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast((float *)&winheight, 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast(&mystate.alpha, 1, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast(mystate.newconst, 6, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast(mystate.mvm, 16, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast(mystate.pm, 16, MPI_FLOAT, 0, MPI_COMM_WORLD);
        MPI_Bcast(mystate.vv, 4, MPI_FLOAT, 0, MPI_COMM_WORLD);
#endif
        float planeconst[6] = {pzero[0], pzero[1], pzero[2], pzero[3], pzero[4], pzero[5]};
        setviewport(&viewport, 0, 0, winwidth, winheight);
        setplaneconst(planeconst, mystate.newconst);
        setmvm(mvm, mystate.mvm);
        setpm(pm, mystate.pm);
        setfrustum(&viewvolume, mystate.vv);
        updatevolbbox();
        initcolbufs(rank);

        // create and display the image
        unsigned long long lstart, lstop;
        for (int i=0; i<1; i++) {
            TIME(RENDER, lstart);
            createlocalimage(rank);
            // can't composite until all ranks have completed local image generation
            MPI_Barrier(MPI_COMM_WORLD);
            compositelocalimage();
            TIME(RENDER, lstop);
            PERFORMANCE(lstart, lstop, framenum, elapsed, avg);
        }
        // wait until all ranks exit composite step before writing image
        MPI_Barrier(MPI_COMM_WORLD);
        writeimage(ctr++);
#ifdef REMOTE
    } // end while remote loop
    if (rank == 0) disconnect(sockfd);
#endif // END OF REMOTE CLIENT  HANDSHAKE


    fprintf(stderr,"%3d: finished\n", rank);
    MPI_Barrier(MPI_COMM_WORLD);
    MPI_Finalize();
#endif
    // clean up
    freeall();
    exit(0);
}