1. 程式人生 > >【OpenCV】OpenCV輪廓檢測,計算物體旋轉角度

【OpenCV】OpenCV輪廓檢測,計算物體旋轉角度

OpenCV輪廓檢測,計算物體旋轉角度

效果還是有點問題的,希望大家共同探討一下

// FindRotation-angle.cpp : 定義控制檯應用程式的入口點。
//

// findContours.cpp : 定義控制檯應用程式的入口點。
//

#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")      
#pragma comment(lib,"opencv_imgproc2410d.lib")

#define PI 3.1415926

using namespace std;
using namespace cv;



int hough_line(Mat src)
{
 //【1】載入原始圖和Mat變數定義  
 Mat srcImage = src;//imread("1.jpg");  //工程目錄下應該有一張名為1.jpg的素材圖
 Mat midImage,dstImage;//臨時變數和目標圖的定義

 //【2】進行邊緣檢測和轉化為灰度圖
 Canny(srcImage, midImage, 50, 200, 3);//進行一此canny邊緣檢測
 cvtColor(midImage,dstImage, CV_GRAY2BGR);//轉化邊緣檢測後的圖為灰度圖

 //【3】進行霍夫線變換
 vector<Vec4i> lines;//定義一個向量結構lines用於存放得到的線段向量集合
 HoughLinesP(midImage, lines, 1, CV_PI/180, 80, 50, 10 );

 //【4】依次在圖中繪製出每條線段
 for( size_t i = 0; i < 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】顯示原始圖  
 imshow("【原始圖】", srcImage); 

 //【6】邊緣檢測後的圖 
 imshow("【邊緣檢測後的圖】", midImage); 

 //【7】顯示效果圖  
 imshow("【效果圖】", dstImage); 

 //waitKey(0); 

 return 0;  
}

int main()
{
 // Read input binary image

 char *image_name = "test.jpg";
 cv::Mat image = cv::imread(image_name,0);
 if (!image.data)
  return 0;

 cv::namedWindow("Binary Image");
 cv::imshow("Binary Image",image);


 
 // 從檔案中載入原圖  
    IplImage *pSrcImage = cvLoadImage(image_name, CV_LOAD_IMAGE_UNCHANGED);  
  
    // 轉為2值圖
  
  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 components
 std::vector<std::vector<cv::Point>> contours;
 cv::findContours(image, 
  contours, // a vector of contours 
  CV_RETR_EXTERNAL, // retrieve the external contours
  CV_CHAIN_APPROX_NONE); // retrieve all pixels of each contours

 // Print contours' length
 std::cout << "Contours: " << contours.size() << std::endl;
 std::vector<std::vector<cv::Point>>::const_iterator itContours= contours.begin();
 for ( ; itContours!=contours.end(); ++itContours) 
 {

  std::cout << "Size: " << itContours->size() << std::endl;
 }

 // draw black contours on white image
 cv::Mat result(image.size(),CV_8U,cv::Scalar(255));
 cv::drawContours(result,contours,
  -1, // draw all contours
  cv::Scalar(0), // in black
  2); // with a thickness of 2

 cv::namedWindow("Contours");
 cv::imshow("Contours",result);






 // Eliminate too short or too long contours
 int cmin= 100;  // minimum contour length
 int cmax= 1000; // maximum contour length
 std::vector<std::vector<cv::Point>>::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 image
 cv::Mat original= cv::imread(image_name);
 cv::drawContours(original,contours,
  -1, // draw all contours
  cv::Scalar(255,255,0), // in white
  2); // with a thickness of 2

 cv::namedWindow("Contours on original");
 cv::imshow("Contours on original",original);



 // Let's now draw black contours on white image
 result.setTo(cv::Scalar(255));
 cv::drawContours(result,contours,
  -1, // draw all contours
  cv::Scalar(0), // in black
  1); // with a thickness of 1
 image= cv::imread("binary.jpg",0);

 //imshow("lll",result);
 //waitKey(0);

 // testing the bounding box 
 //////////////////////////////////////////////////////////////////////////////
 //霍夫變換進行直線檢測,此處使用的是probabilistic Hough transform(cv::HoughLinesP)而不是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】進行邊緣檢測和轉化為灰度圖
 //Canny(result_line, tempimage, 50, 200, 3);//進行一此canny邊緣檢測
 //imshow("canny",tempimage);
 //waitKey(0);

 //cvtColor(tempimage,result_line, CV_GRAY2BGR);//轉化邊緣檢測後的圖為灰度圖
 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::Point(lines[i][0],lines[i][1]),cv::Point(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<std::vector<cv::Point>>::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);  //開闢記憶體空間


 CvSeq*      contour = NULL;    //CvSeq型別 存放檢測到的影象輪廓邊緣所有的畫素值,座標值特徵的結構體以連結串列形式

 cvFindContours( pSrcImage, storage, &contour, sizeof(CvContour),CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);//這函式可選引數還有不少



 for(; contour; contour = contour->h_next)  //如果contour不為空,表示找到一個以上輪廓,這樣寫法只顯示一個輪廓
  //如改為for(; contour; contour = contour->h_next) 就可以同時顯示多個輪廓
 { 

  End_Rage2D = cvMinAreaRect2(contour);  
  //代入cvMinAreaRect2這個函式得到最小包圍矩形  這裡已得出被測物體的角度,寬度,高度,和中點座標點存放在CvBox2D型別的結構體中,
  //主要工作基本結束。
  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;      //被測物體旋轉角度 
 
 }
 cv::imshow("lalalal",result);
 cv::waitKey();
 return 0;


}

--------------------------------------分割線 --------------------------------------

Taily老段的微信公眾號,歡迎交流學習

相關推薦

OpenCVOpenCV輪廓檢測計算物體旋轉角度

OpenCV輪廓檢測,計算物體旋轉角度 效果還是有點問題的,希望大家共同探討一下 // FindRotation-angle.cpp : 定義控制檯應用程式的入口點。 // // findContours.cpp : 定義控制檯應用程式的入口點。 /

js根據出生日期計算週歲年齡

/*根據出生日期算出年齡*/ function jsGetAge(strBirthday) { var returnAge; var strBirthdayArr = strBirthday.split("-"); var

Python設計一個演算法計算出n階乘中尾部零的個數

1.常見的思路:先求N的階乘,再計算零的個數。 (但是,時間消耗太大)    def trailingZeros( n):         S = 1         for i in range(1,n+1):             S = S * i        

ARTOOlkit讓標識卡顯示自己的旋轉角度

有很多不錯的東西,在已有的知識上補充自己的的學習水平。        我們這次要做的是,旋轉我們的標識卡,在螢幕上顯示出我們的旋轉角度。具體是我們利用glVertex()畫點函式,在標識卡上繪製出一個圓,然後利用atan(double x)函式來求旋轉角度,利用函式gl

opencv特徵點檢測方法--GFTTSIFTFASTSURF

一. 特徵點檢測方法總結 二.關於特徵點分析對比的相關論文 1.      有關特徵點:Shi-Tmoasi,SIFT,SURF 方法:基於opencv,通過RGB分解,比較特徵點的個數和魯棒性 2.      有關特徵點:FAST 方法:主要是

OpenCVOpenCV之calcHist() 計算直方圖

OpenCV 2.4.13 calcHist 通過影象計算直方圖 函式宣告如下:   void calcHist( const Mat* images, int nimages, const int* channels, Inpu

OpenCV影象模糊檢測

在專案中的一個環節用到了模糊檢測的相關內容 主要思想是先對原影象進行灰度化,然後用3x3的拉普拉斯運算元進行濾波處理 再計算處理後圖像的均值和方差,將方差當做模糊檢測的閾值選定標準即可。 相關的程式如

OpenCV森林火災檢測-1

運動檢測 其實就是檢測背景,對背景建模然後提取前景中運動的物體作為候選火災樣本。嘗試了兩種簡單的背景演算法:高斯背景建模和背景相減,還是背景相減的效果較好。以下是程式碼: //背景相減 void FireDetector:: CheckFireMove(IplIma

OpenCV角點檢測:Harris角點及Shi-Tomasi角點檢測

角點 特徵檢測與匹配是Computer Vision 應用總重要的一部分,這需要尋找影象之間的特徵建立對應關係。點,也就是影象中的特殊位置,是很常用的一類特徵,點的區域性特徵也可以叫做“關鍵特徵點”(keypoint feature),或“興趣點”(interest poi

OpenCVCanny 邊緣檢測

Canny 邊緣檢測演算法 1986年,JOHN CANNY 提出一個很好的邊緣檢測演算法,被稱為Canny編邊緣檢測器[1]。 Canny邊緣檢測根據對信噪比與定位乘積進行測度,得到最優化逼近運算元,也就是Canny運算元。類似與 LoG 邊緣檢測方法,也屬於先平滑後求導

OpenCV顯著區域檢測

寫在前面 最近在做畢設,題目是行人再識別。目前只是用行人區域的顏色直方圖進行匹配,效果比較不理想。老闆推薦加入顯著性檢測,然後就搞了搞。 環境 VS2015 OpenCV3.2 程式碼 Saliency_h // Saliency

OpenCVCanny邊緣檢測

五個步驟: 1.使用高斯濾波器對影象進行去噪 2.計算梯度 3.在邊緣上使用非最大抑制—NMS 4.在檢測道德邊緣上使用雙閾值去除假陽性 5.分析邊緣極其之間的連線,以保證保留真正的邊緣並消除不明顯的邊緣 import cv2 import nu

opencvOpencv在Ubuntu16中的code blocks的編譯配置

1. project->build options->compiler settings -> Compiler Flags : pick the "Have g++ follow the C++11 ISO C++ language standard[-std=c++11]"

4OpenCVOpenCV和RTSP的綜合研究

一、RTSP是什麼?用來幹什麼? RTSP(Real Time Streaming Protocol),RFC2326,實時流傳輸協議,是TCP/IP協議體系中的一個應用層協議,由哥倫比亞大學、網景和RealNetworks公司提交的IETF RFC標準。該協議定義了一對多應用程式如何有效地通過IP網路傳送多

翻譯OpenCV裡的畫圖方法

⚠️這個系列是自己瞎翻的,文法很醜,跳著跳著撿重要的部分翻,翻錯了不負責,就這樣。 ⚠️基於3.4.3,Drawing Functions in OpenCV,附原文。   目標  學會用OpenCV畫出不同的幾何圖形 你會

OpenCV神技——人臉檢測貓臉檢測

簡介   OpenCV是一個基於BSD許可(開源)發行的跨平臺計算機視覺庫,可以執行在Linux、Windows、Android和Mac OS作業系統上。它輕量級而且高效——由一系列 C 函式和少量 C++ 類構成,同時提供了Python、Ruby、MATLAB

AndroidOpenCV for Android配置 不使用OpenCV Manager

筆者版本: 名稱 版本 Android Studio 3.2 gradle 4.6 compileSdkVersion

分類 - OpenCV

專欄達人 授予成功建立個人部落格專欄

OpencvOpencv之Mat

Mat Mat的簡單使用 從實際出發,先看看他幹啥的,怎麼用。 一般我們用到Mat有兩個重要的用途: 1.儲存影象(其實影象可以看成一個高行寬列的一個矩陣) 2.儲存矩陣 先來看看Mat用於影象和矩陣的最基本操作,讀取一副影象,修改影象中某些畫素的值,最後顯示並儲存,建立矩陣

pythonopencv 利用電腦攝像頭捕獲影象並儲存

目標 利用筆記本的的內建攝像頭錄影並且儲存。 cv2.VideoCapture()、cv2.VideoWriter()、read()、write()的使用。 示例程式碼 python # -*- coding:utf-8-*- impo