Mat binarize(Mat * inputImage, int threshold)
{
	Mat outputImage(inputImage->rows, inputImage->cols, inputImage->type());
	int i, j;

	for (i = 0; i < outputImage.rows; i++)
	{
		for (j = 0; j < outputImage.cols; j++)
		{
			outputImage.at<uchar>(i, j) = (inputImage->at<uchar>(i, j) > (uchar)threshold);
		}
	}
	return outputImage;
}
Mat invert(Mat * inputImage)
{
	Mat outputImage(inputImage->rows, inputImage->cols, inputImage->type());
	int i, j;

	for (i = 0; i < outputImage.rows; i++)
	{
		for (j = 0; j < outputImage.cols; j++)
		{
			outputImage.at<uchar>(i, j) = !(inputImage->at<uchar>(i, j));
		}
	}

	return outputImage;
}
bool QgsCompositionChecker::testComposition( QString &theReport, int page, int pixelDiff )
{
  if ( !mComposition )
  {
    return false;
  }

  setControlName( "expected_" + mTestName );

#if 0
  //fake mode to generate expected image
  //assume 96 dpi and size of the control image 1122 * 794
  QImage newImage( QSize( 1122, 794 ), QImage::Format_RGB32 );
  mComposition->setPlotStyle( QgsComposition::Print );
  newImage.setDotsPerMeterX( 96 / 25.4 * 1000 );
  newImage.setDotsPerMeterY( 96 / 25.4 * 1000 );
  drawBackground( &newImage );
  QPainter expectedPainter( &newImage );
  //QRectF sourceArea( 0, 0, mComposition->paperWidth(), mComposition->paperHeight() );
  //QRectF targetArea( 0, 0, 3507, 2480 );
  mComposition->renderPage( &expectedPainter, page );
  expectedPainter.end();
  newImage.save( mExpectedImageFile, "PNG" );
  return true;
#endif //0

  QImage outputImage( mSize, QImage::Format_RGB32 );

  mComposition->setPlotStyle( QgsComposition::Print );
  outputImage.setDotsPerMeterX( mDotsPerMeter );
  outputImage.setDotsPerMeterY( mDotsPerMeter );
  drawBackground( &outputImage );
  QPainter p( &outputImage );
  mComposition->renderPage( &p, page );
  p.end();

  QString renderedFilePath = QDir::tempPath() + QDir::separator() + QFileInfo( mTestName ).baseName() + "_rendered.png";
  outputImage.save( renderedFilePath, "PNG" );

  setRenderedImage( renderedFilePath );

  bool testResult = runTest( mTestName, pixelDiff );

  theReport += report();

  return testResult;
}
Beispiel #4
0
static int producerGetImage(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int /*writable*/) {
    int error = 0;
    mlt_properties properties = MLT_FRAME_PROPERTIES(frame);
    mlt_producer producer = (mlt_producer)mlt_properties_get_data(properties, kWebVfxProducerPropertyName, NULL);
    mlt_properties producer_props = MLT_PRODUCER_PROPERTIES(producer);
    int size;
    int bpp;
    bool hasTransparency = false;
    {
        MLTWebVfx::ServiceLocker locker(MLT_PRODUCER_SERVICE(producer));
        if (!locker.initialize(*width, *height))
        return 1;

        if (mlt_properties_get_int( producer_props, "transparent") ) {
            *format = mlt_image_rgb24a;
            hasTransparency = true;
        }
        else {
            *format = mlt_image_rgb24;
        }
        // Get bpp from image format
        mlt_image_format_size(*format, 0, 0, &bpp);
        size = *width * *height * bpp;
        *buffer = (uint8_t*)mlt_pool_alloc(size);

        // When not using transparency, this will make the background black...
        memset( *buffer, 255, size );
        WebVfx::Image outputImage(*buffer, *width, *height, size, hasTransparency);
        locker.getManager()->render(&outputImage,
                                    mlt_properties_get_position(properties, kWebVfxPositionPropertyName),
                                    mlt_producer_get_length(producer), hasTransparency);
    }
    mlt_frame_set_image(frame, *buffer, size, mlt_pool_release);
    if (hasTransparency) {
        // Create the alpha channel
        int alpha_size = *width * *height;
        uint8_t *alpha = (uint8_t *)mlt_pool_alloc( alpha_size );
        // Initialise the alpha
        memset( alpha, 255, alpha_size );
        mlt_frame_set_alpha(frame, alpha, alpha_size, mlt_pool_release);
    }
    return error;
}
Mat stretchHistogram(Mat * inputImage)
{
	/* Input image must be grayscale */
	int min = 255;
	int max = 0;
	int val;
	int i, j;

	Mat outputImage(inputImage->rows, inputImage->cols, inputImage->type() );

	
	for (i = 0; i < inputImage->rows; i++)
	{
		for (j = 0; j < inputImage->cols; j++)
		{
			val = inputImage->at<uchar>(i, j);
			if (val > max)
			{
				max = val;
			}
			if (val < min)
			{
				min = val;
			}
		}
	}

	
	for (i = 0; i < inputImage->rows; i++)
	{
		for (j = 0; j < inputImage->cols; j++)
		{
			val = inputImage->at<uchar>(i, j);
			outputImage.at<uchar>(i, j) = (uchar)((((double)val - min) / ((double)max - min)) * max);
		}
	}

	return outputImage;
}
Beispiel #6
0
int main(int argc, char* argv[])
{
	//test();
	//test2();
	//return 0;

	//setup the scene
	printf("Setup...\n");
	setupScene();

	//render stuff
	printf("Begin Render\n");
#ifdef __linux__
	struct timeval start, end;
	gettimeofday(&start, NULL);
#endif
	render();
#ifdef __linux__
	gettimeofday(&end, NULL);
	long seconds = end.tv_sec - start.tv_sec;
	long useconds = end.tv_usec - start.tv_usec;
	long mtime = static_cast<long>((seconds * 1000 + useconds / 1000.0f) + 0.5f);
	printf("Render Complete, Time Taken: %ld ms\n", mtime);
#else
	printf("Render Complete\n");
#endif

	//output the render result
	printf("Writing Image\n");
	outputImage();

	//cleanup everything
	printf("Cleanup\n");
	cleanupScene();


	return 0;
}
void SpotLightFallOFFIntensityCalculator::GetLightFallOffPointsfromCorePoints_UsingGradientEstimation(const Array2D<Rgba>& inputImage_, const Point2D<int>& corePoint_) {
 
    int imageHeight = (int)inputImage_.height();
    int imageWidth  = (int)inputImage_.width();
    
    UtilityClass* util = new UtilityClass();
    Rgba* outputPixels = util->GetImagePixelsToWrite(imageWidth, imageHeight);
    Array2D<Rgba> outputImage(imageHeight,imageWidth);
    Array2D<Rgba> outputImage1(imageHeight,imageWidth);
    
    ImageFilterFactoryClass* imageFilterFactoryClass = new ImageFilterFactoryClass();
    ImageFilterClass* imageFilterClass = imageFilterFactoryClass->GetImageFilterClass(inputImage_, 5, FILTERTYPE::GAUSSIAN);
    imageFilterClass->ProcessImage(inputImage_, outputImage);
    
    imageFilterClass = imageFilterFactoryClass->GetImageFilterClass(outputImage, 1, FILTERTYPE::SOBEL);
    imageFilterClass->ProcessImage(outputImage,outputImage1);
    
//    imageFilterClass = imageFilterFactoryClass->GetImageFilterClass(inputImage_, 2, FILTERTYPE::GAUSSIAN);
//    imageFilterClass->ProcessImage(outputImage1, outputImage);
//    
//    imageFilterClass = imageFilterFactoryClass->GetImageFilterClass(outputImage, 1, FILTERTYPE::SOBEL);
//    imageFilterClass->ProcessImage(outputImage,outputImage1);
    
    for (int row = 0; row < (imageHeight); ++row) {
        for (int col = 0; col < (imageWidth); ++col) {
            int i = row * imageWidth + col;
            outputPixels[i] = outputImage1[row][col];
        }
    }
    
    util->WriteImage2DArrayPixels("../../Output/LOG1.exr", outputPixels, imageWidth, imageHeight);
    
    delete util;
    delete imageFilterFactoryClass;
   
}
Beispiel #8
0
int main() {

	char algorithm[5] = { '\0' }, imageFilename[128] = { '\0' };
	int quanta = 0, tempBurst = 0, procNum = 0, readTemp = 0, tempStart = 0, 
		totalTime = 0, lastStart = 0;
	bool goodRead = true;
	tProcess processes[64];
	int * timeLine = NULL;

	initialiseProcesses(processes);

	printf("Welcome to Job Scheduler Computer\nEnter a filename for the output ");
	printf("image:\n");
	scanf("%s", imageFilename);

	printf("What algorithm would you like to use?\n");
	scanf("%s", algorithm);

	if (strcmp(algorithm, "RR") == 0) {
		printf("What is the time quanta for RR scheduling?\n");
		scanf("%d", &quanta);
	}

	while (goodRead && procNum < 64) {
		printf("Process %d (P%d) - What is the burst time & start time?\n", 
			procNum + 1, procNum + 1);
		readTemp = scanf("%d %d", &tempBurst, &tempStart);
		if (readTemp > 0 && tempStart <= totalTime && tempStart >= lastStart) {
			processes[procNum].burstTime = tempBurst;
			processes[procNum].remainingTime = tempBurst;
			processes[procNum].startTime = tempStart;
			totalTime += tempBurst;
			lastStart = tempStart;
			++procNum;
		}
		else if (tempStart > totalTime || tempStart< lastStart) {
			printf("ERROR: The start time cannot be greater than the sum of all ");
			printf("previous burst times and it must be at least equal to the last");
			printf("process start time.\nPlease try again.\n\n");
		}
		else
			goodRead = false;
	}

	if (strcmp(algorithm, "RR") == 0) {
		timeLine = rrSim2(processes, procNum, quanta);
	}
	else if (strcmp(algorithm, "FCFS") == 0) {
		timeLine = fcfsSim2(processes, procNum);
	}
	else if (strcmp(algorithm, "SJF") == 0) {
		timeLine = sjfSim2(processes, procNum);
	}
	else if (strcmp(algorithm, "SRT") == 0) {
		timeLine = srtSim2(processes, procNum);
	}
	else {
		printf("%s is not an available option. Program will now quit.", algorithm);
	}

	outputImage(timeLine, procNum, imageFilename);

	free(timeLine);

	return 0;
}
Beispiel #9
0
void runCuda(){

  // Map OpenGL buffer object for writing from CUDA on a single GPU
  // No data is moved (Win & Linux). When mapped to CUDA, OpenGL should not use this buffer
  float curtime;

  if(iterations<renderCam->iterations){
    uchar4 *dptr=NULL;
    iterations++;
    cudaGLMapBufferObject((void**)&dptr, pbo);
  
    //pack geom and material arrays
    geom* geoms = new geom[renderScene->objects.size()];
    material* materials = new material[renderScene->materials.size()];
    
    for(int i=0; i<renderScene->objects.size(); i++){
      geoms[i] = renderScene->objects[i];
    }
    for(int i=0; i<renderScene->materials.size(); i++){
      materials[i] = renderScene->materials[i];
    }
    
    curtime =  glutGet( GLUT_ELAPSED_TIME )/250.0f;
    average_time += (curtime - prev_time)/4.0f;
    prev_time = curtime;
    printf( "average_time: %f \n", average_time/iterations ); 
    //cudaRaytraceCore(dptr, renderCam, targetFrame, iterations, materials, renderScene->materials.size(), geoms, renderScene->objects.size() );
    cudaRaytraceCore(dptr, renderCam, targetFrame, iterations, curtime, materials, renderScene->materials.size(), geoms, renderScene->objects.size() );
    
    // unmap buffer object
    cudaGLUnmapBufferObject(pbo);
  }else{

    if(!finishedRender){
      //output image file
      image outputImage(renderCam->resolution.x, renderCam->resolution.y);

      for(int x=0; x<renderCam->resolution.x; x++){
        for(int y=0; y<renderCam->resolution.y; y++){
          int index = x + (y * renderCam->resolution.x);
          outputImage.writePixelRGB(renderCam->resolution.x-1-x,y,renderCam->image[index]);
        }
      }
      
      gammaSettings gamma;
      gamma.applyGamma = true;
      gamma.gamma = 1.0;
      gamma.divisor = renderCam->iterations;
      outputImage.setGammaSettings(gamma);
      string filename = renderCam->imageName;
      string s;
      stringstream out;
      out << targetFrame;
      s = out.str();
      utilityCore::replaceString(filename, ".bmp", "."+s+".bmp");
      utilityCore::replaceString(filename, ".png", "."+s+".png");
      outputImage.saveImageRGB(filename);
      cout << "Saved frame " << s << " to " << filename << endl;
      finishedRender = true;
      if(singleFrameMode==true){
        cudaDeviceReset(); 
        exit(0);
      }
    }
    if(targetFrame<renderCam->frames-1){

      //clear image buffer and move onto next frame
      targetFrame++;
      iterations = 0;
      for(int i=0; i<renderCam->resolution.x*renderCam->resolution.y; i++){
        renderCam->image[i] = glm::vec3(0,0,0);
      }
      cudaDeviceReset(); 
      finishedRender = false;
    }
  }
  
}
Beispiel #10
0
void createClip(int i, QString name)
{
	QImage outputImage( nWidth, nHeight, QImage::Format_RGB32);
	
	int nRad = 30;
	
	int X = randInt(nRad,nWidth-nRad);
	int Y = randInt(nRad,nHeight-nRad);

	QRectF rectangle(X - nRad, Y - nRad, nRad*2, nRad*2);
	
	QString number = QString::number(i);
	
	while(number.count() < 6)
		number = "0" + number;
		
	
	QPainter p(&outputImage);
	{
		QBrush brush( Qt::black, Qt::SolidPattern);
		QPen pen(Qt::black);
		p.setPen(pen);
		p.setBrush(brush);
		p.drawRect(0,0,outputImage.width(),outputImage.height());
	}
	
	/*{
		QBrush brush( Qt::red, Qt::SolidPattern);
		QPen pen(Qt::white);
		p.setPen(pen);
		p.setBrush(brush);
		p.drawEllipse(rectangle);
	}*/

	{
		
		// draw caption
		
		QString mtr = genNewMatrix();
		QFontMetrics fontMetrics(QFont(fontname, nSizeFont));
 		QRect rectText = fontMetrics.boundingRect(name);
 		
		p.setPen(QPen(Qt::white));
		p.setFont(QFont(fontname, nSizeFont));
		// QRect rect(0, outputImage.height() - rectText.height(), outputImage.width(), rectText.height());
		QRect rect(0, 0, outputImage.width(), outputImage.height());
		p.drawText(rect, Qt::AlignLeft, mtr);
		// p.drawRect(0,0,outputImage.width(),outputImage.height());
		
		// 
		
		
		QRect rect2((outputImage.width() - rectText.width())/2 - 30, (outputImage.height() - rectText.height()-20)/2, rectText.width() + 30, rectText.height() + 20);
		p.drawRect(rect2);
		p.drawText(rect2, Qt::AlignCenter, name);
		p.end();
	}
	

	outputImage.save("images/clip-"+number+".png");	
}
QImage Utils::applyHomography(MatrixXd H, QImage inputImage, QList<Dot*> region)
{
    MatrixXd x(3,1);
    MatrixXd y(3,1);
    vector<double> x_values;
    vector<double> y_values;

    int height_output = 454;
    int width_output = 604;

    // Calculate output image corners
    x << region.at(0)->x(), region.at(0)->y(), 1;
    y = H*x;
    x_values.push_back(y(0,0)/y(2,0));
    y_values.push_back(y(1,0)/y(2,0));

    x << region.at(1)->x(), region.at(1)->y(), 1;
    y = H*x;
    x_values.push_back(y(0,0)/y(2,0));
    y_values.push_back(y(1,0)/y(2,0));

    x << region.at(2)->x(), region.at(2)->y(), 1;
    y = H*x;
    x_values.push_back(y(0,0)/y(2,0));
    y_values.push_back(y(1,0)/y(2,0));

    x << region.at(3)->x(), region.at(3)->y(), 1;
    y = H*x;
    x_values.push_back(y(0,0)/y(2,0));
    y_values.push_back(y(1,0)/y(2,0));

    double max_x = (*max_element(x_values.begin(), x_values.end()));
    double min_x = (*min_element(x_values.begin(), x_values.end()));
    double max_y = (*max_element(y_values.begin(), y_values.end()));
    double min_y = (*min_element(y_values.begin(), y_values.end()));
    height_output = width_output / ((max_x-min_x)/(max_y-min_y));

    QImage outputImage(width_output, height_output, QImage::Format_ARGB32);
    QPainter painter;
    painter.begin(&outputImage);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBackgroundMode(Qt::TransparentMode);
    QPen pen;

    H = H.inverse().eval();

    double step = (max_x - min_x) / width_output;

    for (int i=0; i < height_output; i++)
    {
        for (int j=0; j<width_output; j++)
        {
            x << min_x+j*step, min_y+i*step, 1;
            y = H*x;

            y << y(0,0)/y(2,0), y(1,0)/y(2,0), 1;

            if (y(0,0) >= 0 && y(0,0) <= inputImage.width() - 1
                    && y(1,0) >= 0 && y(1,0) <= inputImage.height() - 1)
            {
                // Point lies inside the input Image

                // Do interpolation
                QColor c = interpolate(inputImage, y);
                //QRgb clrCurrent( inputImage.pixel( y(0,0), y(1,0) ) );
                pen.setColor(c);
                pen.setWidth(1);
                pen.setCapStyle(Qt::RoundCap);
                painter.setPen(pen);
                painter.drawPoint(j, i);

            }
            else
            {
                // Point lies outside the input Image
                QColor clrCurrent(0,0,0);
                pen.setColor(clrCurrent);
                pen.setWidth(1);
                pen.setCapStyle(Qt::RoundCap);
                painter.setPen(pen);
                painter.drawPoint(j, i);
            }
        }
    }
    painter.end();
    return outputImage;
}
void IconsGenerator::doConvertIcon(const IconToGenerate& icon)
{
	// Loading the svg file. Printing a message in case of errors
	QSvgRenderer svgSource(icon.sourceSvg);
	if (!svgSource.isValid()) {
		qDebug() << "Invalid svg image" << icon.sourceSvg;
		emit iconGenerated(icon.index, QString());

		return;
	}

	// Computing the output dimension
	int outputWidth = 0;
	int outputHeight = 0;
	const QSize inputSize = svgSource.defaultSize();
	if (icon.s == SpecifiedDimension::Width) {
		outputWidth = icon.iconDim;
		outputHeight = int((double(inputSize.height()) / double(inputSize.width())) * double(outputWidth));
	} else if (icon.s == SpecifiedDimension::Height) {
		outputHeight = icon.iconDim;
		outputWidth = int((double(inputSize.width()) / double(inputSize.height())) * double(outputHeight));
	} else {
		// We should really never get here...
		qDebug() << "INTERNAL ERROR: invalid specified dimension";
		emit iconGenerated(icon.index, QString());

		return;
	}

	// Generating the output filename
	const QString outputFilename = QString("%1/%2-%3-%4x%5.png")
			.arg(m_outputPath)
			.arg(QFileInfo(icon.sourceSvg).baseName())
			.arg(icon.index)
			.arg(outputWidth)
			.arg(outputHeight);

	// Checking that the icon doesn't already exist
	if (QFileInfo(outputFilename).exists()) {
		// Emitting the signal for the existing image and returning
		emit iconGenerated(icon.index, outputFilename);

		return;
	}

	// Creating the image and the painter to draw the image
	QImage outputImage(outputWidth, outputHeight, QImage::Format_ARGB32);
	outputImage.fill(Qt::transparent);
	QPainter painter(&outputImage);
	painter.setRenderHint(QPainter::Antialiasing, true);

	// Generating the image and saving it. Printing a message in case of errors
	svgSource.render(&painter);
	painter.end();
	if (!outputImage.save(outputFilename, nullptr, 100)) {
		qDebug() << "Could not save png icon" << outputFilename;
		emit iconGenerated(icon.index, QString());

		return;
	}

	// Emitting the signal
	emit iconGenerated(icon.index, outputFilename);
}
Beispiel #13
0
// name   : detect function
// input  : image and dataset
// output : classification result and detect picture
CDetectionResult CRForest::detection(CTestDataset &testSet) const {
    int classNum = classDatabase.vNode.size();//contain class number
    std::vector<CTestPatch> testPatch;
    std::vector<const LeafNode*> result;

    //std::vector<const LeafNode*> storedLN(0);
    //std::vector<std::vector<CParamset> > cluster(0);
    //std::vector<CParamset> clusterMean(0);

    cv::vector<cv::Mat> outputImage(classNum);
    cv::vector<cv::Mat> voteImage(classNum);//voteImage(classNum);
    //cv::vector<cv::Mat_<std::vector<CParamset> > > voteParam(classNum);

    std::vector<int> totalVote(classNum,0);

    //boost::timer t;

    //boost::timer::auto_cpu_timer t;
    //boost::timer::nanosecond_type time;

    std::vector<paramHist**> voteParam2(classNum);

    //timer.start();

    testSet.loadImage(conf);

    testSet.extractFeatures(conf);

    //std::cout << "extracted feature " << t.elapsed() << " sec" << std::endl;

    //testSet.releaseImage();

    //t.restart()
    // image row and col
    int imgRow = testSet.img.at(0)->rows;
    int imgCol = testSet.img.at(0)->cols;

    #pragma omp parallel
    {
        #pragma omp for
        for(int i = 0; i < classNum; ++i) {
            outputImage.at(i) = testSet.img.at(0)->clone();
            voteImage.at(i) = cv::Mat::zeros(imgRow,imgCol,CV_32FC1);
            voteParam2.at(i) = new paramHist*[imgRow];
            for(int j = 0; j < imgRow; ++j)
                voteParam2.at(i)[j] = new paramHist[imgCol];
        }
    }

    //paramHist voteParam[testSet.img.at(0)->rows][testSet.img.at(0)->cols][classNum];
    // extract feature from test image
    //features.clear();
    //extractFeatureChannels(image.at(0), features);
    // add depth image to features
    //features.push_back(image.at(1));
    // extract patches from features

    extractTestPatches(testSet,testPatch,this->conf);

    //std::cout << "extracted feature " << t.elapsed() << " sec" << std::endl;

    std::cout << "patch num: " << testPatch.size() << std::endl;
    std::cout << "detecting..." << std::endl;
    // regression and vote for every patch

    std::cout << "class num = " << classNum << std::endl;

    for(int j = 0; j < testPatch.size(); ++j) {
        // regression current patch
        result.clear();
        this->regression(result, testPatch.at(j));

        // for each tree leaf
        for(int m = 0; m < result.size(); ++m) {
            #pragma omp parallel
            {
                #pragma omp for

                for(int l = 0; l < result.at(m)->pfg.size(); ++l) {
                    if(result.at(m)->pfg.at(l) > 0.9) {
                        int cl = classDatabase.search(result.at(m)->param.at(l).at(0).getClassName());

                        for(int n = 0; n < result.at(m)->param.at(cl).size(); ++n) {
                            cv::Point patchSize(conf.p_height/2,conf.p_width/2);

                            cv::Point rPoint = result.at(m)->param.at(cl).at(n).getCenterPoint();

                            if(conf.learningMode != 2) {
                                cv::Mat tempDepth = *testPatch[j].getDepth();
                                cv::Rect tempRect = testPatch[j].getRoi();
                                cv::Mat realDepth = tempDepth(tempRect);
                                double centerDepth = realDepth.at<ushort>(tempRect.height / 2 + 1, tempRect.width / 2 + 1) + conf.mindist;

                                rPoint *= centerDepth;
                                rPoint.x /= 1000;
                                rPoint.y /= 1000;


                            }

                            cv::Point pos(testPatch.at(j).getRoi().x + patchSize.x +  rPoint.x,
                                          testPatch.at(j).getRoi().y + patchSize.y +  rPoint.y);
                            // vote to result image
                            if(pos.x > 0 && pos.y > 0 && pos.x < voteImage.at(cl).cols && pos.y < voteImage.at(cl).rows) {
                                double v = result.at(m)->pfg.at(cl) / ( result.size() * result.at(m)->param.at(l).size());
                                voteImage.at(cl).at<float>(pos.y,pos.x) += v;//(result.at(m)->pfg.at(c) - 0.9);// * 100;//weight * 500;
                                voteParam2.at(cl)[pos.y][pos.x].roll.at<double>(0,result.at(m)->param.at(l).at(n).getAngle()[0]) += v * 10000;
                                voteParam2.at(cl)[pos.y][pos.x].pitch.at<double>(0,result.at(m)->param.at(l).at(n).getAngle()[1]) += v * 10000;
                                voteParam2.at(cl)[pos.y][pos.x].yaw.at<double>(0,result.at(m)->param.at(l).at(n).getAngle()[2]) += v * 10000;
                                //std::cout << result.at(m)->param.at(l).at(n).getAngle() << std::endl;
                                //std::cout << v << std::endl;
                                totalVote.at(cl) += 1;
                            }

                        } //for(int n = 0; n < result.at(m)->param.at(cl).size(); ++n){
                    } //if(result.at(m)->pfg.at(l) > 0.9){
                } //for(int l = 0; l < result.at(m)->pfg.size(); ++l){

            }//pragma omp parallel

        } // for every leaf
    } // for every patch

    // vote end

    #pragma omp parallel
    {
        #pragma omp for
        // find balance by mean shift
        for(int i = 0; i < classNum; ++i) {
            cv::GaussianBlur(voteImage.at(i),voteImage.at(i), cv::Size(21,21),0);
        }
    }

    // measure time
    //    double time = t.elapsed();
    //    std::cout << time << "sec" << std::endl;
    //    std::cout << 1 / (time) << "Hz" << std::endl;

    // output image to file
    std::string opath;
    //    if(!conf.demoMode){
    //        //create result directory
    //        opath = testSet.getRgbImagePath();
    //        opath.erase(opath.find_last_of(PATH_SEP));
    //        std::string imageFilename = testSet.getRgbImagePath();
    //        imageFilename.erase(imageFilename.find_last_of("."));
    //        //imageFilename.erase(imageFilename.begin(),imageFilename.find_last_of(PATH_SEP));
    //        imageFilename = imageFilename.substr(imageFilename.rfind(PATH_SEP),imageFilename.length());

    //        //opath += PATH_SEP;
    //        opath += imageFilename;
    //        std::string execstr = "mkdir -p ";
    //        execstr += opath;
    //        system( execstr.c_str() );

    //        for(int c = 0; c < classNum; ++c){
    //            std::stringstream cToString;
    //            cToString << c;
    //            std::string outputName = "output" + cToString.str() + ".png";
    //            std::string outputName2 = opath + PATH_SEP + "vote_" + classDatabase.vNode.at(c).name + ".png";
    //            //cv::imwrite(outputName.c_str(),outputImage.at(c));
    //            //cv::cvtColor(voteImage)

    //            cv::Mat writeImage;
    //            //hist.convertTo(hist, hist.type(), 200 * 1.0/second_val,0);
    //            voteImage.at(c).convertTo(writeImage, CV_8UC1, 254);
    //            cv::imwrite(outputName2.c_str(),writeImage);
    //        }
    //    }

    // create detection result
    CDetectionResult detectResult;
    detectResult.voteImage = voteImage;

    // show ground truth
    std::cout << "show ground truth" << std::endl;
    //    std::cout << dataSet.className.size() << std::endl;
    //    std::cout << dataSet.centerPoint.size() << std::endl;
    for(int i = 0; i < testSet.param.size(); ++i) {
        testSet.param.at(i).showParam();
    }

    // show detection reslut
    std::cout << "show result" << std::endl;
    // for every class
    for(int c = 0; c < classNum; ++c) {
        double min,max;
        cv::Point minLoc,maxLoc;
        cv::minMaxLoc(voteImage.at(c),&min,&max,&minLoc,&maxLoc);

        double min_pose_value[3], max_pose_value[3];
        cv::Point min_pose[3], max_pose[3];

        paramHist hist;

        for(int x = 0; x < conf.paramRadius; ++x) {
            for(int y = 0; y < conf.paramRadius; ++y) {
                if( maxLoc.x + x < imgCol &&  maxLoc.y + y < imgRow)
                    hist += voteParam2.at(c)[maxLoc.y + y][maxLoc.x + x];
                if(maxLoc.x - x > 0 && maxLoc.y - y > 0)
                    hist += voteParam2.at(c)[maxLoc.y - y][maxLoc.x - x];
            }
        }

        //hist.showHist();

        //        for(int p = 0; p < 360; ++p){
        //            std::cout << p << " " <<  voteParam2.at(c)[maxLoc.y][maxLoc.x].yaw.at<double>(0,p) << std::endl;
        //        }

        //voteParam2.at(c)[maxLoc.y][maxLoc.x].showHist();

        cv::minMaxLoc(hist.roll, &min_pose_value[0], &max_pose_value[0], &min_pose[0], &max_pose[0]);
        cv::minMaxLoc(hist.pitch, &min_pose_value[1], &max_pose_value[1], &min_pose[1], &max_pose[1]);
        cv::minMaxLoc(hist.yaw, &min_pose_value[2], &max_pose_value[2], &min_pose[2], &max_pose[2]);

        // draw detected class bounding box to result image
        // if you whant add condition of detection threshold, add here
        cv::Size tempSize = classDatabase.vNode.at(c).classSize;
        cv::Rect_<int> outRect(maxLoc.x - tempSize.width / 2,maxLoc.y - tempSize.height / 2 , tempSize.width,tempSize.height);
        cv::rectangle(outputImage.at(c),outRect,cv::Scalar(0,0,200),3);
        cv::putText(outputImage.at(c),classDatabase.vNode.at(c).name,cv::Point(outRect.x,outRect.y),cv::FONT_HERSHEY_SIMPLEX,1.2, cv::Scalar(0,0,200), 2, CV_AA);

        // draw grand truth to result image
        if(!conf.demoMode) {
            for(int i = 0; i < testSet.param.size(); ++i) {
                int tempClassNum = classDatabase.search(testSet.param.at(i).getClassName());
                if(tempClassNum != -1) {
                    cv::Size tempSize = classDatabase.vNode.at(tempClassNum).classSize;
                    cv::Rect_<int> outRect(testSet.param.at(i).getCenterPoint().x - tempSize.width / 2,testSet.param.at(i).getCenterPoint().y - tempSize.height / 2 , tempSize.width,tempSize.height);
                    cv::rectangle(outputImage.at(tempClassNum),outRect,cv::Scalar(200,0,0),3);
                    cv::putText(outputImage.at(tempClassNum),classDatabase.vNode.at(c).name,cv::Point(testSet.param.at(i).getCenterPoint().x, testSet.param.at(i).getCenterPoint().y),cv::FONT_HERSHEY_SIMPLEX,1.2, cv::Scalar(200,0,0), 2, CV_AA);
                }
            }
        }

        // show result
        std::cout << c << " Name : " << classDatabase.vNode.at(c).name <<
                  "\tvote : " << totalVote.at(c) <<
                  " Score : " << voteImage.at(c).at<float>(maxLoc.y, maxLoc.x) <<
                  " CenterPoint : " << maxLoc << std::endl <<
                  " Pose : roll " << max_pose[0].x <<
                  " pitch : " << max_pose[1].x <<
                  " yaw : " << max_pose[2].x << std::endl;

        // if not in demo mode, output image to file
        if(!conf.demoMode) {
            std::string outputName = opath + PATH_SEP + "detectionResult" + "_" + classDatabase.vNode.at(c).name + ".png";
            cv::imwrite(outputName.c_str(),outputImage.at(c));
        }

        CDetectedClass detectedClass;
        detectedClass.name = classDatabase.vNode.at(c).name;
        detectedClass.angle[0] = max_pose[0].x;

        // calc euclidean dist to nearest object
        double minError = DBL_MAX;
        std::string nearestObject;
        for(int d = 0; d < testSet.param.size(); ++d) {
            double tempError = euclideanDist(maxLoc,testSet.param.at(d).getCenterPoint());//= std::sqrt(std::pow((double)(maxLoc.x - testSet.param.at(0).getCenterPoint().x), 2) + std::pow((double)(maxLoc.y - testSet.param.at(0).getCenterPoint().y), 2));
            //std::cout << tempError << std::endl;
            if(tempError < minError) {
                minError = tempError;
                nearestObject = testSet.param.at(d).getClassName();
            }
        }

        // calc and output result
        detectedClass.error = minError;
        detectedClass.nearestClass = nearestObject;
        detectedClass.score = voteImage.at(c).at<float>(maxLoc.y, maxLoc.x);
        detectResult.detectedClass.push_back(detectedClass);
    } // for every class

    for(int k = 0; k < classNum; ++k) {
        for(int i = 0; i < imgRow; ++i) {
            delete[] voteParam2.at(k)[i];
        }
    }

    return detectResult;
}
Beispiel #14
0
void runCuda(){

  // Map OpenGL buffer object for writing from CUDA on a single GPU
  // No data is moved (Win & Linux). When mapped to CUDA, OpenGL should not use this buffer
  


  if(iterations<renderCam->iterations){
    uchar4 *dptr=NULL;
    iterations++;
    cudaGLMapBufferObject((void**)&dptr, pbo);
  
    //pack geom and material arrays
    geom* geoms = new geom[renderScene->objects.size()];
    material* materials = new material[renderScene->materials.size()];
    
    for(int i=0; i<renderScene->objects.size(); i++){
      geoms[i] = renderScene->objects[i];
    }
    for(int i=0; i<renderScene->materials.size(); i++){
      materials[i] = renderScene->materials[i];
    }
    
  
    // execute the kernel
    cudaRaytraceCore(dptr, renderCam, parameterSet, targetFrame, iterations, materials, renderScene->materials.size(), geoms, renderScene->objects.size(),textures,renderScene->bmps.size());
    
    // unmap buffer object
    cudaGLUnmapBufferObject(pbo);

	if(iterations%1000==0)
	{
		long end=clock();
		printf("time usage for %d iterations: %d milliseconds.\n",iterations,(end-starttime));
	}

  }else{

    if(!finishedRender){
      //output image file
      image outputImage(renderCam->resolution.x, renderCam->resolution.y);

      for(int x=0; x<renderCam->resolution.x; x++){
        for(int y=0; y<renderCam->resolution.y; y++){
          int index = x + (y * renderCam->resolution.x);
          outputImage.writePixelRGB(renderCam->resolution.x-1-x,y,renderCam->image[index]);
        }
      }
      
      gammaSettings gamma;
      gamma.applyGamma = true;
      gamma.gamma = 1.0/2.2;
      gamma.divisor = renderCam->iterations;
      outputImage.setGammaSettings(gamma);
      string filename = renderCam->imageName;
      string s;
      stringstream out;
      out << targetFrame;
      s = out.str();
      utilityCore::replaceString(filename, ".bmp", "."+s+".bmp");
      utilityCore::replaceString(filename, ".png", "."+s+".png");
      outputImage.saveImageRGB(filename);
      cout << "Saved frame " << s << " to " << filename << endl;
      finishedRender = true;
      if(singleFrameMode==true){
        cudaDeviceReset(); 
        exit(0);
      }
    }
    if(targetFrame<renderCam->frames-1){

      //clear image buffer and move onto next frame
      targetFrame++;
      iterations = 0;
      for(int i=0; i<renderCam->resolution.x*renderCam->resolution.y; i++){
        renderCam->image[i] = glm::vec3(0,0,0);
		renderCam->shadowVal[i] = glm::vec3(0,0,0);
      }
      cudaDeviceReset(); 
      finishedRender = false;
    }


  }
  
}
	void saveImage(Glip::CoreGL::HdlTexture& texture, const std::string& filename)
	{
		const Glip::CoreGL::HdlTextureFormatDescriptor& descriptor = texture.getFormatDescriptor();
		const GLenum depth = texture.getGLDepth();

		const int bpp = descriptor.getPixelSizeInBits(texture.getGLDepth());

		// Determine the type of the output image : 
		FREE_IMAGE_TYPE fipType = FIT_UNKNOWN;

		if((depth==GL_BYTE || depth==GL_UNSIGNED_BYTE) && descriptor.numChannels>=1 && descriptor.numChannels<=4)
			fipType = FIT_BITMAP;
		if(depth==GL_SHORT && descriptor.numChannels==1)
			fipType = FIT_INT16;
		else if(depth==GL_UNSIGNED_SHORT && descriptor.numChannels==1)
			fipType = FIT_UINT16;
		else if((depth==GL_SHORT || depth==GL_UNSIGNED_SHORT) && descriptor.numChannels==3)
			fipType = FIT_RGB16;
		else if((depth==GL_SHORT || depth==GL_UNSIGNED_SHORT) && descriptor.numChannels==4)
			fipType = FIT_RGBA16;
		else if((depth==GL_INT || depth==GL_UNSIGNED_INT) && descriptor.numChannels==1)
			fipType = FIT_INT32;
		else if(depth==GL_FLOAT && descriptor.numChannels==1)
			fipType = FIT_FLOAT;
		else if(depth==GL_FLOAT && descriptor.numChannels==3)
			fipType = FIT_RGBF;
		else if(depth==GL_FLOAT && descriptor.numChannels==4)
			fipType = FIT_RGBAF;

		if(fipType==FIT_UNKNOWN)
			throw Glip::Exception("Could not save image to \"" + filename + "\", format is incompatible with FreeImage interface (" + Glip::toString(descriptor.numChannels) + " channels, " + Glip::getGLEnumName(depth) + " depth, " + Glip::toString(bpp) + " bits per pixel.)", __FILE__, __LINE__, Glip::Exception::ClientException);

		fipImage outputImage(fipType, texture.getWidth(), texture.getHeight(), bpp);
		
		if(!outputImage.isValid())
			throw Glip::Exception("Could not save image to \"" + filename + "\", format is incompatible.", __FILE__, __LINE__, Glip::Exception::ClientException);

		GLenum 	fipMode	= GL_NONE;

		// Flip the channels : 
		switch(texture.getGLMode())
		{
			case GL_RED:
				fipMode = GL_RED;
				break;
			case GL_LUMINANCE:
				fipMode = GL_LUMINANCE;
				break;
			case GL_RGB:
				fipMode = GL_BGR;
				break;
			case GL_RGBA:
				fipMode = GL_BGRA;
				break;
			default : 
				throw Glip::Exception("[INTERNAL ERROR] Cannot swap channels for type : " + Glip::CoreGL::getGLEnumName(texture.getGLMode()) + ".", __FILE__, __LINE__, Glip::Exception::ClientException);
		}

		texture.read(outputImage.accessPixels(), fipMode, GL_ZERO, 4);

		// Save : 
		bool test = outputImage.save(filename.c_str());

		if(!test)
			throw Glip::Exception("Could not save image to \"" + filename + "\".", __FILE__, __LINE__, Glip::Exception::ClientException);
	}
