opencv2 第9天 Extracting image features

Detecting image contours with the canny operator

Canny(image,//gray-level image
		img2,//output image
		120,//low threshold
		350);//high threshold
	Mat contoursInv;
	threshold(img2,contoursInv,
		128,//value below this
		255,//becomes this
		THRESH_BINARY);

Detecting lines in images with the Hough transform

/* This is a standalone program. Pass an image name as a first parameter of the program.
   Switch between standard and probabilistic Hough transform by changing "#if 1" to "#if 0" and back */
#include <cv.h>
#include <highgui.h>
#include <math.h>
 
int main(int argc, char** argv)
{
    const char* filename = argc >= 2 ? argv[1] : "D:\\1.jpg";
    IplImage* src = cvLoadImage( filename, 0 );
    IplImage* dst;
    IplImage* color_dst;
    CvMemStorage* storage = cvCreateMemStorage(0);
    CvSeq* lines = 0;
    int i;
 
    if( !src )
        return -1;
 
    dst = cvCreateImage( cvGetSize(src), 8, 1 );
    color_dst = cvCreateImage( cvGetSize(src), 8, 3 );
 
    cvCanny( src, dst, 50, 200, 3 );
    cvCvtColor( dst, color_dst, CV_GRAY2BGR );
#if 0
    lines = cvHoughLines2( dst, storage, CV_HOUGH_STANDARD, 1, CV_PI/180, 100, 0, 0 );
 
    for( i = 0; i < MIN(lines->total,100); i++ )
    {
        float* line = (float*)cvGetSeqElem(lines,i);
        float rho = line[0];
        float theta = line[1];
        CvPoint pt1, pt2;
        double a = cos(theta), b = sin(theta);
        double x0 = a*rho, y0 = b*rho;
        pt1.x = cvRound(x0 + 1000*(-b));
        pt1.y = cvRound(y0 + 1000*(a));
        pt2.x = cvRound(x0 - 1000*(-b));
        pt2.y = cvRound(y0 - 1000*(a));
        cvLine( color_dst, pt1, pt2, CV_RGB(255,0,0), 3, CV_AA, 0 );
    }
#else
    lines = cvHoughLines2( dst, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, 50, 50, 10 );
    for( i = 0; i < lines->total; i++ )
    {
        CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);
        cvLine( color_dst, line[0], line[1], CV_RGB(255,0,0), 3, CV_AA, 0 );
    }
#endif
    cvNamedWindow( "Source", 1 );
    cvShowImage( "Source", src );
 
    cvNamedWindow( "Hough", 1 );
    cvShowImage( "Hough", color_dst );
 
    cvWaitKey(0);
 system("pause");
    return 0;
}
opencv 标准的检测直线的程序

opencv2给的程序

//user.cpp
/*------------------------------------------------------------------------------------------*\
   This file contains material supporting chapter 7 of the cookbook:  
   Computer Vision Programming using the OpenCV Library.
   by Robert Laganiere, Packt Publishing, 2011.

   This program is free software; permission is hereby granted to use, copy, modify,
   and distribute this source code, or portions thereof, for any purpose, without fee,
   subject to the restriction that the copyright notice may not be removed
   or altered from any source or altered source distribution.
   The software is released on an as-is basis and without any warranties of any kind.
   In particular, the software is not guaranteed to be fault-tolerant or free from failure.
   The author disclaims all warranties with regard to this software, any use,
   and any consequent failure, is purely the responsibility of the user.
 
   Copyright (C) 2010-2011 Robert Laganiere, www.laganiere.name
\*------------------------------------------------------------------------------------------*/

#include <iostream>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include "linefinder.h"
#include "edgedetector.h"

#define PI 3.1415926

