简体   繁体   中英

OpenCV filter2D negative values in C++

I'm trying to implement Histogram of Oriented Gradients on some video frames in C++. I used filter2D to convolute the frame image yet it seems that the resulting values are floored at 0. How do I get filter2D to give negative values as well?

Here's a snippet of code:

// Function that gets the histogram of gradients for a single video file
int HOG(string filename)
{
    static int frames_read = 0;
    VideoCapture cap(filename);
    if(!cap.isOpened())  // check if we succeeded
        return -1;

    Mat image;
    namedWindow(filename,1);

    // Read through frames of video
    for(;;)
    {
        Mat frame;
        float histogram[NUM_BINS * SPACIAL_X * SPACIAL_Y] = {0};
        cap >> frame; // Get a new frame from camera
        if(frame.empty())
            break;
        cvtColor(frame, image, CV_BGR2GRAY);

        // Set up gradient kernels
        float kernelX[9] = {0, 0, 0, -1.0, 0, 1.0, 0, 0, 0};
        float kernelY[9] = {0, -1.0, 0, 0, 0, 0, 0, 1.0, 0};
        Mat filterX(3, 3, CV_32F, kernelX);
        Mat filterY(3, 3, CV_32F, kernelY);
        Mat gradientX;
        Mat gradientY;

        // Apply gradients
        filter2D(image, gradientX, CV_32F, filterX, Point (-1, 1), 0, BORDER_DEFAULT);
        filter2D(image, gradientY, CV_32F, filterY, Point (-1, 1), 0, BORDER_DEFAULT);
    }
}
  1. Your code seems to be OK, and should generate positive results as well as negatives. How are you checking that there no negative results? Maybe you are converting floating point images to gray level (ie unsigned char), this indeed will crop all negative results.

  2. It is easier to get same results by using Sobel function, that is dedicated to calculation of gradients in image:

    Sobel(image, gradientX, CV_32F, 1, 0, 1);

    Sobel(image, gradientY, CV_32F, 0, 1, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM