Ejemplo n.º 1
0
	inline auto convolution(
		MatrixBase< DerivedM > const& m,
		MatrixBase< DerivedKC > const& vc,
		MatrixBase< DerivedKR > const& vr
	){
		return convolution(convolution(m, vr), vc);
	}
Ejemplo n.º 2
0
Archivo: main.c Proyecto: jlin705/18645
int main (int argc, char * argv[]){
    char * path = "/Users/neo_cupid/Desktop/18645/final_proj/data-2/1/input0.ppm";
    char * path_csv = "/Users/neo_cupid/Desktop/18645/final_proj/data-2/1/input1.csv";
    char * path_out = "/Users/neo_cupid/Desktop/18645/final_proj/data-2/1/outTest.ppm";
    clock_t begin, end;
    double time_spent;
    
    begin = clock();
    
    PPM_IMG img = read_ppm (path);
    PPM_IMG output;
    output.h = img.h;
    output.w = img.w;
    output.data = (unsigned char *)malloc(3 * img.w * img.h * sizeof(unsigned char));
    float mask[25];
    read_csv(path_csv, mask);
    convolution(CHANNELS, img.w, img.h, mask, img, &output);
    write_ppm(output, path_out);
    free (output.data);
    free(img.data);
    end = clock();
    time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("execution time: %lf.\n",time_spent);
    return 0;
    
}
Ejemplo n.º 3
0
void regclass_pyngraph_op_Convolution(py::module m)
{
    py::class_<ngraph::op::Convolution,
               std::shared_ptr<ngraph::op::Convolution>,
               ngraph::op::util::RequiresTensorViewArgs>
        convolution(m, "Convolution");
    convolution.doc() = "ngraph.impl.op.Convolution wraps ngraph::op::Convolution";
    convolution.def(py::init<const std::shared_ptr<ngraph::Node>&,
                             const std::shared_ptr<ngraph::Node>&,
                             const ngraph::Strides&,
                             const ngraph::Strides&,
                             const ngraph::CoordinateDiff&,
                             const ngraph::CoordinateDiff&,
                             const ngraph::Strides&>());

    convolution.def(py::init<const std::shared_ptr<ngraph::Node>&,
                             const std::shared_ptr<ngraph::Node>&,
                             const ngraph::Strides&,
                             const ngraph::Strides&,
                             const ngraph::CoordinateDiff&,
                             const ngraph::CoordinateDiff&>());

    convolution.def(py::init<const std::shared_ptr<ngraph::Node>&,
                             const std::shared_ptr<ngraph::Node>&,
                             const ngraph::Strides&,
                             const ngraph::Strides&>());

    convolution.def(py::init<const std::shared_ptr<ngraph::Node>&,
                             const std::shared_ptr<ngraph::Node>&,
                             const ngraph::Strides&>());

    convolution.def(
        py::init<const std::shared_ptr<ngraph::Node>&, const std::shared_ptr<ngraph::Node>&>());
}
Ejemplo n.º 4
0
void solve_pppm(FILE *fp,t_commrec *cr,
		t_fftgrid *grid,real ***ghat,rvec box,
		bool bVerbose,t_nrnb *nrnb)
{
  int  ntot,npppm;
  
/*  if (bVerbose) 
    print_fftgrid(fp,"Q-Real",grid,grid->nxyz,"qreal.pdb",box,TRUE);*/
  
  gmxfft3D(grid,FFTW_FORWARD,cr);
  
/*  if (bVerbose) {
    print_fftgrid(fp,"Q-k",grid,1.0,"qk-re.pdb",box,TRUE);
    print_fftgrid(fp,"Q-k",grid,1.0,"qk-im.pdb",box,FALSE);
    fprintf(stderr,"Doing convolution\n");
    }*/
  
  convolution(fp,bVerbose,grid,ghat,cr); 
  
  if (bVerbose) 
/*    print_fftgrid(fp,"Convolution",grid,1.0,
      "convolute.pdb",box,TRUE);*/
  
  gmxfft3D(grid,FFTW_BACKWARD,cr);
  
/*  if (bVerbose) 
    print_fftgrid(fp,"Potential",grid,1.0,"pot.pdb",box,TRUE);*/
  
  ntot  = grid->nxyz;  
  npppm = ntot*log((real)ntot)/log(2.0);
  inc_nrnb(nrnb,eNR_FFT,2*npppm);
  inc_nrnb(nrnb,eNR_CONV,ntot);
}
Ejemplo n.º 5
0
MainWindow::MainWindow(PgmImage *pgmImage, QWidget *parent) :
    QMainWindow(parent), ui(new Ui::MainWindow) {

    // init gui
    ui->setupUi(this);
    setWindowTitle("Digitale Bildverarbeitung - Tobias Dreher");

    // pointer to image class
    this->pgmImage = pgmImage;

    // connect select-buttons with methods
    connect(ui->btnLoad,SIGNAL(clicked()),this,SLOT(load()));
    connect(ui->btnHistogram,SIGNAL(clicked()),this,SLOT(histogram()));
    connect(ui->btnInvert,SIGNAL(clicked()),this,SLOT(invert()));
    connect(ui->btnConvolution,SIGNAL(clicked()),this,SLOT(convolution()));
    connect(ui->btnHough,SIGNAL(clicked()),this,SLOT(hough()));
    connect(ui->btnSave,SIGNAL(clicked()),this,SLOT(save()));
    connect(ui->btnLaneDec,SIGNAL(clicked()),this,SLOT(laneDetection()));
    connect(ui->btnLaneDec2,SIGNAL(clicked()),this,SLOT(laneDetection2()));
    connect(ui->btnLaneDec3,SIGNAL(clicked()),this,SLOT(laneDetection3()));
    connect(ui->btnRailDec,SIGNAL(clicked()),this,SLOT(railDetection()));

    // init other things
    rotateKernel = false;
}
Ejemplo n.º 6
0
void operations(int op, FILE *stream, int row, int col, int grey_scale){
	int mask_dim;
	int **conv_image;
	double **mask;
	char *mask_file;
	FILE *fp;

	switch(op) {
		case 1: //Produção do negativo.
			negativeTransform(stream, row, col, grey_scale);
			break;
		
		case 2: //Filtragem Espacial.
			mask_file = readLine(); //Lê o nome do arquivo de máscara.
			fp = fopen(mask_file, "r");
			if(!fp) noFile(mask_file, fp);

			mask = readMask(fp, &mask_dim);//Armazena o seu conteúdo.
			//Recebe a imagem já com a filtragem espacial
			conv_image = convolution(stream, mask, row, col, grey_scale, mask_dim);
			//Libera o conteúdo relacionado com a máscara.
			freeMask(mask_dim, mask, mask_file, fp);
			printImage(row, col, grey_scale, conv_image);
			break;
		
		default:
			//Caso não seja digitado nenhum operador esperado
			printf("Unknown Operator.\n");
			break;
	}
}
Ejemplo n.º 7
0
/**
* Applique la convolution 2d sur l'image passée en paramètre
* @param thread_id contient les paramètres à fournir pour la convolution 2d
* @return ne retourne rien
*/
void *thread(void *thread_id) {
  //on recupère les paramètres fourni au thread
  convolution_params_t *tab = (convolution_params_t *) thread_id;
  //On appel la fonction convolution avec les paramètres fournis
  convolution(tab->source, tab->destination, tab->filtre, tab->debut, tab->fin);
  return NULL;
}
Ejemplo n.º 8
0
void
filtre_sobel_v3(ndgIm src, ndgIm dest)
{
  /* largeur_filtre = 3 */
  /* hauteur_filtre = 3 */
  int **filtre;
  
  filtre = (int**)malloc(3 * sizeof(int*)); /* Allocation largeur */
  
  for (int ix = 0; ix < 3; ++ix)
    {
      filtre[ix] = (int*)malloc(3 * sizeof(int)); /* Allocation hauteur */
    }

  filtre[0][0] = -1; filtre[1][0] = 0; filtre[2][0] = 1;
  filtre[0][1] =-2;  filtre[1][1] = 0; filtre[2][1] = 2;
  filtre[0][2] = -1; filtre[1][2] = 0; filtre[2][2] = 1;

  convolution(src, dest, filtre, 3, 3, 4);

  for (int ix = 0; ix < 3; ++ix)
    {
      free(filtre[ix]);
    }
  free(filtre);
}
Ejemplo n.º 9
0
        // Forward with CPU.
        virtual unsigned long long forwardCPU(const vec &in) {

            clock_t start = clock(), diff;
            
            // Clear the output buffer.
            std::fill(out.begin(), out.end(), 0.0f);

            // For each output feature map.
            for (size_t o = 0; o < oDepth; ++o) {
                // For each input feature map.
                for (size_t i = 0; i < iDepth; ++i) {
                    // For each element in the output feature map.
                    for (size_t r = 0; r < oHeight; ++r) {
                        for (size_t c = 0; c < oWidth; ++c) {
                            getInput(i, r, c, in);
                            out[getOutputIdx(o, r, c)] += convolution(getWeightBase(i, o));
                        }
                    }
                }

                // Activate function.
                for (size_t r = 0; r < oHeight; ++r) {
                    for (size_t c = 0; c < oWidth; ++c) {
                        size_t idx = getOutputIdx(o, r, c);
                        out[idx] = sigmod(out[idx] + offset[o]);
                    }
                }
            }

            diff = clock() - start;
            int msec = diff * 1000 / CLOCKS_PER_SEC;

            return (unsigned long long)msec;
        }