int main()
{
        // Read input image
        cv::Mat image= cv::imread("D:\\images\\road.jpg");
        if (!image.data)
                return 0;

    // Display the image
        cv::namedWindow("Original Image");
        cv::imshow("Original Image",image);

        // Compute Sobel
        EdgeDetector ed;
        ed.computeSobel(image);

    // Display the Sobel orientation
        cv::namedWindow("Sobel (orientation)");
        cv::imshow("Sobel (orientation)",ed.getSobelOrientationImage());
        cv::imwrite("ori.bmp",ed.getSobelOrientationImage());

    // Display the Sobel low threshold
        cv::namedWindow("Sobel (low threshold)");
        cv::imshow("Sobel (low threshold)",ed.getBinaryMap(125));

    // Display the Sobel high threshold
        cv::namedWindow("Sobel (high threshold)");
        cv::imshow("Sobel (high threshold)",ed.getBinaryMap(350));

        // Apply Canny algorithm
        cv::Mat contours;
        cv::Canny(image,contours,125,350);
        cv::Mat contoursInv;
        cv::threshold(contours,contoursInv,128,255,cv::THRESH_BINARY_INV);

    // Display the image of contours
        cv::namedWindow("Canny Contours");
        cv::imshow("Canny Contours",contoursInv);
		//
		//system("pause");
		//cvDestroyAllWindows();
        // Create a test image
        cv::Mat test(200,200,CV_8U,cv::Scalar(0));
        cv::line(test,cv::Point(100,0),cv::Point(200,200),cv::Scalar(255));
        cv::line(test,cv::Point(0,50),cv::Point(200,200),cv::Scalar(255));
        cv::line(test,cv::Point(0,200),cv::Point(200,0),cv::Scalar(255));
        cv::line(test,cv::Point(200,0),cv::Point(0,200),cv::Scalar(255));
        cv::line(test,cv::Point(100,0),cv::Point(100,200),cv::Scalar(255));
        cv::line(test,cv::Point(0,100),cv::Point(200,100),cv::Scalar(255));

    // Display the test image
        cv::namedWindow("Test Image");
        cv::imshow("Test Image",test);
        cv::imwrite("test.bmp",test);

        // Hough tranform for line detection
        std::vector<cv::Vec2f> lines;
        cv::HoughLines(contours,lines,1,PI/180,60);

        // Draw the lines
        cv::Mat result(contours.rows,contours.cols,CV_8U,cv::Scalar(255));
        image.copyTo(result);

        std::cout << "Lines detected: " << lines.size() << std::endl;

        std::vector<cv::Vec2f>::const_iterator it= lines.begin();
        while (it!=lines.end()) {

                float rho= (*it)[0];   // first element is distance rho
                float theta= (*it)[1]; // second element is angle theta
               
                if (theta < PI/4. || theta > 3.*PI/4.) { // ~vertical line
               
                        // point of intersection of the line with first row
                        cv::Point pt1(rho/cos(theta),0);        
                        // point of intersection of the line with last row
                        cv::Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows);
                        // draw a white line
                        cv::line( result, pt1, pt2, cv::Scalar(255), 1);

                } else { // ~horizontal line

                        // point of intersection of the line with first column
                        cv::Point pt1(0,rho/sin(theta));        
                        // point of intersection of the line with last column
                        cv::Point pt2(result.cols,(rho-result.cols*cos(theta))/sin(theta));
                        // draw a white line
                        cv::line( result, pt1, pt2, cv::Scalar(255), 1);
                }

                std::cout << "line: (" << rho << "," << theta << ")\n";

                ++it;
        }

    // Display the detected line image
        cv::namedWindow("Detected Lines with Hough");
        cv::imshow("Detected Lines with Hough",result);

        // Create LineFinder instance
        LineFinder ld;

        // Set probabilistic Hough parameters
        ld.setLineLengthAndGap(100,20);
        ld.setMinVote(80);

        // Detect lines
        std::vector<cv::Vec4i> li= ld.findLines(contours);
        ld.drawDetectedLines(image);
        cv::namedWindow("Detected Lines with HoughP");
        cv::imshow("Detected Lines with HoughP",image);

        std::vector<cv::Vec4i>::const_iterator it2= li.begin();
        while (it2!=li.end()) {

                std::cout << "(" << (*it2)[0] << ","<< (*it2)[1]<< ")-("
                             << (*it2)[2]<< "," << (*it2)[3] << ")" <<std::endl;

                ++it2;
        }

        // Display one line
        image= cv::imread("D:\\images\\road.jpg");
        int n=0;
        cv::line(image, cv::Point(li[n][0],li[n][1]),cv::Point(li[n][2],li[n][3]),cv::Scalar(255),5);
        cv::namedWindow("One line of the Image");
        cv::imshow("One line of the Image",image);

        // Extract the contour pixels of the first detected line
        cv::Mat oneline(image.size(),CV_8U,cv::Scalar(0));
        cv::line(oneline, cv::Point(li[n][0],li[n][1]),cv::Point(li[n][2],li[n][3]),cv::Scalar(255),5);
        cv::bitwise_and(contours,oneline,oneline);
        cv::Mat onelineInv;
        cv::threshold(oneline,onelineInv,128,255,cv::THRESH_BINARY_INV);
        cv::namedWindow("One line");
        cv::imshow("One line",onelineInv);
		//cvDestroyAllWindows();
		//system("pause");
        std::vector<cv::Point> points;

        // Iterate over the pixels to obtain all point positions
        for( int y = 0; y < oneline.rows; y++ ) {
   
                uchar* rowPtr = oneline.ptr<uchar>(y);
   
                for( int x = 0; x < oneline.cols; x++ ) {

                    // if on a contour
                        if (rowPtr[x]) {

                                points.push_back(cv::Point(x,y));
                        }
                }
    }
       
        // find the best fitting line
        cv::Vec4f line;
        cv::fitLine(cv::Mat(points),line,CV_DIST_L2,0,0.01,0.01);

        std::cout << "line: (" << line[0] << "," << line[1] << ")(" << line[2] << "," << line[3] << ")\n";

        int x0= line[2];
        int y0= line[3];
        int x1= x0-200*line[0];
        int y1= y0-200*line[1];
        image= cv::imread("D:\\images\\road.jpg");
        cv::line(image,cv::Point(x0,y0),cv::Point(x1,y1),cv::Scalar(0),3);
        cv::namedWindow("Estimated line");
        cv::imshow("Estimated line",image);

        // eliminate inconsistent lines
        ld.removeLinesOfInconsistentOrientations(ed.getOrientation(),0.4,0.1);

   // Display the detected line image
        image= cv::imread("D:\\images\\road.jpg");
        ld.drawDetectedLines(image);
        cv::namedWindow("Detected Lines (2)");
        cv::imshow("Detected Lines (2)",image);

        // Create a Hough accumulator
        cv::Mat acc(200,180,CV_8U,cv::Scalar(0));

        // Choose a point
        int x=50, y=30;

        // loop over all angles
        for (int i=0; i<180; i++) {

                double theta= i*PI/180.;

                // find corresponding rho value
                double rho= x*cos(theta)+y*sin(theta);
                int j= static_cast<int>(rho+100.5);

                std::cout << i << "," << j << std::endl;

                // increment accumulator
                acc.at<uchar>(j,i)++;
        }

        cv::imwrite("hough1.bmp",acc*100);

        // Choose a second point
        x=30, y=10;

        // loop over all angles
        for (int i=0; i<180; i++) {

                double theta= i*PI/180.;
                double rho= x*cos(theta)+y*sin(theta);
                int j= static_cast<int>(rho+100.5);

                acc.at<uchar>(j,i)++;
        }

        cv::namedWindow("Hough Accumulator");
        cv::imshow("Hough Accumulator",acc*100);
        cv::imwrite("hough2.bmp",acc*100);

        // Detect circles
        image= cv::imread("D:\\images\\chariot.jpg",0);
        cv::GaussianBlur(image,image,cv::Size(5,5),1.5);
        std::vector<cv::Vec3f> circles;
        cv::HoughCircles(image, circles, CV_HOUGH_GRADIENT,
                2,   // accumulator resolution (size of the image / 2)
                50,  // minimum distance between two circles
                200, // Canny high threshold
                100, // minimum number of votes
                25, 100); // min and max radius

        std::cout << "Circles: " << circles.size() << std::endl;
       
        // Draw the circles
        image= cv::imread("D:\\images\\chariot.jpg");
        std::vector<cv::Vec3f>::const_iterator itc= circles.begin();
       
        while (itc!=circles.end()) {
               
          cv::circle(image,
                  cv::Point((*itc)[0], (*itc)[1]), // circle centre
                  (*itc)[2], // circle radius
                  cv::Scalar(255), // color
                  2); // thickness
               
          ++itc;        
        }

        cv::namedWindow("Detected Circles");
        cv::imshow("Detected Circles",image);

        cv::waitKey();
		system("pause");
        return 0;
}

