OpenCV contour detection to calculate object rotation angle

Source: Internet
Author: User
Tags scalar

The effect is still a bit of a problem, I hope we discuss together

Findrotation-angle.cpp: Defines the entry point of the console application. FindContours.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <vector> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/ highgui.hpp> #pragma comment (lib, "Opencv_core2410d.lib") #pragma comment (lib, "Opencv_highgui2410d.lib") #pragm A comment (lib, "Opencv_imgproc2410d.lib") #define PI 3.1415926using namespace std;using namespace Cv;int hough_line (Mat  SRC) {//"1" load the original graph and Mat variable definition mat srcimage = Src;//imread ("1.jpg"); The project directory should have a footage map named 1.jpg Mat midimage,dstimage;//temporary variables and the definition of the target Graph//"2" for edge detection and conversion to grayscale canny (Srcimage, Midimage, 50, 200, 3); /Perform a canny edge detection cvtcolor (Midimage,dstimage, CV_GRAY2BGR);//conversion edge detection after the image is grayscale//"3" for the Hough Line transformation vector<vec4i> lines;// Defines a vector structure lines is used to store the resulting segment vector set HOUGHLINESP (Midimage, lines, 1, cv_pi/180, 80, 50, 10);//"4" in turn plots each segment for (size_t i = 0; I &l T Lines.size (); i++) {vec4i L = lines[i];line (DSTImage, point (L[0], l[1]), point (L[2], l[3]), Scalar (186,88,255), 1, CV_AA);}  "5" shows the original figure Imshow ("original figure" ", srcimage);  "6" Edge detection after the figure imshow ("Edge detection after the figure" ", midimage);  "7" Display Imshow ("" "" ", dstimage);  Waitkey (0);  return 0; }int Main () {//Read input binary Imagechar *image_name = "test.jpg"; Cv::mat image = Cv::imread (image_name,0); if (!image.da TA) return 0; Cv::namedwindow ("binary image"); Cv::imshow ("Binary image", image);//load Original from file Iplimage *psrcimage = Cvloadimage (image_       Name, cv_load_image_unchanged);      Converted to 2 value Figure cvthreshold (PSRCIMAGE,PSRCIMAGE,200,255,CV::THRESH_BINARY_INV);   Image = Cv::mat (psrcimage,true); Cv::imwrite ("binary.jpg", image);//Get The contours of the connected COMPONENTSSTD::VECTOR&LT;STD::VECTOR&LT;CV:: Point>> contours;cv::findcontours (image, contours,//vector of contours cv_retr_external,//Retrieve the Externa L contourscv_chain_approx_none); Retrieve all pixels of each contours//Print contours ' lengthstd::cout << ' contours: ' << Contours.size () << STD::ENDL;STD::VECTOR&LT;STD::VECTOR&LT;CV::P oint>>::const_iterator itContours= Contours.begin (); for (; Itcontours!=contours.end (); ++itcontours) {std::cout << "Size:" << itcontours-> Size () << Std::endl;} Draw black contours on white imagecv::mat result (Image.size (), Cv_8u,cv::scalar (255)); CV::d rawcontours (Result, Contours,-1,//Draw all Contourscv::scalar (0),//in Black2); With a thickness of 2cv::namedwindow ("contours"); Cv::imshow ("contours", result);//eliminate too short or too long conto  Ursint cmin= 100; Minimum contour lengthint cmax= 1000; Maximum contour LENGTHSTD::VECTOR&LT;STD::VECTOR&LT;CV::P oint>>::const_iterator itc= contours.begin (); while (Itc!=contours.end ()) {if (Itc->size () < Cmin | | itc->size () > Cmax) itc= contours.erase (ITC); else ++ITC ;} Draw contours on the original Imagecv::mat original= Cv::imread (image_name); CV::d rawcontours (original,contours,-1,/ /Draw All Contourscv::scalar (255,255,0),//in White2); With a thickness of 2cv::namedwindow ("contours to Original"); Cv::imshow ("Contours on Original", original);/Let's now D Raw black contours on white imageresult.setto (Cv::scalar (255)); CV::d rawcontours (result,contours,-1,//Draw All Contourscv::scalar (0),//in BLACK1); With a thickness of 1image= cv::imread ("Binary.jpg", 0);//imshow ("lll", result);//waitkey (0);//testing the bounding Box////////////////////////////////////////////////////////////////////////////////Hough transform for line detection, Used here is probabilistic Hough transform (CV::HOUGHLINESP) instead of standard Hough transform (cv::houghlines) Cv::mat Result_line ( Image.size (), Cv_8u,cv::scalar (255)); result_line = Result.clone (); Hough_line (result_line);//mat tempimage;//"2" Edge detection and conversion to grayscale figure//canny (Result_line, Tempimage, 50, 200, 3);//Conduct a Canny edge detection//imshow ("Canny", Tempimage);//waitkey (0); /cvtcolor (Tempimage,result_line, CV_GRAY2BGR);//The image after conversion edge detection is a grayscale image vector<vec4i> Lines;cv::houghlinesp (result_ line,lines,1,cv_pi/180,80,50,10); for (int i = 0; I < lines.size (); i++) {line (RESULT_LINE,CV::P oint (lines[i][0],lines[i][1]), CV::P oint (lines[i][2],lines[i][3]), Scalar (0,0,0), 2,8,0);} Cv::namedwindow ("line"); Cv::imshow ("line", Result_line);//waitkey (0);////////////////////////////////////////// STD::VECTOR&LT;STD::VECTOR&LT;CV::P oint>>::const_ Iterator itc_rec= Contours.begin ()//while (Itc_rec!=contours.end ())//{//cv::rect r0= cv::boundingrect (Cv::Mat (* ( ITC_REC));//cv::rectangle (result,r0,cv::scalar (0), 2);//++itc_rec;//}//cv::namedwindow ("Some Shape descriptors") ;//cv::imshow ("Some Shape descriptors", result); Cvbox2d end_rage2d; cvpoint2d32f Rectpoint[4];  Cvmemstorage *storage = cvcreatememstorage (0);     Open memory space cvseq* contour = NULL; The CVSEQ type holds all pixel values for the detected contour edges of the image, the structure of the coordinate value features in the form of a chain cvfindcontours (psrcimage, storage, &contour, sizeof (cvcontour), cv_ Retr_ccomp, Cv_chain_approx_none);//This function optional parameter also has a lot for (; contour; contour = contour->h_next)//If contour is not empty, it means to find aMore than one contour, so that the wording only shows a contour//such as change to for (; contour; contour = contour->h_next) can display multiple profiles at the same time {end_rage2d = CvMinAreaRect2 (contour); Substituting CvMinAreaRect2 This function obtains the smallest bounding rectangle here has been obtained the angle of the object being measured, width, height, and midpoint sitting punctuation in the structure of the cvbox2d type,//main work basically ended. for (int i = 0;i< 4;i++) {//cvarr* s= (cvarr*) &result;//cvline (s,cvpointfrom32f (rectpoint[i)), cvPointFrom32f ( rectpoint[(i+1)%4]), Cv_g (0,0,255), 2); line (result,cvpointfrom32f (rectpoint[i)), cvpointfrom32f (rectpoint[(i+1)%4 ]), Scalar (125), 2);}      Cvboxpoints (end_rage2d,rectpoint); Std::cout << "angle:\n" << (float) end_rage2d.angle << Std::endl; Measured object rotation angle}cv::imshow ("Lalalal", result); Cv::waitkey (); return 0;}


This is the original implementation of the Code of the blog post:

http://blog.csdn.net/wangyaninglm/article/details/41864251

Reference documents:

http://blog.csdn.net/z397164725/article/details/7248096

http://blog.csdn.net/fdl19881/article/details/6730112

http://blog.csdn.net/mine1024/article/details/6044856

OpenCV contour detection to calculate object rotation angle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.