Search code examples
opencvgradientruntime-errorhistogramintegral

Runtime error SIGSEV in opencv2 HOG code


I got this code Im working on, extracted from http://smsoftdev-solutions.blogspot.com/2009/08/integral-histogram-for-fast-calculation.html.

Currently im porting the code on that page to opencv2 c++ implementation, and this is what I have so far.

MAIN


using namespace cv;
using namespace std;

//CONSTANTES
#define PI 3.142

//FUNCIONES
vector<Mat> extractIntegralHist(Mat in, const int _nbins);

int main(int argc, char *argv[])
{
//Definicion de variables
    Mat frame;
    vector<Mat> integrals(9);
    namedWindow("main_video",WINDOW_AUTOSIZE);
    namedWindow("temporal_window",WINDOW_AUTOSIZE);

//Inicializa la captura del video
    VideoCapture cap(0);
       if(!cap.isOpened()){
           return -1;
           cout << "No se puede capturar";
       }

//Loop principal
    while(1){
       cap >> frame;
       imshow("main_video",frame);
       waitKey(1);

       extractIntegralHist(frame, 9);

    }
    integrals.clear();
}

FUNCTION


//CALCULAR HISTOGRAMAS DE INTEGRALES
vector<Mat> extractIntegralHist(Mat in, const int _nbins){
    Mat in_gray;
    int x,y;
    float temp_gradient,temp_magnitude;
    namedWindow("temporal_window",WINDOW_AUTOSIZE);
//Convierte la imagen a escala de grises y normaliza
    cvtColor(in,in_gray,CV_RGB2GRAY);
    equalizeHist(in_gray,in_gray);
//Calcula la derivada de la imagen en gris en direccion x,y utilizando sobel
    Mat xsobel, ysobel;
    Sobel(in_gray, xsobel, CV_32FC1, 1, 0, 1);
    Sobel(in_gray, ysobel, CV_32FC1, 0, 1, 1);
    in_gray.release();
//Crea la matriz de 9 imagenes contenedoras -- REVISAR ESTE CODIGO
    vector<Mat> bins(_nbins);
    for (int i = 0; i < _nbins ; i++) {
        bins[9] = Mat::zeros(in.size(),CV_32F);
    }
//Crea la matriz donde se guardaran las integrales de la imagen
    vector<Mat> integrals(_nbins);
    for (int i = 0; i < _nbins ; i++) {
        integrals[9] = Mat(Size(in_gray.cols+1,in_gray.rows+1),CV_64F);
    }
//Calcula los contenedores
    for(y=0;y<in.rows;y++){

        float* xSobelPtr = (float*) (xsobel.row(y).data);
        float* ySobelPtr = (float*) (ysobel.row(y).data);

        float** binsRowPtrs = new float *[_nbins];
        for (int i = 0; i < _nbins; i++){
            binsRowPtrs[i] = (float*) (bins[i].row(y).data);
        }
    //Para cada pixel en la fila los valores de magnitud y orientacion son calculados
        for(x=0;x<in.cols;x++){
            if(xSobelPtr==0){
                temp_gradient = ((atan(ySobelPtr[x]/(xSobelPtr[x]+0.00001)))*(180/PI)+90);
            }
            else{
                temp_gradient = ((atan(ySobelPtr[x]/xSobelPtr[x]))+(180/PI)+90);
            }
            temp_magnitude = sqrt((xSobelPtr[x] * xSobelPtr[x]) + (ySobelPtr[x] *       ySobelPtr[x]));
            float binStep = 180/ /*_nbins*/9;
                for (int i=1 ; i<=/*_nbins*/9 ; i++){
                    if (temp_gradient <= binStep*i){
                    binsRowPtrs[i-1][x] = temp_magnitude;
                    break;
                    }
                }
        }
     }

     for (int i = 0; i<_nbins;i++){
        integral(bins[i],integrals[i]);
     }

     for (int i = 0; i <_nbins ; i++){
        bins[i].release();
     }

    return integrals;
}

The program compiles, but when I run it, it just stops, the debugger shows me a SIGSEV error and shows line 61 and 38.

38 - extractIntegralHist(frame, 9);

61 - bins[9] = Mat::zeros(in.size(),CV_32F);

I havent been able to pinpoint the problem because everything seems fine to me, can you take a look to the code please?

Edit. Update. It appears the program stop when the function extractIntegralHist is run, allegedly on line 61 (of the function). Now, I know this is a memory handling exception but I just can't find what's wrong with it, furthermore I don't understand what the debugger is telling me.

Thanks.


Solution

  • The line

    bins[9] = Mat::zeros(in.size(),CV_32F);
    

    is attempting to access the tenth (note the zero-indexing) element of bins. Since _nbins is passed in with a value of 9, this is past the vector's bounds. Also, if you use .at() instead of accessing elements using [], this kind of error will throw an out_of_range exception which should be more helpful in diagnosing the problem.

    To assign each element of the vector to a cv::Mat containing zeroes, consider changing your loop to

    for (int i = 0; i < _nbins ; i++) {
        bins[i] = Mat::zeros(in.size(),CV_32F);
    }
    

    Or more succinctly, remove the loop and replace your bins initialization with

    vector<Mat> bins(_nbins, Mat::zeros(in.size(),CV_32F));
    

    Note that you have the same problem in your initialization of integrals.