Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Get strength of edges using magnitude

I am trying to get the strength of detected lines using the gradient magnitude referring to this post:

I detect lines as vector<Vec4f>with the Line Segment Detector (LSD) in an image and I calculate the magnitude of the same image. Now I want to calculate the strength of a single line using my magnitude Mat. How can I use one line as a mask for my magnitude and calculate for example the sum of all values. My first approach would be to draw a line in the magnitude "image" and sum up all values the line hits. But I think there must be a better approach using the opencv libs?

Here is my code:

void findLines(cv::Mat inputimg, std::vector<cv::Vec4f> &lines, cv::Mat &outputimg) {
   cv::equalizeHist(inputimg, inputimg);

   cv::Mat reduced_noise;
   cv::bilateralFilter(inputimg, reduced_noise, 5, 75, 75, 4);

   cv::Ptr<cv::LineSegmentDetector> Line_detector = cv::createLineSegmentDetector();
   Line_detector->detect(reduced_noise, lines);
   Line_detector->drawSegments(outputimg, lines);

void computeMagnitude(Mat img, Mat magn) {

  // Compute dx and dy deratives with Sobel
  Mat dx, dy;
  Sobel(img, dx, CV_32F, 1, 0);
  Sobel(img, dy, CV_32F, 0, 1);

  // Compute gradient 
  magnitude(dx, dy, magn);

int main(int argc, char** argv) {
  // Load two images as grayscale images
  Mat img_1, img_2;
  img_1 = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
  img_2 = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE);

  // Test if images could be read
  if (! || ! {
      cout << "Error reading image" << endl;
      return EXIT_FAILURE;

  Mat magnitude_1;
  vector<Vec4f> lines_1;
  Mat drawing = img_1.clone();

  computeMagnitude(img_1, magnitude_1);
  findLines(img_1, lines_1, drawing);

  // Draw a line in the magnitude image and calculate the sum of all cells it hits ?