c++ - 方向梯度直方图

标签 c++ image-processing opencv

对于一个项目,我正在编写一些代码来计算一些图像的 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 吗?

关于c++ - 方向梯度直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12435846/

相关文章:

c++ - STL 对输入与 STL 映射

c++ - C/C++ 中最有效的方法来修剪额外的空白,除了 1 个空白用于非常大的数据集

c++ - 使用opencv和c++进行稀疏编码和字典学习

opencv - 如何分类是单个数字还是多个数字

c++ - multimap 像拼接 - 添加第三个图像

python - 灰度图像中缺陷区域的分割,对阴影具有不变性

python - Python中的OpenCV GUI问题

c++ - X 请求失败错误 : BadValue (integer parameter out of range for operation)

c++ - visual studio 查找替换

python - 如何应用超过 4 对点的透视变换?