//linefinder.h
/*------------------------------------------------------------------------------------------*\
   This file contains material supporting chapter 7 of the cookbook:  
   Computer Vision Programming using the OpenCV Library.
   by Robert Laganiere, Packt Publishing, 2011.

   This program is free software; permission is hereby granted to use, copy, modify,
   and distribute this source code, or portions thereof, for any purpose, without fee,
   subject to the restriction that the copyright notice may not be removed
   or altered from any source or altered source distribution.
   The software is released on an as-is basis and without any warranties of any kind.
   In particular, the software is not guaranteed to be fault-tolerant or free from failure.
   The author disclaims all warranties with regard to this software, any use,
   and any consequent failure, is purely the responsibility of the user.
 
   Copyright (C) 2010-2011 Robert Laganiere, www.laganiere.name
\*------------------------------------------------------------------------------------------*/

#if !defined LINEF
#define LINEF

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#define PI 3.1415926

class LineFinder {

  private:

          // original image
          cv::Mat img;

          // vector containing the end points
          // of the detected lines
          std::vector<cv::Vec4i> lines;

          // accumulator resolution parameters
          double deltaRho;
          double deltaTheta;

          // minimum number of votes that a line
          // must receive before being considered
          int minVote;

          // min length for a line
          double minLength;

          // max allowed gap along the line
          double maxGap;

