用OpenCV计算到红点的距离

Calculate the distance to a red point with opencv

本文关键字:距离 OpenCV 计算      更新时间:2023-10-16

我是openCV的新手。刚刚设法安装并将其设置为Visual2013。我用笔记本电脑相机的实时流示例对其进行了测试。现在,我想通过网络摄像头与将位于屏幕中间的红色激光点(Live_stream)计算距离。告诉我从哪里开始?我知道我必须从屏幕中间找到R(红色)像素,但我不知道该怎么做以及可以使用什么功能。请问吗?来自网络摄像头的实时流如下所示:

   #include "opencv2/highgui/highgui.hpp"
   #include <opencv2/objdetect/objdetect.hpp>
   #include <opencv2/imgproc/imgproc.hpp>
   #include <iostream>
   #include <vector>
   #include <stdio.h>
 int main()
 {
 //Data Structure to store cam.
 CvCapture* cap=cvCreateCameraCapture(0);
 //Image variable to store frame
 IplImage* frame;
 //Window to show livefeed
 cvNamedWindow("Imagine Live",CV_WINDOW_AUTOSIZE);
while(1)
{
//Load the next frame
frame=cvQueryFrame(cap);
//If frame is not loaded break from the loop
if(!frame)
    printf("nno");;
//Show the present frame
cvShowImage("Imagine Live",frame);
//Escape Sequence
char c=cvWaitKey(33);
//If the key pressed by user is Esc(ASCII is 27) then break out of the loop
if(c==27)
   break;
}
//CleanUp
cvReleaseCapture(&cap);
cvDestroyAllWindows();
}

您的红点很可能会在相机流中显示为全白色,所以我建议

  1. 使用cvtColor()
  2. 转换为灰度
  3. 使用 threshold()的阈值,用于参数,使用阈值= 253,maxval = 255和mode thresh_binary。那应该给你一个全黑的图像,带有激光器所在的小白点。
  4. 然后,您可以使用findContours()在图像中找到点。获取轮廓的boundingRect(),然后您可以计算其中心以获取点的精确坐标。

也已经提到,请勿使用弃用的C API,而是使用C API。