2012-09-15 69 views
0

对于一个项目,我正在编写一些代码来计算一些图像的灰度值,但我坚持使用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; 
} 

如果您有任何其他提示在我的代码或其他东西中加快速度,当然也是受欢迎的。

回答

1

我注意到这一点:

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

你似乎使用uchar。这不应该是char

+0

以及使用cv :: sobel更容易取得衍生物 – etarion