C++ 中的 OpenCV filter2D 负值

OpenCV filter2D negative values in C++

我正在尝试在 C++ 中的某些视频帧上实现定向梯度直方图。我使用 filter2D 对帧图像进行卷积,但结果值似乎以 0 为底。如何让 filter2D 也给出负值?

这是一段代码:

// 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. 您的代码似乎没问题,应该会产生积极的结果和消极的结果。你如何检查没有负面结果?也许您正在将浮点图像转换为灰度级(即 unsigned char),这确实会裁剪所有负面结果。

  2. 使用Sobel函数更容易获得相同的结果,该函数专门用于计算图像中的梯度:

    Sobel(图像, gradientX, CV_32F, 1, 0, 1);

    Sobel(图像, gradientY, CV_32F, 0, 1, 1);