Ejemplo n.º 10
0
// samples should be u-law encoded
void modem_decode(buffer_t *input, buffer_t *output)
{
    static int phase = -1;
    int max_idx;
    size_t i;
    int16_t max_mag;
    int16_t samples[SAMPLES_PER_ITER];

    for (i = 0; i < SAMPLES_PER_ITER; i++)
    {
        uint8_t byte;
        buffer_read_bytes(input, &byte, 1);
        samples[i] = comp_decode(byte) * 4;
    }

    // apply band-pass filter to remove noise
    bandpass_filter(samples);

    // apply convolution with delay line
    convolution(samples);

    // apply low-pass filter to remove high-frequency artifacts
    lowpass_filter(samples);

    // try and find the middle of the phase
    if (phase == -1)
    {
        max_mag = 0;
        max_idx = 0;
        for (i = 0; i < SAMPLES_PER_ITER; i++)
        {
            if (samples[i] > max_mag)
            {
                max_mag = samples[i];
                max_idx = i;
            }
            else if (-samples[i] > max_mag)
            {
                max_mag = -samples[i];
                max_idx = i;
            }
        }
        phase = (max_idx) % (SAMPLES_PER_BIT / 2);
    }

    // sample at baudrate to get output
    for (i = phase; i < SAMPLES_PER_ITER; i += SAMPLES_PER_BIT)
    {
        int avg = 0;
        int j;
        for (j = 0; j < SAMPLES_PER_BIT / 4; j++)
            avg += samples[i + j]; //< 0 ? -1 : 1;
        avg /= SAMPLES_PER_BIT / 4;
        int bit = avg < 0 ? 1 : 0;
        buffer_write_bit(output, bit);
    }
}
Ejemplo n.º 11
0
/**
    Applies polyphase FIR filter 

    Coefficients create a 24 kHz low pass filter for a 192 kHz wave
*/
void AudioProcessing::TestSimpleConvolution( const juce::File & input )
{
    const int polyphase4Size = sizeof(filterPhase0) / sizeof(float);
    const int convolutionSize = 4 * polyphase4Size;
    juce::AudioSampleBuffer convolutionFilter( 1, convolutionSize );

    float * data = convolutionFilter.getWritePointer( 0 );
    for ( int i = 0 ; i < polyphase4Size ; ++ i )
    {
        *data++ = filterPhase0[ i ];
        *data++ = filterPhase1[ i ];
        *data++ = filterPhase2[ i ];
        *data++ = filterPhase3[ i ];
    }

    juce::AudioFormatManager audioFormatManager;
    audioFormatManager.registerBasicFormats();

    juce::AudioFormatReader * reader = audioFormatManager.createReaderFor( input );

    if ( reader != nullptr )
    {
        // read file
        juce::AudioSampleBuffer origin( (int)reader->numChannels, (int)reader->lengthInSamples );
        reader->read( &origin, 0, (int)reader->lengthInSamples, 0, true, true );

        // Convolve
        juce::AudioSampleBuffer output;
        convolution( origin, convolutionFilter, output );
        output.applyGain(0.25f); // filter values use sample with 3 zeros per valid sample (1 / 4)

        juce::String outputName = input.getFullPathName().substring(0, input.getFullPathName().length() - 4);
        juce::File outputFile( outputName + "_convolution.wav" );
        juce::FileOutputStream * outputStream = new juce::FileOutputStream( outputFile );

        juce::WavAudioFormat wavAudioFormat;

        juce::StringPairArray emptyArray;
        juce::AudioFormatWriter * writer = wavAudioFormat.createWriterFor( 
            outputStream, reader->sampleRate, reader->numChannels, 24, emptyArray, 0 );

        if ( writer != nullptr )
        {
            writer->writeFromAudioSampleBuffer( output, 0, output.getNumSamples() );

            delete writer;
        }

        delete reader;
    }
}
Ejemplo n.º 12
0
int main(int argc,char** argv)
{
	int i,j,k;
  	int length,width;
  	float var;
  	int size_filter; 

  	float** image; 
	float** mask;  
  	float** degrad_image;  
   	
  	printf("Input the size of filter: ");
  	scanf("%d",&size_filter);
	
	printf("Input the variance of bruit : ");
  	scanf("%f",&var);

	image = LoadImagePgm(NAME_IMG_IN,&length,&width);
	mask = fmatrix_allocate_2d(length,width);
	degrad_image = fmatrix_allocate_2d(length,width);

	/* initialize array*/
	for(i=0;i<length;i++){
		for(j=0;j<width;j++){
			mask[i][j]=0.0;
			degrad_image[i][j]=0.0;
		}
	}

  	/* add blur to original image */
	blur_mask(mask,size_filter,length,width);
	convolution(degrad_image,image,mask,length,width);
	Recal(degrad_image,length,width);

	/* add noise to blur image */
	add_gaussian_noise(degrad_image,length,width,var);
	Recal(degrad_image,length,width);

  	/* save image */
	SaveImagePgm(NAME_IMG_OUT,degrad_image,length,width);
	system("display photograph_degraded.pgm&");
        
  
  	/* free memory*/
	free_fmatrix_2d(image);  
	free_fmatrix_2d(mask);
	free_fmatrix_2d(degrad_image);
  	
  	printf("\n Ending ... \n\n\n");
  	return 0; 	 
}
Ejemplo n.º 13
0
Archivo: convol.c Proyecto: alkra/MPIMP
int main(int argc, char *argv[]) {

  /* Variables se rapportant a l'image elle-meme */
  Raster r;
  int    w, h;	/* nombre de lignes et de colonnes de l'image */

  /* Variables liees au traitement de l'image */
  int 	 filtre;		/* numero du filtre */
  int 	 nbiter;		/* nombre d'iterations */

  /* Variables liees au chronometrage */
  double debut, fin;

  /* Variables de boucle */
  int 	i;

  if (argc != 4) {
    fprintf( stderr, usage, argv[0]);
    return 1;
  }
      
  /* Saisie des paramètres */
  filtre = atoi(argv[2]);
  nbiter = atoi(argv[3]);
        
  /* Lecture du fichier Raster */
  lire_rasterfile( argv[1], &r);
  h = r.file.ras_height;
  w = r.file.ras_width;
    
  /* debut du chronometrage */
  debut = my_gettimeofday();            

  /* La convolution a proprement parler */
  for(i=0 ; i < nbiter ; i++){
    convolution( filtre, r.data, h, w);
  } /* for i */

  /* fin du chronometrage */
  fin = my_gettimeofday();
  printf("Temps total de calcul : %g seconde(s) \n", fin - debut);
    
    /* Sauvegarde du fichier Raster */
  { 
    char nom_sortie[100] = "";
    sprintf(nom_sortie, "post-convolution_filtre%d_nbIter%d.ras", filtre, nbiter);
    sauve_rasterfile(nom_sortie, &r);
  }

  return 0;
}
Ejemplo n.º 14
0
arma::fmat * PithExtractor::contour(const Slice &slice, arma::fmat **orientation) const
{
	const uint height = slice.n_rows;
	const uint width = slice.n_cols;

	arma::fcolvec filtre1 = "1 2 1";			//filtre Sobel Gx
	arma::frowvec filtre2 = "-1 0 1";
	Slice *resultatGX, *resultatGY;
	arma::fmat norm = arma::fmat(height, width);
	arma::fmat *contour = new arma::fmat(height, width);

	*orientation = new arma::fmat(height, width);
	(*orientation)->zeros();
	resultatGX = convolution(slice, filtre1, filtre2);		//convolution Sobel GX
	filtre1 = "1 0 -1";										//filtre Sobel Gy
	filtre2 = "1 2 1";
	resultatGY = convolution(slice, filtre1, filtre2);		//convolution Sobel GY

	for (uint i=0; i<height; i++) {
		for (uint j=0; j<width; j++) {
			norm(i,j) = sqrt((*resultatGX)(i,j)*(*resultatGX)(i,j)+(*resultatGY)(i,j)*(*resultatGY)(i,j))/4;
			if (norm(i,j)>_binarizationThreshold && i>0 && i<norm.n_rows-1 && j>0 && j<norm.n_cols-1 ) {
				(*contour)(i,j) = 1;
				if((*resultatGX)(i,j)) {
					// Fred : pas de raison de faire une division entière ici :
					// (**orientation)(i,j) = (*resultatGY)(i,j) / (*resultatGX)(i,j);	//tangente teta
					(**orientation)(i,j) = double ((*resultatGY)(i,j)) / (*resultatGX)(i,j);	//tangente teta
				}
			} else {
				(*contour)(i,j) = 0;
			}
		}
	}
	delete resultatGX;
	delete resultatGY;

	return contour;
}
Ejemplo n.º 15
0
void EdgeDetectMarrHill::marr(float s, QImage *img)
{
    int width;
    float **smx;
    int i, j, n;
    float **lgau;

    /* Create a Gaussian and a derivative of Gaussian filter mask  */
    width = 3.35*s + 0.33;
    n = width + width + 1;

    qDebug() << ">>> Suavizando com Gaussiana de tamanho " << n << "x" << n;

    lgau = f2d (n, n);

    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            lgau[i][j] = LoG (distance((float)i, (float)j,
                                        (float)width, (float)width), s);

    /* Convolution of source image with a Gaussian in X and Y directions  */
    smx = f2d (img->width(), img->height());

    qDebug() << ">>> Convolucao com LoG";

    convolution (img, lgau, n, n, smx, img->height(), img->width());

    /* Locate the zero crossings */
    qDebug() << ">>> Passagens por Zero";
    zero_cross (smx, img);

    /* Clear the boundary */
    for (i = 0; i < img->width(); i++) {
        for (j = 0; j <= width; j++)
            img->setPixel(QPoint(i, j), qRgb(0, 0, 0));
        for (j = img->height() - width - 1; j < img->height(); j++)
            img->setPixel(QPoint(i, j), qRgb(0, 0, 0));
    }

    for (j = 0; j < img->height(); j++) {
        for (i = 0; i <= width; i++)
            img->setPixel(QPoint(i, j), qRgb(0, 0, 0));
        for (i = img->width() - width - 1; i < img->width(); i++)
            img->setPixel(QPoint(i, j), qRgb(0, 0, 0));
    }

    free(smx[0]); free(smx);
    free(lgau[0]); free(lgau);
}
Ejemplo n.º 16
0
int main(int argc, char **argv)
{
    int my_id;
    int p;

    /* Initialize rank and number of processor for the MPI */
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
    MPI_Comm_size(MPI_COMM_WORLD, &p);

    convolution(my_id, p);

    MPI_Finalize();
    return 0;
}
Ejemplo n.º 17
0
void filtre_moyenne3(ndgIm src, ndgIm dest)
{
  int** filtre;
  int largeur_filtre = 3;
  int hauteur_filtre = 3;
  filtre =(int**) malloc((largeur_filtre)*sizeof(int*));  
  for (int ix=0; ix<largeur_filtre; ix++)
    filtre[ix] =(int*) malloc((hauteur_filtre)*sizeof(int));  
  for (int iy=0; iy<hauteur_filtre; iy++)
    for (int ix=0; ix<largeur_filtre; ix++)
      filtre[ix][iy] = 1;

  convolution(src, dest, filtre, 3, 3, 9);

  for (int ix=0;ix<largeur_filtre; ix++)
    free(filtre[ix]);
  free(filtre);
}
Ejemplo n.º 18
0
void filtre_Sobel_Hori3(ndgIm src, ndgIm dest)
{
  int** filtre;
  int largeur_filtre = 3;
  int hauteur_filtre = 3;
  filtre =(int**) malloc((largeur_filtre)*sizeof(int*));  
  for (int ix=0; ix<largeur_filtre; ix++)
    filtre[ix] =(int*) malloc((hauteur_filtre)*sizeof(int));  
  
  filtre[0][0] = -1; filtre[1][0] = -2; filtre[2][0] = -1; 
  filtre[0][1] = 0; filtre[1][1] = 0; filtre[2][1] = 0; 
  filtre[0][2] = 1; filtre[1][2] = 2; filtre[2][2] = 1; 

  convolution(src, dest, filtre, 3, 3, 4);

  for (int ix=0;ix<largeur_filtre; ix++)
    free(filtre[ix]);
  free(filtre);
}
Ejemplo n.º 19
0
void bruit()
{
    g_print("reduction du bruit\n");

    float gauss[][3] = {
        {1, 1, 1},
        {1, 2, 1},
        {1, 1, 1}
    };


    SDL_Surface *ecran = NULL, *surface_tmp_c = NULL;
    SDL_Rect position;

    position.x = 0;
    position.y = 0;

    SDL_Init(SDL_INIT_VIDEO);

    surface_tmp_c = IMG_Load(chemin);

    ecran = SDL_SetVideoMode(surface_tmp_c->w, surface_tmp_c->h, 32, SDL_HWSURFACE);
    SDL_WM_SetCaption("PicToText", NULL);

    convolution(surface_tmp_c, 3, gauss);
    SDL_SaveBMP(surface_tmp_c, "image_convolution");

    SDL_Flip(ecran);

    SDL_FreeSurface(surface_tmp_c);
    SDL_Quit();

    GtkWidget *image, *pHbox, *window;
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_window_set_default_size(GTK_WINDOW(window),1550,900);
    gtk_container_set_border_width(GTK_CONTAINER(window),10);

    pHbox = gtk_hbox_new(FALSE,8);
    image = gtk_image_new_from_file("image_convolution");
    gtk_box_pack_start(GTK_BOX(pHbox), image, FALSE,TRUE,0);
    gtk_container_add(GTK_CONTAINER(window), pHbox);
    gtk_widget_show_all(window);
}
Ejemplo n.º 20
0
void PDI::testConvolution(){
    cv::Mat g = cv::Mat::ones(10, 10, CV_64F);
    cv::Mat h = cv::Mat::ones(3, 3, CV_64F);

    // cv::Mat f = convolution(g, h);
    cv::Mat f = convolution(g, h);

    for(int y=0; y<f.rows; y++){
        for(int x=0; x<f.cols; x++){
            std::cout << f.at<double>(y,x) << " ";
        }
        std::cout << std::endl;
    }

    normalizateMatrix(f, 0, 255);
    cv::Mat f_d = convertToInterger(f);
    cv::namedWindow("f(x,y)"); //, CV_WINDOW_NORMAL);
    cv::imshow("f(x,y)", f_d);
}
Ejemplo n.º 21
0
int main ( int argc, char * argv [] ){

    matrix_t A=matinit();
    matrix_t B=matinit();
    matrix_t C=matinit();

    loadByName("testfiles/input.mat", "a", &A);
    loadByName("testfiles/input.mat", "b", &B);

    printf("Matriz A:\n");
    matprint(A);
    putchar('\n');

    printf("Matriz B:\n");
    matprint(B);
    putchar('\n');
    C=convolution(A,B);
    if( C.height==0 ){
        return 1;
    }

    printf("\nMatriz C:\n");
    matprint(C);
    putchar('\n');

    saveByName("testfiles/output.mat", "c", &C);

    //TEST probar si funciona el copiar:
    matrix_t D = matinit();
    D.height=0;
    D.width=0;
    matcpy(&D, &C);
    printf("\nMatriz D:\n");
    matprint(D);
    matfree(&D);

    matfree(&C);
    matfree(&A);
    matfree(&B);

    return 0;
}
Ejemplo n.º 22
0
/*
 * gaussianFilter:
 * http://www.songho.ca/dsp/cannyedge/cannyedge.html
 * determine size of kernel (odd #)
 * 0.0 <= sigma < 0.5 : 3
 * 0.5 <= sigma < 1.0 : 5
 * 1.0 <= sigma < 1.5 : 7
 * 1.5 <= sigma < 2.0 : 9
 * 2.0 <= sigma < 2.5 : 11
 * 2.5 <= sigma < 3.0 : 13 ...
 * kernelSize = 2 * int(2*sigma) + 3;
 */
void gaussian_filter(const pixel_t *in, pixel_t *out,
                     const int nx, const int ny, const float sigma)
{
    const int n = 2 * (int)(2 * sigma) + 3;
    const float mean = (float)floor(n / 2.0);
    float kernel[n * n]; // variable length array
 
    fprintf(stderr, "gaussian_filter: kernel size %d, sigma=%g\n",
            n, sigma);
    size_t c = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            kernel[c] = exp(-0.5 * (pow((i - mean) / sigma, 2.0) +
                                    pow((j - mean) / sigma, 2.0)))
                        / (2 * M_PI * sigma * sigma);
            c++;
        }
 
    convolution(in, out, kernel, nx, ny, n, true);
}
Ejemplo n.º 23
0
void PDI::gaussianConvolution(int sigma, cv::Mat &image, bool separated_kernel){
    // Get the image range (to re-convert)
    int min, max;
    getImageRange(image, min, max);
    // Create a copy of the values (as double)
    cv::Mat g = convertToDouble(image);
    // Image double of zeros
    cv::Mat f = cv::Mat::zeros(g.rows, g.cols, CV_64F);

    if(separated_kernel){ // Kernel separated routine
        // Generating Kernel
        double h0[6*sigma];
        double h1[6*sigma];
        gaussianArrays(sigma, h0, h1);

        f = convolutionSeparatedKernel(g, h0, 6*sigma, h1, 6*sigma);
    }

    else{ // Unique Kernel routine
        // Generating Kernel
        cv::Mat h = gaussianImage(sigma);
        cv::namedWindow("Kernel",CV_WINDOW_NORMAL);
        cv::imshow("Kernel", convertToInterger(h));

        f = convolution(g, h);
    }

    // Image double converted into integer
    normalizateMatrix(f, min, max);
    cv::Mat img = convertToInterger(f);

    cv::namedWindow("Initial Image");
    cv::imshow("Initial Image", image);
    cv::namedWindow("Final Image");
    cv::imshow("Final Image", img);
}
Ejemplo n.º 24
0
void itConv(byte *buffer, int buffer_size, int width, int *op, byte **res) {
    // Allocate memory for result
    *res = malloc(sizeof(byte) * buffer_size);

    // Temporary memory for each pixel operation
    byte op_mem[SOBEL_OP_SIZE];
    memset(op_mem, 0, SOBEL_OP_SIZE);

    // Make convolution for every pixel
    for(int i=0; i<buffer_size; i++) {
        // Make op_mem
        makeOpMem(buffer, buffer_size, width, i, op_mem);

        // Convolution
        (*res)[i] = (byte) abs(convolution(op_mem, op, SOBEL_OP_SIZE));

        /*
         * The abs function is used in here to avoid storing negative numbers
         * in a byte data type array. It wouldn't make a different if the negative
         * value was to be stored because the next time it is used the value is
         * squared.
         */
    }
}
Ejemplo n.º 25
0
/*
// Computation objective function D according the original paper
//
// API
// int filterDispositionLevel(const CvLSVMFilterObject *Fi, const featurePyramid *H, 
                              int level, float **scoreFi, 
                              int **pointsX, int **pointsY);
// INPUT
// Fi                - filter object (weights and coefficients of penalty 
                       function that are used in this routine)
// H                 - feature pyramid
// level             - level number
// OUTPUT
// scoreFi           - values of distance transform on the level at all positions
// (pointsX, pointsY)- positions that correspond to the maximum value 
                       of distance transform at all grid nodes
// RESULT
// Error status
*/
int filterDispositionLevel(const CvLSVMFilterObject *Fi, const CvLSVMFeatureMap *pyramid,
                           float **scoreFi, 
                           int **pointsX, int **pointsY)
{
    int n1, m1, n2, m2, p, size, diff1, diff2;
    float *f;    
    int i1, j1;
    int res;
    
    n1 = pyramid->sizeY;
    m1 = pyramid->sizeX;
    n2 = Fi->sizeY;
    m2 = Fi->sizeX;
    p = pyramid->p;
    (*scoreFi) = NULL;
    (*pointsX) = NULL;
    (*pointsY) = NULL;
    
    // Processing the situation when part filter goes 
    // beyond the boundaries of the block set
    if (n1 < n2 || m1 < m2)
    {
        return FILTER_OUT_OF_BOUNDARIES;
    } /* if (n1 < n2 || m1 < m2) */

    // Computation number of positions for the filter
    diff1 = n1 - n2 + 1;
    diff2 = m1 - m2 + 1;
    size = diff1 * diff2;

    // Allocation memory for additional array (must be free in this function)
    f = (float *)malloc(sizeof(float) * size);       
    // Allocation memory for arrays for saving decisions
    (*scoreFi) = (float *)malloc(sizeof(float) * size);
    (*pointsX) = (int *)malloc(sizeof(int) * size);
    (*pointsY) = (int *)malloc(sizeof(int) * size);

    // Consruction values of the array f 
    // (a dot product vectors of feature map and weights of the filter)
    res = convolution(Fi, pyramid, f); 
    if (res != LATENT_SVM_OK)
    {
        free(f);
        free(*scoreFi);
        free(*pointsX);
        free(*pointsY);
        return res;
    }

    // TODO: necessary to change
    for (i1 = 0; i1 < diff1; i1++)
    {
         for (j1 = 0; j1 < diff2; j1++)
         {
             f[i1 * diff2 + j1] *= (-1);
         }   
    }

    // Decision of the general distance transform task 
    DistanceTransformTwoDimensionalProblem(f, diff1, diff2, Fi->fineFunction, 
                                          (*scoreFi), (*pointsX), (*pointsY));

    // Release allocated memory
    free(f);
    return LATENT_SVM_OK;
}
// Identify the peaks of votes (most significant straight lines) in the accmulator.
void
peak_detection(lines_list_t &lines, const accumulator_t &accumulator)
{
	/* Leandro A. F. Fernandes, Manuel M. Oliveira
	 * Real-time line detection through an improved Hough transform voting scheme
	 * Pattern Recognition (PR), Elsevier, 41:1, 2008, 299-314.
	 *
	 * Section 3.4
	 */

	const int **bins = accumulator.bins();
	const double *rho = accumulator.rho();
	const double *theta = accumulator.theta();

	// Create a list with all cells that receive at least one vote.
	static bins_list_t used_bins;
	
	size_t used_bins_count = 0;
	for (size_t theta_index=1, theta_end=accumulator.height()+1; theta_index!=theta_end; ++theta_index)
	{
		for (size_t rho_index=1, rho_end=accumulator.width()+1; rho_index!=rho_end; ++rho_index)
		{
			if (bins[theta_index][rho_index])
			{
				used_bins_count++;
			}
		}
	}
	used_bins.resize( used_bins_count );
		
	for (size_t theta_index=1, i=0, theta_end=accumulator.height()+1; theta_index!=theta_end; ++theta_index)
	{
		for (size_t rho_index=1, rho_end=accumulator.width()+1; rho_index!=rho_end; ++rho_index)
		{
			if (bins[theta_index][rho_index])
			{
				bin_t &bin = used_bins[i];

				bin.rho_index = rho_index;
				bin.theta_index = theta_index;
				bin.votes = convolution( bins, rho_index, theta_index ); // Convolution of the cells with a 3x3 Gaussian kernel

				i++;
			}
		}
	}
	
	// Sort the list in descending order according to the result of the convolution.
	std::qsort( used_bins.items(), used_bins_count, sizeof( bin_t ), (int(*)(const void*, const void*))compare_bins );
	
	// Use a sweep plane that visits each cell of the list.
	static visited_map_t visited;
	visited.init( accumulator.width(), accumulator.height() );

	lines.clear();
	lines.reserve( used_bins_count );

	for (size_t i=0; i!=used_bins_count; ++i)
	{
		bin_t &bin = used_bins[i];

		if (!visited.visited_neighbour( bin.rho_index, bin.theta_index ))
		{
			line_t &line = lines.push_back();
			
			line.rho = rho[bin.rho_index];
			line.theta = theta[bin.theta_index];
		}
		visited.set_visited( bin.rho_index, bin.theta_index );
	}
}
Ejemplo n.º 27
0
/*
 * Links:
 * http://en.wikipedia.org/wiki/Canny_edge_detector
 * http://www.tomgibara.com/computer-vision/CannyEdgeDetector.java
 * http://fourier.eng.hmc.edu/e161/lectures/canny/node1.html
 * http://www.songho.ca/dsp/cannyedge/cannyedge.html
 *
 * Note: T1 and T2 are lower and upper thresholds.
 */