  public:

          // Default accumulator resolution is 1 pixel by 1 degree
          // no gap, no mimimum length
          LineFinder() : deltaRho(1), deltaTheta(PI/180), minVote(10), minLength(0.), maxGap(0.) {}

          // Set the resolution of the accumulator
          void setAccResolution(double dRho, double dTheta) {

                  deltaRho= dRho;
                  deltaTheta= dTheta;
          }

          // Set the minimum number of votes
          void setMinVote(int minv) {

                  minVote= minv;
          }

          // Set line length and gap
          void setLineLengthAndGap(double length, double gap) {

                  minLength= length;
                  maxGap= gap;
          }

          // Apply probabilistic Hough Transform
          std::vector<cv::Vec4i> findLines(cv::Mat& binary) {

                  lines.clear();
                  cv::HoughLinesP(binary,lines,deltaRho,deltaTheta,minVote, minLength, maxGap);

                  return lines;
          }

          // Draw the detected lines on an image
          void drawDetectedLines(cv::Mat &image, cv::Scalar color=cv::Scalar(255,255,255)) {
       
                  // Draw the lines
                  std::vector<cv::Vec4i>::const_iterator it2= lines.begin();
       
                  while (it2!=lines.end()) {
               
                          cv::Point pt1((*it2)[0],(*it2)[1]);        
                          cv::Point pt2((*it2)[2],(*it2)[3]);

                          cv::line( image, pt1, pt2, color);
               
                          ++it2;        
                  }
          }

          // Eliminates lines that do not have an orientation equals to
          // the ones specified in the input matrix of orientations
          // At least the given percentage of pixels on the line must
          // be within plus or minus delta of the corresponding orientation
          std::vector<cv::Vec4i> removeLinesOfInconsistentOrientations(
                  const cv::Mat &orientations, double percentage, double delta) {

                          std::vector<cv::Vec4i>::iterator it= lines.begin();
       
                          // check all lines
                          while (it!=lines.end()) {

                                  // end points
                                  int x1= (*it)[0];
                                  int y1= (*it)[1];
                                  int x2= (*it)[2];
                                  int y2= (*it)[3];
                   
                                  // line orientation + 90o to get the parallel line
                                  double ori1= atan2(static_cast<double>(y1-y2),static_cast<double>(x1-x2))+PI/2;
                                  if (ori1>PI) ori1= ori1-2*PI;

                                  double ori2= atan2(static_cast<double>(y2-y1),static_cast<double>(x2-x1))+PI/2;
                                  if (ori2>PI) ori2= ori2-2*PI;
       
                                  // for all points on the line
                                  cv::LineIterator lit(orientations,cv::Point(x1,y1),cv::Point(x2,y2));
                                  int i,count=0;
                                  for(i = 0, count=0; i < lit.count; i++, ++lit) {
               
                                          float ori= *(reinterpret_cast<float *>(*lit));

                                          // is line orientation similar to gradient orientation ?
                                          if (std::min(fabs(ori-ori1),fabs(ori-ori2))<delta)
                                                  count++;
               
                                  }

                                  double consistency= count/static_cast<double>(i);

                                  // set to zero lines of inconsistent orientation
                                  if (consistency < percentage) {
 
                                          (*it)[0]=(*it)[1]=(*it)[2]=(*it)[3]=0;

                                  }

                                  ++it;
                          }

                          return lines;
          }
};


