Esempio n. 1
0
int main() {
	FILE *input, *output;
	BMP bmp;
	int error;
	Color blue = {255, 0, 0};
	char nombre[50];
	scanf("%s",nombre);
	strcat(nombre,".bmp");
	printf("%s",nombre);
	input = fopen(nombre, "rb");
	error = 0;
	bmp = readBMP(input, &error);

	if (!error) {
		output = fopen("salida.bmp", "wb");

		flipBMP(&bmp);
		//greyscaleBMP(&bmp);
		tintBMP(&bmp, blue);

		writeBMP(bmp, output);
		freeBMP(&bmp);
		fclose(output);
	}
	else {
		puts("error al leer archivo");
	}

	fclose(input);
}
void TraceGLWindow::saveImage(char *iname)
{
	unsigned char* buf;

	raytracer->getBuffer(buf, m_nDrawWidth, m_nDrawHeight);
	if (buf)
		writeBMP(iname, m_nDrawWidth, m_nDrawHeight, buf); 
}
Esempio n. 3
0
// usage : ray [option] in.ray out.bmp
// Simply keying in ray will invoke a graphics mode version.
// Use "ray --help" to see the detailed usage.
// OK. I am lying. any illegal option such as "ray blahbalh" will print
// out the usage
//
// Graphics mode will be substantially slower than text mode because of
// event handling overhead.
int main(int argc, char **argv) {
	progname=argv[0];
	srand((unsigned)time(NULL));

	if (argc!=1) {
		// text mode
		if (!processArgs(argc, argv)) {
			usage();
			exit(1);
		}
		
		theRayTracer=new RayTracer();
		theRayTracer->loadScene(rayName);
	
		if (theRayTracer->sceneLoaded()) {
			g_height = (int)(g_width / theRayTracer->aspectRatio() + 0.5);

			theRayTracer->traceSetup(g_width, g_height, 2, 1.0, 0.0001);
		
			clock_t start, end;
			start=clock();

			theRayTracer->traceLines(0, g_height);
		
			end=clock();

			// save image
			unsigned char* buf;

			theRayTracer->getBuffer(buf, g_width, g_height);
			if (buf)
				writeBMP(imgName, g_width, g_height, buf); 

			if (bReport) {
				double t=(double)(end-start)/CLOCKS_PER_SEC;
#ifdef WIN32
				fl_message( "total time = %.3f seconds\n", t); 
#else
				fprintf( stderr, "total time = %.3f seconds\n", t); 
#endif
			}
		}

		return 1;
	} else {
		// graphics mode
		traceUI=new TraceUI();
		theRayTracer=new RayTracer();

		traceUI->setRayTracer(theRayTracer);

		Fl::visual(FL_DOUBLE|FL_INDEX);

		traceUI->show();

		return Fl::run();
	}
}
Esempio n. 4
0
void windowsIcon(iw_context* context, const char* filename) {
	//16x16
	//32x32
	//48x48
	//256x256

	ByteStream stream;
	writeIcoHeader(stream);

	writeIconDirEntry(stream, 16, 16, iconHeaderSize + iconDirEntrySize * 4);
	writeIconDirEntry(stream, 32, 32, iconHeaderSize + iconDirEntrySize * 4 + getBMPSize(16, 16));
	writeIconDirEntry(stream, 48, 48, iconHeaderSize + iconDirEntrySize * 4 + getBMPSize(16, 16) + getBMPSize(32, 32));
	writeIconDirEntry(stream, 256, 256, iconHeaderSize + iconDirEntrySize * 4 + getBMPSize(16, 16) + getBMPSize(32, 32) + getBMPSize(48, 48));

	scale(context, 16, 16);
	iw_image img;
	iw_get_output_image(context, &img);
	writeBMP(stream, &img);

	scale(context, 32, 32);
	iw_get_output_image(context, &img);
	writeBMP(stream, &img);

	scale(context, 48, 48);
	iw_get_output_image(context, &img);
	writeBMP(stream, &img);

	scale(context, 256, 256);
	iw_get_output_image(context, &img);
	iw_iodescr writedescr;
	memset(&writedescr, 0, sizeof(struct iw_iodescr));
	writedescr.write_fn = stream_writefn;
	writedescr.seek_fn = stream_seekfn;
	writedescr.fp = &stream;
	iw_write_file_by_fmt(context, &writedescr, IW_FORMAT_PNG);

	std::vector<byte> pngSize = convertIntToByteArrayLE(static_cast<int>(stream.size()) - (iconHeaderSize + iconDirEntrySize * 4 + getBMPSize(16, 16) + getBMPSize(32, 32) + getBMPSize(48, 48)));
	for (int i = 0; i < 4; ++i) stream.set(i + iconHeaderSize + iconDirEntrySize * 3 + 8, pngSize[i]);

	stream.save(filename);
}
Esempio n. 5
0
int main()
{  
	 
	///lectura de imagen
	char carName[50];
	printf("\n Introduzca el nombre de la imagen extension *BMP (ej:lena.bmp) : \n");
	scanf("%s", carName);

	IMAGE *img;
	//el formato de entrada de la imagen es nombre.extención, para este caso solo lee imagenes BMP.
	loadBMP(carName, &img);//el formato de entrada de la imagen es nombre.extención, para este caso solo lee imagenes BMP.
	//variables de entrada a la funcion
	uint8_t Rpixel;
	uint8_t Bpixel;
	uint8_t Gpixel;
	uint8_t maxi;
	uint8_t mini;
	float filtro;
	float H;
	float sat;
	int i;
	float *x;
	

	//recorriendo la imagen
	for (i = 0; i < img->width*img->height; i++) {
		Rpixel=(uint8_t)img->data[i].r;
		Bpixel=(uint8_t)img->data[i].b;
		Gpixel=(uint8_t)img->data[i].g;

		// se definen las funciones max y min para el calculo de los canales hsv
		maxi = (uint8_t)maxim(Rpixel, Gpixel, Bpixel);
		mini = (uint8_t)minim(Rpixel, Gpixel, Bpixel);
		sat = Saturacion(maxi, mini);//calculo de la saturacion del pixel
		H =Color(maxi,mini,Rpixel, Gpixel, Bpixel);//calculando canal de color H
		filtro=FiltroExperimental(H,sat,(float)(maxi)/255);//definiendo filtro multiplicador de color

		//retornando de hsv a rgb
		x=ConvHsvRgb(filtro*H,sat,(float)(maxi)/(255));

		//salida a imagen 
		img->data[i].r = x[1];
		img->data[i].g = x[2];
		img->data[i].b = x[3];
		}
	

	writeBMP("img.bmp", img); //guardado de imagen
	freeBMP(img);// libera memoria de la imagen.
	free(img);
	return 0;
}
Esempio n. 6
0
File: dll.c Progetto: Auzzy/school
void toDLL(packet* pack)
{
	message msg = pack->mess;
	if (msg.code == START_HEADER || msg.code == CONT_HEADER)
		addToMockBuffer(&msg,pack->length);
	else if (msg.code == END_HEADER)
	{
		addToMockBuffer(&msg,pack->length);
		
		mockHeaderLen = joinMessages(mockBuffer,mockBufferLen,&mockHeaderData);
		
		int k;
		for (k = 0; k<mockBufferLen; k++)
			free(mockBuffer[k].data);
		free(mockBuffer);
		mockBuffer = NULL;
		mockBufferLen = 0;
	}
	else if (msg.code == START_FILE || msg.code == CONT_FILE)
		addToMockBuffer(&msg,pack->length);
	else if (msg.code == END_FILE)
	{
		addToMockBuffer(&msg,pack->length);
		
		char* mockData = NULL;
		joinMessages(mockBuffer,mockBufferLen,&mockData);

		int success = writeBMP("test.bmp",mockHeaderData,mockData);
		if (success)
			printf("INFO: File succcessfully written.\n");
		
		int k;
		for (k = 0; k<mockBufferLen; k++)
			free(mockBuffer[k].data);
		free(mockBuffer);
		free(mockData);
		free(mockHeaderData);
		mockBuffer = NULL;
		mockBufferLen = 0;
	}
	else if (msg.code == SUCCESS)
		printf("INFO: %s\n",msg.data);
	else if (msg.code == ERROR)
		printf("ERROR: %s\n",msg.data);
	else if (msg.code == COMMAND)
		printf("DLL RECEIVED COMMAND: %s\n",msg.data);
	else
		printf("ERROR: Unrecognized code: %d\n",msg.code);
}
void FrameIOView::keyboard(int key,int scancode,int action,int mods) {
  if(key == GLFW_KEY_S && action == GLFW_PRESS) {
  	// taken from http://stackoverflow.com/questions/19173412
  	// we get the width/height of the screen into this array
    int screenStats[4];
    // get the width/height of the window
    glGetIntegerv(GL_VIEWPORT, screenStats);
    int width = screenStats[2];
    int height = screenStats[3];
    // generate an array large enough to hold the pixel data
    // (width*height*bytesPerPixel)
    unsigned char* pixels = new unsigned char[width * height * 3];
    // read in the pixel data, TGA's pixels are BGR aligned
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);

    writeBMP("test.bmp", width, height, pixels);
  }
}
int main(int argc, char *argv[])
{
    unsigned char* image;
    unsigned char header[54];
    unsigned char end[1024];
    unsigned char* final_image;
    float DesE = 20.0;
    int size;
    int window = 30;
    int TX,TY,p=4;
    double startT,stopT;
    int nt=4;

    if(isdigit(argv[1])){
       p = atoi(argv[1]);
    if(p<1 || p>20)
        printf("# of threads should be between 1 and 20 - it runs 4 threads -> default");
    else
        nt = p;
    }
    omp_set_num_threads(nt);

    startT = clock();
    double ss = omp_get_wtime();
    image = readBMP("lady1000.bmp",header,end,&size);

    //applying filter
    //extracting size
    TX = *(int*)&header[18];
    TY = *(int*)&header[22];

    final_image = (unsigned char*) malloc(size*sizeof(unsigned char));

    //copy image
    copy_image(image,final_image,size);
    //applying filter
    promediador(image,TX,TY,window,final_image,DesE);
    //write final result
    writeBMP("exit.bmp",final_image,header,end,size);

    stopT = clock();
    double ee = omp_get_wtime();
    printf("%d processors; %f secs\n",p,ee-ss);
}
Esempio n. 9
0
int main(int argc, char **argv) {
	tagBITMAPFILEHEADER BITMAPFILEHEADER; 
	tagBITMAPINFOHEADER BITMAPINFOHEADER;
	matrix image;
	char source_file_name[100];
	parameters inputParameters;
	bool dontStopMeNow = true;//flag for help calling or incorrect parameters

	initParameters(inputParameters);
	readParameters(argc, argv, inputParameters, source_file_name[0], dontStopMeNow);

	//function: sort parameters by queue --> user can combine it as he want

	if (dontStopMeNow) {
		readBMP(BITMAPFILEHEADER, BITMAPINFOHEADER, image, source_file_name[0]);

		runFilters(inputParameters, BITMAPFILEHEADER, BITMAPINFOHEADER, image);

		writeBMP(BITMAPFILEHEADER, BITMAPINFOHEADER, image);
	}	
}
Esempio n. 10
0
void Image::write(std::string filepath){
    ASSERT(loaded, "You didn't load the image!");
    ASSERT(path != INVALID_PATH, "You didn't provide a path for the Image");

    INFO("Writing image " << filepath << "...");

    std::string ext = getFileExtension(filepath);

    bool success = false;

    if(ext == BMP_EXT){
        unsigned int rc = writeBMP(filepath);
        if(!rc) success = true;
    }
    else if (ext == PNG_EXT){
        unsigned int rc = writePNG(filepath);
        if(!rc) success = true;
    }

    ASSERT(success, "Failed to write image " << filepath << "!");
    INFO("Image wrote " << filepath << "!");
}
Esempio n. 11
0
int main (void) {
	clock_t begin, einde;

	byte in[1280][1280], out[1280][1280];
	readBMP (in, "ct-scan.bmp");

	in_counter = 0; gtemp_counter = 0; gauss_counter = 0; edge_counter = 0; out_counter = 0;
	accux_counter = 0; accuy_counter = 0; buffer_counter = 0; memory_counter = 0;

	printf ("Version: %s\n", VERSION); 
	printf ("----------------------------------------------------\n");

#ifdef COUNT_MEMORY_ACCESSES
	cavityDetection (in, out);
	if (in_counter != 0) printf ("in:       %7d accesses\n", in_counter);
	if (gtemp_counter != 0) printf ("gtemp:    %7d accesses\n", gtemp_counter);
	if (gauss_counter != 0) printf ("gauss:    %7d accesses\n", gauss_counter);
	if (edge_counter != 0) printf ("edge:     %7d accesses\n", edge_counter);
	if (out_counter != 0) printf ("out:      %7d accesses\n", out_counter);
	if (accux_counter != 0) printf ("accux:    %7d accesses\n", accux_counter);
	if (accuy_counter != 0) printf ("accuy:    %7d accesses\n", accuy_counter);
	if (memory_counter != 0) printf ("memory: %7d accesses\n", memory_counter);
	printf ("----------------------------------------------------\n");
	printf ("Total:   %7d accesses\n", in_counter + gtemp_counter + gauss_counter + edge_counter + out_counter + accux_counter + accuy_counter + memory_counter);
	if (buffer_counter != 0) printf ("buffer:   %7d accesses\n", buffer_counter);
#else
	begin = clock();
	for (int i = 0; i < NUMBER_OF_TEST_RUNS; i++) cavityDetection (in, out);
	einde = clock();
	printf ("Execution time: %.1f ms\n", 1000 * (double) (einde - begin) / (double) CLOCKS_PER_SEC / (double) NUMBER_OF_TEST_RUNS);
#endif
	printf ("----------------------------------------------------\n");
	writeBMP (out, "output.bmp");
	diffBMP ("output.bmp", "output-correct.bmp", "output-diff.bmp");
	printf ("\n");

	return 0;
}
Esempio n. 12
0
inline void ModelerUserInterface::cb_Save_i(Fl_Menu_*, void*) {
  char *filename = NULL;
filename = fl_file_chooser("Save BMP File", "*.bmp", NULL);
if (filename)
{
	int x = m_modelerView->x();
	int y = m_modelerView->y();
	int w = m_modelerView->w();
	int h = m_modelerView->h();

	m_modelerWindow->show();
//	do {Sleep(10); }
//	while (!m_modelerWindow->shown());
//	m_modelerView->draw();
	m_modelerView->make_current();
        m_modelerView->draw();
	
		
	unsigned char *imageBuffer = new unsigned char[3*w*h];

        // Tell openGL to read from the front buffer when capturing
        // out paint strokes
        glReadBuffer(GL_BACK);

        glPixelStorei( GL_PACK_ALIGNMENT, 1 );
        glPixelStorei( GL_PACK_ROW_LENGTH, w );
        
        glReadPixels( 0, 0, w, h, 
                GL_RGB, GL_UNSIGNED_BYTE, 
                imageBuffer );


	writeBMP(filename, w,h, imageBuffer);

	delete [] imageBuffer;
};
}
void ModelerView::saveBMP(const char* szFileName)
{
	int xx = x();
	int yy = y();
	int ww = w();
	int hh = h();
	
	make_current();
	
	unsigned char *imageBuffer = new unsigned char[3 * ww * hh];
	
	glReadBuffer(GL_BACK);

    glPixelStorei(GL_PACK_ALIGNMENT, 1);
    glPixelStorei(GL_PACK_ROW_LENGTH, ww);
    
    glReadPixels( 0, 0, ww, hh, 
		GL_RGB, GL_UNSIGNED_BYTE, 
		imageBuffer );
	
	writeBMP(szFileName, ww, hh, imageBuffer);
	
	delete [] imageBuffer;
}
Esempio n. 14
0
int main( int argc, char* argv[] )
{
    //===================================================================
    // Get the command-line options.
    //===================================================================
    Options opt;
    if( !options( argc, argv , opt ) )
    {
        return 1;
    }

    // Output the options.
    std::cerr << "Using demo sequence " << opt.sequenceNumber << "." << std::endl;
    std::cerr << "Output path is: \"" << opt.outputPath << "\"." << std::endl;
    std::cerr << "Number Of Images: " << opt.nImages << std::endl;
    std::cerr << "Start frame: " << opt.startFrame << std::endl;

    std::cerr << "Blur mode: " << ( opt.blurMode == Options::kGentle ? "Gentle" : "Aggressive") << std::endl;
    std::cerr << "Blur strength: " << opt.blurStrength << std::endl;
    std::cerr << "Contribution strength: " << opt.contributionStrength << std::endl;
    std::cerr << "Kernel width: " << opt.kernelWidth << std::endl;

    // Load the images.
    std::vector< Image > images( opt.nImages );
    int frame = opt.startFrame;
    for( unsigned int i = 0; i < images.size(); ++i )
    {
        std::stringstream s;
        s << "images/image" << opt.sequenceNumber << "." << frame << ".ppm";

        if( !readPPM( s.str(), images[i] ) )
        {
            std::cerr << "Failed to open image " << s.str() << std::endl;
            return 1;
        }

        if( ++frame >= 11 )
        {
            frame = 0;
        }
    }

    //===================================================================
    // The algorithm.
    //===================================================================

    SampleSet set( images );
    const int width = set.width(), height = set.height();
    Image result( width, height );


    int kernelRadius = opt.kernelWidth > 1 ? ( opt.kernelWidth - 1 ) / 2 : 0;
    std::vector< double > srcSamples;
    for( int y = 0; y < height; ++y )
    {
        for( int x = 0; x < width; ++x )
        {
            fprintf(stderr,"\rFiltering %5.2f%% complete.", 100. * y / ( height-1 ) );

            // Loop over each channel.
            for( unsigned int c = 0; c < 3; ++c )
            {
                double destMean = set.mean( x, y, c );
                double destDeviation = set.deviation( x, y, c );
                double destVariation = set.variance( x, y, c );
                double destRange = set.max( x, y, c ) - set.min( x, y, c );

                // Loop over the neighbouring pixels.
                double weightedSum = 0.;
                double v = 0.;
                for( int ky = -kernelRadius; ky <= kernelRadius; ++ky )
                {
                    for( int kx = -kernelRadius; kx <= kernelRadius; ++kx )
                    {
                        // Don't include the pixel being sampled in our calculations as we are
                        // summing the deviations from it and doing so will bias our results.
                        if( ky == 0 && kx == 0 )
                        {
                            continue;
                        }

                        // Gather information on the source pixel's samples.
                        srcSamples = set.samples( x + kx, y + ky, c );
                        double srcMin = set.min( x + kx, y + ky, c );
                        double srcMax = set.max( x + kx, y + ky, c );
                        double srcMean = set.mean( x + kx, y + ky, c );
                        double srcDeviation = set.deviation( x + kx, y + ky, c );
                        double srcVariation = set.variance( x + kx, y + ky, c );
                        double srcRange = set.max( x + kx, y + ky, c ) - set.min( x + kx, y + ky, c );

                        if( srcVariation == 0 && srcSamples[0] == 0. ) continue;

                        // A gaussian falloff that weights contributing samples which are closer to the pixel being filtered higher.
                        /// \todo Intuitive falloff parameters need to be added to the distance weight or at least a suitable curve found.
                        double distanceWeight = gaussian( sqrt( kx*kx + ky*ky ) / sqrt( kernelRadius*kernelRadius + kernelRadius*kernelRadius ), 0., .7, false );

                        // Similarity weight.
                        // This weight defines a measure of how similar the set of contributing samples is to the pixel being filtered.
                        // By itself it will produce a smart blur of sorts which is then attenuated by the variance of the source samples in the process of weighted offsets.
                        // Changing this value will effect how aggressive the filtering is.
                        double similarity;
                        if( opt.blurMode == Options::kAggressive )
                        {
                            similarity = ( srcMean - destMean ) * ( srcRange - destRange );
                        }
                        else
                        {
                            similarity = ( srcMean - destMean );
                        }
                        similarity *= similarity;

                        // Temporal weight.
                        // Weight the contribution using a function in the range of 0-1 which weights the importance of the
                        // contributing sample according to how close it is in time to the current time.
                        double time = 1.; // \todo: implement this! Example functions are Median, Gaussian, etc.

                        // Loop over each of the neighbouring samples.
                        for( unsigned int i = 0; i < srcSamples.size(); ++i )
                        {
                            // The contribution weight extends the range of allowed samples that can influence the pixel being filtered.
                            // It is simply a scaler that increases the width of the bell curve that the samples are weighted against.
                            double contribution = gaussian( srcSamples[i], destMean, destDeviation * ( 1 + opt.contributionStrength ) ) * gaussian( srcSamples[i], srcMean, srcDeviation );
                            contribution = contribution * ( 1. - opt.blurStrength ) + opt.blurStrength;

                            // This weight is a step function with a strong falloff close to the limits. However, it will never reach 0 so that the sample is not excluded.
                            // By using this weight the dependency on the limiting samples is much less which reduces the effect of sparkling artefacts.
                            double limitWeight = srcSamples.size() <= 2 ? 1. : softStep( srcSamples[i], srcMin, srcMax );

                            // Combine the weights together and normalize to the range of 0-1.
                            double weight = pow( M_E, -( similarity / ( contribution * srcVariation * time * distanceWeight * limitWeight ) ) );
                            weight = ( isnan( weight ) || isinf( weight ) ) ? 0. : weight;

                            // Sum the offset.
                            v += ( srcSamples[i] - destMean ) * weight;

                            // Sum the weight.
                            weightedSum += weight;
                        }
                    }
                }

                if( weightedSum == 0. || destVariation <= 0. )
                {
                    result.writeable( x, y )[c] = destMean;
                }
                else
                {
                    result.writeable( x, y )[c] = destMean + ( v / weightedSum );
                }
            }
        }
    }

    bool success = false;
    if( opt.extension == "bmp" )
    {
        success = writeBMP( opt.outputPath.c_str(), result );
    }
    else
    {
        success = writePPM( opt.outputPath.c_str(), result );
    }

    if( !success )
    {
        std::cerr << "Failed to write image." << std::endl;
        return 1;
    }

    return 0;
}