pixel_t *canny_edge_detection(const pixel_t *in,
                              const bitmap_info_header_t *bmp_ih,
                              const int tmin, const int tmax,
                              const float sigma)
{
    const int nx = bmp_ih->width;
    const int ny = bmp_ih->height;
 
    pixel_t *G = calloc(nx * ny * sizeof(pixel_t), 1);
    pixel_t *after_Gx = calloc(nx * ny * sizeof(pixel_t), 1);
    pixel_t *after_Gy = calloc(nx * ny * sizeof(pixel_t), 1);
    pixel_t *nms = calloc(nx * ny * sizeof(pixel_t), 1);
    pixel_t *out = malloc(bmp_ih->bmp_bytesz * sizeof(pixel_t));
 
    if (G == NULL || after_Gx == NULL || after_Gy == NULL ||
        nms == NULL || out == NULL) {
        fprintf(stderr, "canny_edge_detection:"
                " Failed memory allocation(s).\n");
        exit(1);
    }
 
    gaussian_filter(in, out, nx, ny, sigma);
 
    const float Gx[] = {-1, 0, 1,
                        -2, 0, 2,
                        -1, 0, 1};
 
    convolution(out, after_Gx, Gx, nx, ny, 3, false);
 
    const float Gy[] = { 1, 2, 1,
                         0, 0, 0,
                        -1,-2,-1};
 
    convolution(out, after_Gy, Gy, nx, ny, 3, false);
 
    for (int i = 1; i < nx - 1; i++)
        for (int j = 1; j < ny - 1; j++) {
            const int c = i + nx * j;
            // G[c] = abs(after_Gx[c]) + abs(after_Gy[c]);
            G[c] = (pixel_t)hypot(after_Gx[c], after_Gy[c]);
        }
 
    // Non-maximum suppression, straightforward implementation.
    for (int i = 1; i < nx - 1; i++)
        for (int j = 1; j < ny - 1; j++) {
            const int c = i + nx * j;
            const int nn = c - nx;
            const int ss = c + nx;
            const int ww = c + 1;
            const int ee = c - 1;
            const int nw = nn + 1;
            const int ne = nn - 1;
            const int sw = ss + 1;
            const int se = ss - 1;
 
            const float dir = (float)(fmod(atan2(after_Gy[c],
                                                 after_Gx[c]) + M_PI,
                                           M_PI) / M_PI) * 8;
 
            if (((dir <= 1 || dir > 7) && G[c] > G[ee] &&
                 G[c] > G[ww]) || // 0 deg
                ((dir > 1 && dir <= 3) && G[c] > G[nw] &&
                 G[c] > G[se]) || // 45 deg
                ((dir > 3 && dir <= 5) && G[c] > G[nn] &&
                 G[c] > G[ss]) || // 90 deg
                ((dir > 5 && dir <= 7) && G[c] > G[ne] &&
                 G[c] > G[sw]))   // 135 deg
                nms[c] = G[c];
            else
                nms[c] = 0;
        }
 
    // Reuse array
    // used as a stack. nx*ny/2 elements should be enough.
    int *edges = (int*) after_Gy;
    memset(out, 0, sizeof(pixel_t) * nx * ny);
    memset(edges, 0, sizeof(pixel_t) * nx * ny);
 
    // Tracing edges with hysteresis . Non-recursive implementation.
    size_t c = 1;
    for (int j = 1; j < ny - 1; j++)
        for (int i = 1; i < nx - 1; i++) {
            if (nms[c] >= tmax && out[c] == 0) { // trace edges
                out[c] = MAX_BRIGHTNESS;
                int nedges = 1;
                edges[0] = c;
 
                do {
                    nedges--;
                    const int t = edges[nedges];
 
                    int nbs[8]; // neighbours
                    nbs[0] = t - nx;     // nn
                    nbs[1] = t + nx;     // ss
                    nbs[2] = t + 1;      // ww
                    nbs[3] = t - 1;      // ee
                    nbs[4] = nbs[0] + 1; // nw
                    nbs[5] = nbs[0] - 1; // ne
                    nbs[6] = nbs[1] + 1; // sw
                    nbs[7] = nbs[1] - 1; // se
 
                    for (int k = 0; k < 8; k++)
                        if (nms[nbs[k]] >= tmin && out[nbs[k]] == 0) {
                            out[nbs[k]] = MAX_BRIGHTNESS;
                            edges[nedges] = nbs[k];
                            nedges++;
                        }
                } while (nedges > 0);
            }
            c++;
        }
 
    free(after_Gx);
    free(after_Gy);
    free(G);
    free(nms);
 
    return out;
}
Ejemplo n.º 28
0
int main(int argc, char** argv)
{
	if(argc != 4)
	{
		printf("Sorry, error datum");
		printf("%s %s %s", argv[0], argv[1], argv[2]);
	}
	else
	{
		int i;
		FILE* BMP = fopen(argv[1], "r");
		printf("Enter name of the outfile: ");
		FILE* BMP1 = fopen(argv[2], "w");

		if(BMP == NULL)
		{
			printf("Sorry error, repeat pleas\n");
		}
		else
		{
			fread(&BITMAPFILEHEADER.bfType, 2, 1, BMP);
			char* pz = (char*) &BITMAPFILEHEADER.bfType;

			if(BITMAPFILEHEADER.bfType == 19778)
			{
				printf("Type of the file: BMP");
				fread(&BITMAPFILEHEADER.bfSize, 4, 1, BMP);
				fread(&BITMAPFILEHEADER.bfReserved1, 2, 1, BMP);
				fread(&BITMAPFILEHEADER.bfReserved2, 2, 1, BMP);
				fread(&BITMAPFILEHEADER.bfOffBits, 4, 1, BMP);

				fread(&BITMAPINFOHEADER.biSize, 4, 1, BMP);
				fread(&BITMAPINFOHEADER.biWidth, 4, 1, BMP);
				fread(&BITMAPINFOHEADER.biHeight, 4, 1, BMP);
				fread(&BITMAPINFOHEADER.biPlanes, 2, 1, BMP);
				fread(&BITMAPINFOHEADER.biBitCount, 2, 1, BMP);
				fread(&BITMAPINFOHEADER.biCompression, 4, 1, BMP);
				fread(&BITMAPINFOHEADER.biSizeImage, 4, 1, BMP);
				fread(&BITMAPINFOHEADER.biXPelsPerMeter, 4, 1, BMP);
				fread(&BITMAPINFOHEADER.biYPelsPerMeter, 4, 1, BMP);
				fread(&BITMAPINFOHEADER.biClrUsed, 4, 1, BMP);
				fread(&BITMAPINFOHEADER.biClrImportant, 4, 1, BMP);
				int j, i;
				printf("\nHeight %d, Width %d\nNumbers pixel: %d. \n", BITMAPINFOHEADER.biHeight, BITMAPINFOHEADER.biWidth, BITMAPINFOHEADER.biHeight * BITMAPINFOHEADER.biWidth);
				RGB** pok;
				pok = (RGB**) malloc(sizeof(RGB*) * BITMAPINFOHEADER.biHeight);
				for(i = 0; i < BITMAPINFOHEADER.biHeight; i++)
				{
					pok[i] = (RGB*) malloc(sizeof(RGB) * BITMAPINFOHEADER.biWidth);
				}
				int k, k1; //...............................
				k = (4 - (BITMAPINFOHEADER.biWidth * 3) % 4) % 4;

				unsigned char mus = 0;
				for(i = 0; i < abs(BITMAPINFOHEADER.biHeight); i++)
				{
					for(j = 0; j < abs(BITMAPINFOHEADER.biWidth); j++)
					{
						RGB rgb;
						fread(&rgb.rgbBlue, 1, 1, BMP);
						fread(&rgb.rgbGreen, 1, 1, BMP);
						fread(&rgb.rgbRed, 1, 1, BMP);
						pok[i][j].rgbBlue = rgb.rgbBlue;
						(pok[i][j]).rgbGreen = rgb.rgbGreen;
						((pok[i][j])).rgbRed = rgb.rgbRed;
					}
					//printf("%d %d %d\n", pok[i][j].rgbBlue, rgb.rgbGreen, rgb.rgbBlue);
					for(k1 = 0; k1 < k; k1++)
					{
						fread(&mus, 1, 1, BMP);
					}

				}//.........................считывания файла, корректный случай
				//.............,..дополнения фильтрами.............................
				menu();
				switch(atoi(argv[3])) {
					case (1): medium_filtr(BMP1, pok);
						break;
					case (2): convolution(BMP1, pok);
						break;
					case (3): filtr_Gaussa_blur(BMP1, pok);
						break;
					case (4): filtr_Sobel_x(BMP1, pok);
						break;
					case (5): filtr_Sobel_y(BMP1, pok);
						break;
					case (6): filtr_Gaussa_x(BMP1, pok);
						break;
					case (7): filtr_Gaussa_y(BMP1, pok);
						break;
					case (8): filtr_Happy(BMP1, pok);
						break;
					case (9): pasta(BMP1, pok);
						break;
					case (10): filtr_Color(BMP1, pok);
						break;
					case (11): filtr_Sobel_x_y(BMP1, pok);
						break;
					case (12): filtr_Gaussa_x_y(BMP1, pok);
						break;
				}
			}
			else
			{
				printf("File no correct.\n");
				printf("\n%c%c\n", *pz, *pz + 1);
				getchar();
				getchar();
				fclose(BMP);
				fclose(BMP1);
			}
		}
		fclose(BMP);
	}

	return(EXIT_SUCCESS);
}
Ejemplo n.º 29
0
int main(int argc, char** argv){
    int N,i;
    double a,b,W,w;
    std::string FuncName,FileName;
    dcomplex *fw, *gw, *nw, *ew;
    std::ofstream ofs;
    
    //////////////////////////////////////////
    // parameters
    W=10; // width
    N = 1000; // # of mesh
    a = -W/2; // w_min
    b = +W/2;  // w_max
    FuncName = "Symmetric"; // function type
    FileName = "graph-"
        +FuncName
        +"-width_"+int2string(int(round(W)))
        +".txt"; // export file
    //////////////////////////////////////////
    

    fw = new dcomplex [N]; // operand
    gw = new dcomplex [N]; // operand
    nw = new dcomplex [N]; // numerical convolution
    ew = new dcomplex [N]; // exact convolution

    
    // generate operand functions
    if(FuncName=="Asymmetric"){
        for(i=0;i<N;i++){
            w=a+(b-a)*i/N;
            fw[i]=func(w-8);
            gw[i]=func(w+2);
            ew[i]=.5*func((w-6)/2);
        }
    }else{
        for(i=0;i<N;i++){
            w=a+(b-a)*i/N;
            fw[i]=func(w-2);
            gw[i]=func(w+2);
            ew[i]=.5*func(w/2);
        }
    }
    
    // calculate convolution
    convolution(N,W,fw,gw,nw);
    
    // export
    ofs.open(FileName.c_str());
    ofs.setf(std::ios::scientific);
    ofs << "# \"w\" \"numerical(real, imag)\" \"exact(real, imag)\"\n";
    for(i=0;i<N;i++){
        w=a+(b-a)*i/N;
        ofs << w << " "
        << nw[i].real() << " " << nw[i].imag() << " "
        << ew[i].real() << " " << ew[i].imag() << "\n";
    }
    ofs.close();
    
    delete [] fw;
    delete [] gw;
    delete [] nw;
    delete [] ew;
    
    return 0;
}
Ejemplo n.º 30
0
/*
// Computation score function at the level that exceed threshold
//
// API
// int thresholdFunctionalScoreFixedLevel(const CvLSVMFilterObject **all_F, int n, 
                                          const featurePyramid *H, 
                                          int level, float b, 
                                          int maxXBorder, int maxYBorder,
                                          float scoreThreshold,
                                          float **score, CvPoint **points, int *kPoints,
                                          CvPoint ***partsDisplacement);
// INPUT
// all_F             - the set of filters (the first element is root filter, 
                       the other - part filters)
// n                 - the number of part filters
// H                 - feature pyramid
// level             - feature pyramid level for computation maximum score
// b                 - linear term of the score function
// maxXBorder        - the largest root filter size (X-direction)
// maxYBorder        - the largest root filter size (Y-direction)
// scoreThreshold    - score threshold
// OUTPUT
// score             - score function at the level that exceed threshold
// points            - the set of root filter positions (in the block space)
// levels            - the set of levels
// kPoints           - number of root filter positions
// partsDisplacement - displacement of part filters (in the block space)
// RESULT
// Error status
*/
int thresholdFunctionalScoreFixedLevel(const CvLSVMFilterObject **all_F, int n, 
                                       const CvLSVMFeaturePyramid *H, 
                                       int level, float b, 
                                       int maxXBorder, int maxYBorder,
                                       float scoreThreshold,
                                       float **score, CvPoint **points, int *kPoints,
                                       CvPoint ***partsDisplacement)
{
    int i, j, k, dimX, dimY, nF0, mF0, p;
    int diff1, diff2, index, last, partsLevel;
    CvLSVMFilterDisposition **disposition;
    float *f;
    float *scores;
    float sumScorePartDisposition;
    int res;
    CvLSVMFeatureMap *map;
#ifdef FFT_CONV
    CvLSVMFftImage *rootFilterImage, *mapImage;
#else
#endif
    /*
    // DEBUG variables
    FILE *file;
    char *tmp;
    char buf[40] = "..\\Data\\score\\score", buf1[10] = ".csv";
    tmp = (char *)malloc(sizeof(char) * 80);
    itoa(level, tmp, 10);
    strcat(tmp, buf1);
    //*/

    // Feature map matrix dimension on the level
    dimX = H->pyramid[level]->sizeX;
    dimY = H->pyramid[level]->sizeY;

    // Number of features
    p = H->pyramid[level]->p;
        
    // Getting dimension of root filter
    nF0 = all_F[0]->sizeY;
    mF0 = all_F[0]->sizeX;
    // Processing the situation when root filter goes 
    // beyond the boundaries of the block set
    if (nF0 > dimY || mF0 > dimX)
    {
        return LATENT_SVM_FAILED_SUPERPOSITION;
    }
        
    diff1 = dimY - nF0 + 1;
    diff2 = dimX - mF0 + 1;   
   
    // Allocation memory for saving values of function D 
    // on the level for each part filter
    disposition = (CvLSVMFilterDisposition **)malloc(sizeof(CvLSVMFilterDisposition *) * n);
    for (i = 0; i < n; i++)
    {
        disposition[i] = (CvLSVMFilterDisposition *)malloc(sizeof(CvLSVMFilterDisposition));
    }  

    // Allocation memory for values of score function for each block on the level
    scores = (float *)malloc(sizeof(float) * (diff1 * diff2));
    // A dot product vectors of feature map and weights of root filter
#ifdef FFT_CONV
    getFFTImageFeatureMap(H->pyramid[level], &mapImage);
    getFFTImageFilterObject(all_F[0], H->pyramid[level]->sizeX, H->pyramid[level]->sizeY, &rootFilterImage);
    res = convFFTConv2d(mapImage, rootFilterImage, all_F[0]->sizeX, all_F[0]->sizeY, &f);
    freeFFTImage(&mapImage);
    freeFFTImage(&rootFilterImage);
#else
    // Allocation memory for saving a dot product vectors of feature map and 
    // weights of root filter
    f = (float *)malloc(sizeof(float) * (diff1 * diff2));
    res = convolution(all_F[0], H->pyramid[level], f);
#endif
    if (res != LATENT_SVM_OK)
    {
        free(f);
        free(scores);
        for (i = 0; i < n; i++)
        {
            free(disposition[i]);
        }
        free(disposition);
        return res;
    }

    // Computation values of function D for each part filter 
    // on the level (level - LAMBDA)
    partsLevel = level - LAMBDA;
    // For feature map at the level 'partsLevel' add nullable border
    map = featureMapBorderPartFilter(H->pyramid[partsLevel], 
                                     maxXBorder, maxYBorder);
    
    // Computation the maximum of score function
    sumScorePartDisposition = 0.0;
#ifdef FFT_CONV
    getFFTImageFeatureMap(map, &mapImage);
    for (k = 1; k <= n; k++)
    {  
        filterDispositionLevelFFT(all_F[k], mapImage, 
                               &(disposition[k - 1]->score), 
                               &(disposition[k - 1]->x), 
                               &(disposition[k - 1]->y));
    }
    freeFFTImage(&mapImage);
#else
    for (k = 1; k <= n; k++)
    {        
        filterDispositionLevel(all_F[k], map, 
                               &(disposition[k - 1]->score), 
                               &(disposition[k - 1]->x), 
                               &(disposition[k - 1]->y));
    }
#endif
    (*kPoints) = 0;
    for (i = 0; i < diff1; i++)
    {
        for (j = 0; j < diff2; j++)
        {
            sumScorePartDisposition = 0.0;
            for (k = 1; k <= n; k++)
            {                
                // This condition takes on a value true
                // when filter goes beyond the boundaries of block set
                if ((2 * i + all_F[k]->V.y < 
                            map->sizeY - all_F[k]->sizeY + 1) &&
                    (2 * j + all_F[k]->V.x < 
                            map->sizeX - all_F[k]->sizeX + 1))
                {
                    index = (2 * i + all_F[k]->V.y) * 
                                (map->sizeX - all_F[k]->sizeX + 1) + 
                            (2 * j + all_F[k]->V.x);
                    sumScorePartDisposition += disposition[k - 1]->score[index];
                } 
            }
            scores[i * diff2 + j] = f[i * diff2 + j] - sumScorePartDisposition + b;
            if (scores[i * diff2 + j] > scoreThreshold)                
            {
                (*kPoints)++;
            }
        }
    }

    // Allocation memory for saving positions of root filter and part filters
    (*points) = (CvPoint *)malloc(sizeof(CvPoint) * (*kPoints));
    (*partsDisplacement) = (CvPoint **)malloc(sizeof(CvPoint *) * (*kPoints));
    for (i = 0; i < (*kPoints); i++)
    {
        (*partsDisplacement)[i] = (CvPoint *)malloc(sizeof(CvPoint) * n);
    }

    /*// DEBUG
    strcat(buf, tmp);
    file = fopen(buf, "w+");
    //*/
    // Construction of the set of positions for root filter 
    // that correspond score function on the level that exceed threshold
    (*score) = (float *)malloc(sizeof(float) * (*kPoints));
    last = 0;
    for (i = 0; i < diff1; i++)
    {
        for (j = 0; j < diff2; j++)
        {
            if (scores[i * diff2 + j] > scoreThreshold) 
            {
                (*score)[last] = scores[i * diff2 + j];
                (*points)[last].y = i;
                (*points)[last].x = j;
                for (k = 1; k <= n; k++)
                {                    
                    if ((2 * i + all_F[k]->V.y < 
                            map->sizeY - all_F[k]->sizeY + 1) &&
                        (2 * j + all_F[k]->V.x < 
                            map->sizeX - all_F[k]->sizeX + 1))
                    {
                        index = (2 * i + all_F[k]->V.y) * 
                                   (map->sizeX - all_F[k]->sizeX + 1) + 
                                (2 * j + all_F[k]->V.x);
                        (*partsDisplacement)[last][k - 1].x = 
                                              disposition[k - 1]->x[index];
                        (*partsDisplacement)[last][k - 1].y = 
                                              disposition[k - 1]->y[index];
                    } 
                }
                last++;
            }
            //fprintf(file, "%lf;", scores[i * diff2 + j]);
        }
        //fprintf(file, "\n");
    }
    //fclose(file);
    //free(tmp);

    // Release allocated memory
    for (i = 0; i < n ; i++)
    {
        free(disposition[i]->score);
        free(disposition[i]->x);
        free(disposition[i]->y);
        free(disposition[i]);
    }
    free(disposition);
    free(f);
    free(scores);
    freeFeatureMapObject(&map);
    return LATENT_SVM_OK;
}