#endif

//edgedetector.h
/*------------------------------------------------------------------------------------------*\
   This file contains material supporting chapter 6 of the cookbook:  
   Computer Vision Programming using the OpenCV Library.
   by Robert Laganiere, Packt Publishing, 2011.

   This program is free software; permission is hereby granted to use, copy, modify,
   and distribute this source code, or portions thereof, for any purpose, without fee,
   subject to the restriction that the copyright notice may not be removed
   or altered from any source or altered source distribution.
   The software is released on an as-is basis and without any warranties of any kind.
   In particular, the software is not guaranteed to be fault-tolerant or free from failure.
   The author disclaims all warranties with regard to this software, any use,
   and any consequent failure, is purely the responsibility of the user.
 
   Copyright (C) 2010-2011 Robert Laganiere, www.laganiere.name
\*------------------------------------------------------------------------------------------*/

#if !defined SOBELEDGES
#define SOBELEDGES

#define PI 3.1415926

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>

class EdgeDetector {

  private:

          // original image
          cv::Mat img;

          // 16-bit signed int image
          cv::Mat sobel;

          // Aperture size of the Sobel kernel
          int aperture;

          // Sobel magnitude
          cv::Mat sobelMagnitude;

          // Sobel orientation
          cv::Mat sobelOrientation;

  public:

          EdgeDetector() : aperture(3) {}

          // Set the aperture size of the kernel
          void setAperture(int a) {

                  aperture= a;
          }

          // Get the aperture size of the kernel
          int getAperture() const {

                  return aperture;
          }

          // Compute the Sobel
          void computeSobel(const cv::Mat& image, cv::Mat &sobelX=cv::Mat(), cv::Mat &sobelY=cv::Mat()) {

                  // Compute Sobel
                  cv::Sobel(image,sobelX,CV_32F,1,0,aperture);
                  cv::Sobel(image,sobelY,CV_32F,0,1,aperture);

                  // Compute magnitude and orientation
                  cv::cartToPolar(sobelX,sobelY,sobelMagnitude,sobelOrientation);
          }

          // Get Sobel magnitude
          // Make a copy if called more than once
          cv::Mat getMagnitude() {

                  return sobelMagnitude;
          }

          // Get Sobel orientation
          // Make a copy if called more than once
          cv::Mat getOrientation() {

                  return sobelOrientation;
          }

          // Get a thresholded binary map
          cv::Mat getBinaryMap(double threshold) {

                  cv::Mat bin;            
                  cv::threshold(sobelMagnitude,bin,threshold,255,cv::THRESH_BINARY_INV);

                  return bin;
          }

          // Get a CV_8U image of the Sobel
          cv::Mat getSobelImage() {

                  cv::Mat bin;

                  double minval, maxval;
                  cv::minMaxLoc(sobelMagnitude,&minval,&maxval);
                  sobelMagnitude.convertTo(bin,CV_8U,255/maxval);

                  return bin;
          }

          // Get a CV_8U image of the Sobel orientation
          // 1 gray-level = 2 degrees
          cv::Mat getSobelOrientationImage() {

                  cv::Mat bin;

                  sobelOrientation.convertTo(bin,CV_8U,90/PI);

                  return bin;
          }

};


#endif







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值