void runCuda(){

  // Map OpenGL buffer object for writing from CUDA on a single GPU
  // No data is moved (Win & Linux). When mapped to CUDA, OpenGL should not use this buffer
  
  if((unsigned int)iterations < renderCam->iterations){
    uchar4 *dptr=NULL;
    ++iterations;
    cudaGLMapBufferObject((void**)&dptr, pbo);
  
    //pack geom and material arrays
	unsigned int objectsSize = renderScene->objects.size(), materialsSize = renderScene->materials.size(), lightsSize = renderScene->lights.size();
    geom* geoms = new geom[objectsSize];
    material* materials = new material[materialsSize];
	light* lights = new light[lightsSize];

    
    for(unsigned int i=0; i< objectsSize; ++i){
      geoms[i] = renderScene->objects[i];
    }
    for(unsigned int i=0; i< materialsSize; ++i){
      materials[i] = renderScene->materials[i];
    }
	for(unsigned int i=0; i< lightsSize; ++i){
      lights[i] = renderScene->lights[i];
    }
    
  
    // execute the kernel
    cudaRaytraceCore(dptr, renderCam, targetFrame, iterations, materials, materialsSize, geoms, objectsSize, lights, lightsSize);
    
    // unmap buffer object
    cudaGLUnmapBufferObject(pbo);
  }else{

    if(!finishedRender){
      //output image file
      image outputImage(renderCam->resolution.x, renderCam->resolution.y);

      for(int x=0; x<renderCam->resolution.x; ++x){
        for(int y=0; y<renderCam->resolution.y; ++y){
          int index = x + (y * renderCam->resolution.x);
          outputImage.writePixelRGB(x,y,renderCam->image[index]);
        }
      }
      
      gammaSettings gamma;
      gamma.applyGamma = true;
      gamma.gamma = 1.0/2.2;
      gamma.divisor = renderCam->iterations;
      outputImage.setGammaSettings(gamma);
      string filename = renderCam->imageName;
      string s;
      stringstream out;
      out << targetFrame;
      s = out.str();
      utilityCore::replaceString(filename, ".bmp", "."+s+".bmp");
      utilityCore::replaceString(filename, ".png", "."+s+".png");
      outputImage.saveImageRGB(filename);
      cout << "Saved frame " << s << " to " << filename << endl;
      finishedRender = true;
      if(singleFrameMode==true){
        cudaDeviceReset(); 
        exit(0);
      }
    }
    if(targetFrame < renderCam->frames - 1){

      //clear image buffer and move onto next frame
      ++targetFrame;
      iterations = 0;
      for(int i=0; i<renderCam->resolution.x*renderCam->resolution.y; ++i){
        renderCam->image[i] = glm::vec3(0,0,0);
      }
      cudaDeviceReset(); 
      finishedRender = false;
    }
  }
  
}
Beispiel #17
0
void convertImageFromGray(unsigned char* gray,
                          int width,
                          int height,
                          int dim,
                          float time,
                          FILE* fp_out,
                          bool output_image,
                          bool output_pts,
                          int searchRange)
{
    char bmpFname[100];
    Image outputImage(width, height);
    Tools::Timer timer;
    double dctTime = 0.0;
    double matchTime = 0.0;
    double convTime = 0.0;
    
    int matching;
    unsigned char glyphIndex;
    fprintf(stderr, "converting rgb frame at time %f\n", time);
    sprintf(bmpFname, "image_%0.4f.ppm", time);
    
    if (output_pts)
    {
        // write pts to output stream
        fwrite(&time, sizeof(time), 1, fp_out);
        fprintf(stderr, "output pts!\n");
    }

    for (int y = 0; y < height; y += dim)
    {
        for (int x = 0; x < width; x += dim)
        {
            // copy values into input buffer
            for (int yy = 0; yy < dim; yy ++)
            {
                for (int xx = 0; xx < dim; xx++)
                {
                    dctInput[xx][yy] = gray[(y+yy)*width + (x+xx)];
                }
            }
            
            timer.start();
#ifdef USE_1D_DCT
            dct1WithInput(dctInput, dctOutput, cos1DLookup, dim);
#else
            dctWithInput(dctInput, dctOutput, cosLookup, dim);
#endif
            dctTime += timer.getTime();
            
            timer.start();
            matching = getMatchingGlyph(dctOutput, searchRange);
            matchTime += timer.getTime();
            
            glyphIndex = (unsigned char)matching;
            
            fwrite(&glyphIndex, 1, 1, fp_out);
            
            if (output_image)
            {
                // write to png
                unsigned char *glyphString;
                int glyphPix = dim*dim;
                
                
                if (matching < 128)
                {
                    glyphString = &glyphs[matching * glyphPix];
                }
                else
                {
                    glyphString = &glyphs[(matching - 128)*glyphPix];
                }
                
                int ind;
                ind = 0;
                for (int yy = 0; yy < dim; yy ++)
                {
                    for (int xx = 0; xx < dim; xx++)
                    {
                        Pixel* pixel = outputImage.pixelAt(x+xx, y+yy);
                        
                        if ((glyphString[ind] == '0' && matching < 128) ||
                            (glyphString[ind] == '1' && matching >= 128))
                        {
                            pixel->rgb[0] = 0;
                            pixel->rgb[1] = 0;
                            pixel->rgb[2] = 0;
                        }
                        else
                        {
                            pixel->rgb[0] = 1.0;
                            pixel->rgb[1] = 1.0;
                            pixel->rgb[2] = 1.0;
                        }
                        
                        ind++;
                    }
                }
            }
        }
    }
    if (output_image)
    {
        outputImage.writePPM(bmpFname);
    }
    
    fprintf(stderr, "dct time %lf match time %lf conversion time %lf\n", dctTime, matchTime, convTime);
}
Beispiel #18
0
void ImageSourceThread::run(){

   if (debug) {
      cout << "ImageSourceThread::run: width          " << *widthValue << endl;
      cout << "ImageSourceThread::run: height         " << *heightValue << endl;
      cout << "ImageSourceThread::run: noise          " << *noiseValue << endl;
      cout << "ImageSourceThread::run: window flag    " << *windowValue << endl;
      cout << "ImageSourceThread::run: random flag    " << *randomValue << endl;
      cout << "ImageSourceThread::run: horizontal FoV " << *horizontalViewAngleValue << endl;
      cout << "ImageSourceThread::run: vertical FoV   " << *verticalViewAngleValue << endl;
      cout << "ImageSourceThread::run: xShift         " << *xShiftValue << endl;
      cout << "ImageSourceThread::run: yShift         " << *yShiftValue << endl;
   }


   /* 
    * copy the image data from file, either scale or extract sub-image, and add noise
    */ 

   double noise;
   double azimuth;
   double elevation;
 
   /* generate offsets for sub-image extraction */

   if (*windowValue == 1) {

      windowFlag = true;

      if ( (*widthValue < inputImage.width())  && (*heightValue < inputImage.height()) ) {

         if (*randomValue == 1) {

            // random position of window

            xOffset = (int)((float)(inputImage.width() - *widthValue)*((float)rand() / (float)(RAND_MAX)));
            yOffset = (int)((float)(inputImage.height() - *heightValue)*((float)rand() / (float)(RAND_MAX)));

         }
         else {

            // regular scan pattern: row major order, with x and y increment equal to the xShift and yShift value
            // so that the window scans the complete image (except for borders at the right-hand side and bottom)

            xOffset = xOffset + *xShiftValue;
            if (xOffset > (inputImage.width() - *widthValue)) {
               xOffset = 0;
               yOffset = yOffset + *yShiftValue;
               if (yOffset > (inputImage.height() - *heightValue)) {
                  yOffset = 0;
               }
            }
         }
      }
      else {
         xOffset = 0;
         yOffset = 0;
      }
   }
   else {
      windowFlag = false;
   }

   if (debug) {
      cout << "ImageSourceThread::run: xOffset     " << xOffset << endl;
      cout << "ImageSourceThread::run: yOffset     " << yOffset << endl;
   }
      
   ImageOf<PixelRgb> &outputImage = imagePortOut->prepare();
   outputImage.resize(*widthValue, *heightValue);
      
   for (x=0; x<outputImage.width(); x++) {
      for (y=0; y<outputImage.height(); y++) {
 
         noise = ((float)rand() / (float)(RAND_MAX));          // 0-1
         noise = 2 * (noise - 0.5);                            // -1 - +1
         noise = noise * (*noiseValue);                        // -noiseValue - +noiseValue

         // decide whether to copy directly or extract a sub-image

         if (windowFlag == false) {

            // scale the image
            
            rgbPixel = inputImage((int)(x * ((float)inputImage.width()/(float)outputImage.width())), 
                                  (int)(y * ((float)inputImage.height()/(float)outputImage.height())));
         }
         else {
              
            // extract a sub-image from the original image
            
            rgbPixel = inputImage((int)(x + xOffset), 
                                  (int)(y + yOffset));
         }

         if (((double) rgbPixel.r + noise) < 0)   
            rgbPixel.r = 0; 
         else if (((double) rgbPixel.r + noise) > 255) 
            rgbPixel.r = 255; 
         else 
            rgbPixel.r = (unsigned char) (rgbPixel.r + noise);

         if (((double) rgbPixel.g + noise) < 0)   
            rgbPixel.g = 0; 
         else if (((double) rgbPixel.g + noise) > 255) 
            rgbPixel.g = 255; 
         else 
            rgbPixel.g = (unsigned char) (rgbPixel.g + noise);

         if (((double) rgbPixel.b + noise) < 0)   
            rgbPixel.b = 0; 
         else if (((double) rgbPixel.b + noise) > 255) 
            rgbPixel.b = 255; 
         else 
            rgbPixel.b = (unsigned char) (rgbPixel.b + noise);
           
         outputImage(x,y) = rgbPixel;
      }
   }
   imagePortOut->write();

   /*
    * Now write out the simulated gaze angles
    */

   if (windowFlag == true) {

      azimuth   = ((xOffset * 2.0) - ((double)inputImage.width() - (double)outputImage.width())) * 
                  (*horizontalViewAngleValue /  (2.0 * (double)inputImage.width()));
   
      elevation = ((yOffset * 2.0) - ((double)inputImage.height() - (double)outputImage.height())) * 
                  (*verticalViewAngleValue /  (2.0 * (double)inputImage.height()));

      
      if (debug) {
         cout << "ImageSourceThread::run: azimuth     " << azimuth << endl;
         cout << "ImageSourceThread::run: elevation   " << elevation << endl;
      }

      VectorOf<double> &vctPos = gazePortOut->prepare();
      vctPos.resize(5);
      vctPos(0) = azimuth;
      vctPos(1) = elevation;
      vctPos(2) = (double)(int)'a'; // absolute (neck reference) coordinates are sent
      vctPos(3) = (double)(int)'s'; // receiver module should do saccades
      vctPos(4) = 0; // saccade index

      // write output vector
       
      gazePortOut->write();
   }
           
   /*
    * Now write out the simulated encoder values
    */

   VectorOf<double> &vctEnc = encoderPortOut->prepare();
   vctEnc.resize(6);
   vctEnc(0) = 0;
   vctEnc(1) = 1;
   vctEnc(2) = 2; 
   vctEnc(3) = 3;  
   vctEnc(4) = 4; 
   vctEnc(5) = 5; 

   // write output vector
       
   encoderPortOut->write();
}
bool QgsCompositionChecker::testComposition( QString &report, int page, int pixelDiff )
{
  if ( !mComposition )
  {
    return false;
  }

  setControlName( "expected_" + mTestName );

#if 0
  //fake mode to generate expected image
  //assume 96 dpi and size of the control image 1122 * 794
  QImage newImage( QSize( 1122, 794 ), QImage::Format_ARGB32 );
  mComposition->setPlotStyle( QgsComposition::Print );
  newImage.setDotsPerMeterX( 96 / 25.4 * 1000 );
  newImage.setDotsPerMeterY( 96 / 25.4 * 1000 );
  newImage.fill( 0 );
  QPainter expectedPainter( &newImage );
  //QRectF sourceArea( 0, 0, mComposition->paperWidth(), mComposition->paperHeight() );
  //QRectF targetArea( 0, 0, 3507, 2480 );
  mComposition->renderPage( &expectedPainter, page );
  expectedPainter.end();
  newImage.save( mExpectedImageFile, "PNG" );
  return true;
#endif //0

  //load expected image
  QImage expectedImage( mExpectedImageFile );

  //get width/height, create image and render the composition to it
  int width = expectedImage.width();
  int height = expectedImage.height();
  QImage outputImage( QSize( width, height ), QImage::Format_ARGB32 );

  mComposition->setPlotStyle( QgsComposition::Print );
  outputImage.setDotsPerMeterX( expectedImage.dotsPerMeterX() );
  outputImage.setDotsPerMeterY( expectedImage.dotsPerMeterX() );
  outputImage.fill( 0 );
  QPainter p( &outputImage );
  mComposition->renderPage( &p, page );
  p.end();

  QString renderedFilePath = QDir::tempPath() + QDir::separator() + QFileInfo( mTestName ).baseName() + "_rendered.png";
  outputImage.save( renderedFilePath, "PNG" );

  QString diffFilePath = QDir::tempPath() + QDir::separator() + QFileInfo( mTestName ).baseName() + "_result_diff.png";

  bool testResult = compareImages( mTestName, pixelDiff, renderedFilePath );

  QString myDashMessage = "<DartMeasurementFile name=\"Rendered Image " + mTestName + "\""
                          " type=\"image/png\">" + renderedFilePath +
                          "</DartMeasurementFile>"
                          "<DartMeasurementFile name=\"Expected Image " + mTestName + "\" type=\"image/png\">" +
                          mExpectedImageFile + "</DartMeasurementFile>"
                          "<DartMeasurementFile name=\"Difference Image " + mTestName + "\" type=\"image/png\">" +
                          diffFilePath + "</DartMeasurementFile>";
  qDebug( ) << myDashMessage;

  report += mReport;
  return testResult;
}
Beispiel #20
0
void runCuda(){

  // Map OpenGL buffer object for writing from CUDA on a single GPU
  // No data is moved (Win & Linux). When mapped to CUDA, OpenGL should not use this buffer
  
  if(iterations<renderCam->iterations){
    uchar4 *dptr=NULL;
    iterations++;
    cudaGLMapBufferObject((void**)&dptr, pbo);
  
    //pack geom and material arrays
    geom* geoms = new geom[renderScene->objects.size()];
    material* materials = new material[renderScene->materials.size()];
    map* maps = new map[renderScene->maps.size()];

    for(int i=0; i<renderScene->objects.size(); i++){
      geoms[i] = renderScene->objects[i];
    }
    for(int i=0; i<renderScene->materials.size(); i++){
      materials[i] = renderScene->materials[i];
    }
    
  	for(int i=0; i<renderScene->maps.size(); i++){
      maps[i] = renderScene->maps[i];
    }
    // execute the kernel
	if(!textureMode)
		cudaRaytraceCore(dptr, renderCam, targetFrame, iterations, materials, renderScene->materials.size(),maps,renderScene->maps.size(), geoms, renderScene->objects.size(), mblur,dof);
	else
		cudaRaytraceCoreT(dptr, renderCam, targetFrame, iterations, materials, renderScene->materials.size(),maps,renderScene->maps.size(), geoms, renderScene->objects.size(), mblur,dof);

	// unmap buffer object
    cudaGLUnmapBufferObject(pbo);
  }else{

    if(!finishedRender){
      //output image file
      image outputImage(renderCam->resolution.x, renderCam->resolution.y);
	  image depthImage(renderCam->resolution.x, renderCam->resolution.y);
      for(int x=0; x<renderCam->resolution.x; x++){
        for(int y=0; y<renderCam->resolution.y; y++){
          int index = x + (y * renderCam->resolution.x);
		  glm::vec3 justRGB(renderCam->image[index].x,renderCam->image[index].y,renderCam->image[index].z);
          outputImage.writePixelRGB(renderCam->resolution.x-1-x,y,justRGB);
		  float d = abs(renderCam->image[index].w-renderCam->positions[targetFrame].z)/40.0f;
		  depthImage.writePixelRGB(renderCam->resolution.x-1-x,y,  glm::vec3(d,d,d));
        }
      }
      
      gammaSettings gamma;
      gamma.applyGamma = true;
      gamma.gamma = 1.0/2.2;
      gamma.divisor = renderCam->iterations;
      outputImage.setGammaSettings(gamma);
      string filename = renderCam->imageName;
      string s;
      stringstream out;
      out << targetFrame;
      s = out.str();
      utilityCore::replaceString(filename, ".bmp", "."+s+".bmp");
      utilityCore::replaceString(filename, ".png", "."+s+".png");
      outputImage.saveImageRGB(filename);
	  depthImage.saveImageRGB("depth."+s+".bmp");
      cout << "Saved frame " << s << " to " << filename << endl;
      finishedRender = true;
      if(singleFrameMode==true){
        //cudaDeviceReset(); 
        exit(0);
      }
    }
    if(targetFrame<renderCam->frames-1){

      //clear image buffer and move onto next frame
      targetFrame++;
      iterations = 0;
      for(int i=0; i<renderCam->resolution.x*renderCam->resolution.y; i++){
        renderCam->image[i] = glm::vec4(0,0,0,-1);
      }
      //cudaDeviceReset(); 
      finishedRender = false;
    }
  }
  
}
Beispiel #21
0
void runCuda(){

  // Map OpenGL buffer object for writing from CUDA on a single GPU
  // No data is moved (Win & Linux). When mapped to CUDA, OpenGL should not use this buffer
  
  if(iterations<renderCam->iterations){
    uchar4 *dptr=NULL;
    iterations++;
    cudaGLMapBufferObject((void**)&dptr, pbo);  // hmm pbo is program buffer

	//////////////////////////////////////////  
    ///////pack geom and material arrays//////
	//////////////////////////////////////////

    geom* geoms = new geom[renderScene->objects.size()];
	obj* objs= new obj[renderScene->meshes.size()];
    material* materials = new material[renderScene->materials.size()];
    
    for(unsigned int i=0; i<renderScene->objects.size(); i++)
	{
      geoms[i] = renderScene->objects[i];
    }
	for(unsigned int k=0; k<renderScene->meshes.size(); k++)
	{
		
		objs[k]= renderScene->meshes[k];
		//objs[0].faces
		//cout<<"filling objs\n";
	}
    for(unsigned int j=0; j<renderScene->materials.size(); j++){
      materials[j] = renderScene->materials[j];
    }

	/////////////////////////////////////
	////////// Mesh Loading /////////////
	/////////////////////////////////////
	int number_of_faces;
	triangle* tri_faces;
	if (renderScene->meshes.size() >0)
	{
		vbo = renderScene->meshes[0].getVBO();
		vbosize = renderScene->meshes[0].getVBOsize();

		nbo = renderScene->meshes[0].getNBO();
		nbosize= renderScene->meshes[0].getNBOsize();	

		float newcbo[] = {0.0, 1.0, 0.0, 
						0.0, 0.0, 1.0, 
						1.0, 0.0, 0.0};
		cbo = newcbo;
		cbosize = 9;

		ibo = renderScene->meshes[0].getIBO();
		ibosize = renderScene->meshes[0].getIBOsize();

		vector<vector<int>>* temp_faces= renderScene->meshes[0].getFaces();
		//hack
		number_of_faces=ibosize/3;
		tri_faces= new triangle[number_of_faces];

		/*for(int i=0;i<108;i++)
		{
			cout<<vbo[i]<<"   \n";
			if((i+1)%3==0)
			{
				cout<<"\n";
			}
		}*/

		for( int i=0 ; i <number_of_faces ; i++)
		{
			// here P0 has the vertex index of 1 vertex of triangle
			tri_faces[i].p0=glm::vec3(vbo[i*9],vbo[i*9 +1 ],vbo[i*9 +2]);
			tri_faces[i].p1=glm::vec3(vbo[i*9 +3],vbo[i*9 +4],vbo[i*9 +5]);
			tri_faces[i].p2=glm::vec3(vbo[i*9 + 6],vbo[i*9 + 7],vbo[i*9 + 8]);


			tri_faces[i].n0=glm::vec3(nbo[i*9],    nbo[i*9 +1 ],nbo[i*9 +2]);
			tri_faces[i].n1=glm::vec3(nbo[i*9 +3], nbo[i*9 +4], nbo[i*9 +5]);
			tri_faces[i].n2=glm::vec3(nbo[i*9 + 6],nbo[i*9 + 7],nbo[i*9 + 8]);


			////// NOTE This line is hacky, just to save the normal

			tri_faces[i].n0=glm::normalize(tri_faces[i].n0+tri_faces[i].n1+tri_faces[i].n2);


			//tri_faces[i].p0 = glm::vec3(vbo[3*temp_faces[0][i][0]],vbo[3*temp_faces[0][i][0] + 1],vbo[3*(temp_faces[0][i][0]) + 2]);
			//tri_faces[i].p1 = glm::vec3(vbo[3*temp_faces[0][i][1]],vbo[3*temp_faces[0][i][1] + 1],vbo[3*(temp_faces[0][i][1]) + 2]);
			//tri_faces[i].p2 = glm::vec3(vbo[3*temp_faces[0][i][2]],vbo[3*temp_faces[0][i][2] + 1],vbo[3*(temp_faces[0][i][2]) + 2]);
			//cout<"ok";
			//tri_faces[i].p0= vbo[i*tri_faces[i].p0.x, i*tri_faces[i].p0.y,i*tri_faces[i].p0.z];
		}
	
		//vbo[temp_faces[0][0][0]
		/*for( int i=0 ; i <number_of_faces ; i++)
		{
		cout<<tri_faces[i].p0.x<<"	\n";
		cout<<tri_faces[i].p1.x<<"	\n";
		cout<<tri_faces[i].p2.x<<"	\n";
		}*/
	}

	//cout<<renderCam->fov.x<<"fov"<<endl;
	
	// you dont have to do this everytime. think about it
	
	float xDirection = sin(renderCam->yaw) * cos(renderCam->pitch);
	float yDirection = sin(renderCam->pitch);
	float zDirection = cos(renderCam->yaw) * cos(renderCam->pitch);
	glm::vec3 directionToCamera = glm::vec3(xDirection, yDirection, zDirection);
	glm::vec3 viewDirection = -directionToCamera;
	glm::vec3 eyePosition = renderCam->centerPosition + directionToCamera * renderCam->radius;
	renderCam->positions[0]= glm::vec3(eyePosition.x,eyePosition.y,eyePosition.z);
	
	
	// execute the kernel
    cudaRaytraceCore(dptr, renderCam, targetFrame, iterations, materials,
		renderScene->materials.size(), geoms, renderScene->objects.size(),
		vbo,nbo,cbo,vbosize,nbosize,cbosize,objs, renderScene->meshes.size(), number_of_faces, tri_faces,
		ibo,ibosize);
    
    // unmap buffer object
	
    cudaGLUnmapBufferObject(pbo);
  }
else{

    if(!finishedRender){
      //output image file
      image outputImage(renderCam->resolution.x, renderCam->resolution.y);

      for(int x=0; x<renderCam->resolution.x; x++){
        for(int y=0; y<renderCam->resolution.y; y++){
          int index = x + (y * renderCam->resolution.x);
          outputImage.writePixelRGB(x,y,renderCam->image[index]);
        }
      }
      
      gammaSettings gamma;
      gamma.applyGamma = true;
      gamma.gamma = 1.0/2.2;
      gamma.divisor = renderCam->iterations;
      outputImage.setGammaSettings(gamma);
      string filename = renderCam->imageName;
      string s;
      stringstream out;
      out << targetFrame;
      s = out.str();
      utilityCore::replaceString(filename, ".bmp", "."+s+".bmp");
      utilityCore::replaceString(filename, ".png", "."+s+".png");
      outputImage.saveImageRGB(filename);
      cout << "Saved frame " << s << " to " << filename << endl;
      finishedRender = true;
      if(singleFrameMode==true){
        cudaDeviceReset(); 
        exit(0);
      }
    }
    if(targetFrame<renderCam->frames-1){

      //clear image buffer and move onto next frame
      targetFrame++;
      iterations = 0;
      for(int i=0; i<renderCam->resolution.x*renderCam->resolution.y; i++){
        renderCam->image[i] = glm::vec3(0,0,0);
      }
      cudaDeviceReset();
	  //deleteImage(image);
      finishedRender = false;
    }
  }
}