定向梯度直方图

Histogram of oriented gradiants

本文关键字:直方图      更新时间:2023-10-16

对于一个项目,我正在编写一些代码来计算一些图像的HoG,但在使用atan2函数时,我的方向仅在0~90度之间。我猜这个问题是由于OpenCV的filter2D函数引起的,但我不确定这是原因还是我做错了什么:

Vector<Vector<Mat_<float>>> HoG(Mat image) {
Mat img_x;
Mat img_y;
IplImage img = image;
Mat kern_x = (Mat_<char>(1, 3) << -1, 0, 1);
Mat kern_y = (Mat_<char>(3, 1) << -1, 0, 1);
filter2D(image, img_x, image.depth(), kern_x);
filter2D(image, img_y, image.depth(), kern_y);
Vector<Vector<Mat_<float>>> histograms;
for(int y = 0; y < image.rows - size; y += size) {
    Vector<Mat_<float>> temp_hist;
    for(int x = 0; x < image.cols - size; x += size) {
        float total_mag = 0;
        Mat hist = Mat::zeros(1, 8, CV_32FC1);
        for(int i = y; i < y + size; ++i) {
            for(int j = x; j < x + size; ++j) {
                float grad_x = (float)img_x.at<uchar>(i, j);
                float grad_y = (float)img_y.at<uchar>(i, j);
                double ori = myatan2(grad_x, grad_y);
                float mag = sqrt(pow(grad_x, 2) + pow(grad_y, 2));
                int bin = round(ori/45);
                hist.at<float>(0, (bin - 1 < 0 ? 7 : bin - 1)) += - (float)(ori - ((round(ori/45) - 1) * 45.0 + 22.5)) / 45.0f;
                hist.at<float>(0, bin) += -(float)(ori - ((round(ori/45) - 1) * 45.0 + 22.5)) / 45.0f;
                total_mag += mag;
            }
        }
        // Normalize the histogram
        for(int i = 0; i < 8; ++i) {
            hist.at<float>(0, i) = hist.at<float>(0, i) / total_mag;
        }
        temp_hist.push_back(hist);
    }
    histograms.push_back(temp_hist);
}
return histograms;
}

如果你有任何其他技巧来提高我的代码或其他东西的速度,这当然也是受欢迎的。

我注意到了这一点:

float grad_x = (float)img_x.at<uchar>(i, j);
float grad_y = (float)img_y.at<uchar>(i, j);

您似乎在使用uchar。这不应该是char吗?