c++ - 如何使用opencv从图像中找到标尺位置?

标签 c++ opencv pixel

我必须使用 opencv 从图像中找到标尺位置。我能够检测标尺的颜色(绿色)。如何从图像中读取所有像素并获取标尺的上下位置。

void findrulerPosition(cv::Mat image, int indx) {
std::stringstream ss;//create a stringstream
ss << indx;//add number to the stream

cv::Mat hsv;
cvtColor(image, hsv, CV_BGR2HSV);

String filename = OUTPUT_FOLDER + "hsv" + ss.str() + ".png";
imwrite(filename, hsv );

cv::Mat hsvbw;
inRange(hsv, cv::Scalar(30,0,0), cv::Scalar(80, 255, 255), hsvbw);
//inRange(hsv, cv::Scalar(12,255,255), cv::Scalar(23, 245, 255), hsvbw);
   //inRange(image, cv::Scalar(0,64,255), cv::Scalar(0, 207, 255), hsvbw);

filename = OUTPUT_FOLDER + "hsvbw" + ss.str() + ".png";
imwrite(filename, hsvbw );


vector<vector<Point> > contours;
findContours(hsvbw.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
cv::Mat dst = Mat::zeros(image.size(), image.type());
drawContours(dst, contours, -1, Scalar::all(255), CV_FILLED);

this->cmpddst &=  dst;
dst &= image;
this->cmpddst &=  image;

filename = OUTPUT_FOLDER + "cmpddst" + ss.str() + ".png";
imwrite(filename, this->cmpddst );


filename = OUTPUT_FOLDER + "dst" + ss.str() + ".png";
imwrite(filename, dst );

最佳答案

这是我所做的:

  1. 稍微改善了您的绿色范围,因为您没有检测到绿色 - 它检测了许多其他颜色。
  2. 在图像上找到轮廓。
  3. 找到面积大于 100 的等高线。
  4. 找出等高线的上点和低点。
  5. 画出这 2 个点。
Mat src = imread("input.png"), tmp;
cvtColor(src, tmp, CV_BGR2HSV_FULL);
inRange(tmp, Scalar(50, 50, 50), Scalar(70, 255, 255), tmp);

vector<vector<Point> > contours;
findContours(tmp, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

int upY = INT_MAX, lowY = 0, upX, lowX;
for (int i=0; i<contours.size(); i++)
{
    if (contourArea(contours[i]) > 100)
    {
        for (int j=0; j<contours[i].size(); j++)
        {
            if (contours[i][j].y > lowY)
            {
                lowY = contours[i][j].y;
                lowX = contours[i][j].x;
            }
            if (contours[i][j].y < upY)
            {
                upY = contours[i][j].y;
                upX = contours[i][j].x;
            }
        }

        cout << "low = (" << lowX << ", " << lowY << ")"<<  endl
             << "up  = (" << upX << ", " << upY << ")"<<  endl;
        break;
    }
}

circle(src, Point(lowX, lowY), 3, Scalar(255, 0, 255));
circle(src, Point(upX, upY), 3, Scalar(255, 0, 255));

imshow("Window", src);
waitKey();

结果如下:

enter image description here

关于c++ - 如何使用opencv从图像中找到标尺位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13809959/

相关文章:

c++ - 如何将视频文件作为输入传递给 NodeJS 中的子进程并接收帧/图像作为输出?

c++ - 在像素搜索算法中找不到错误

c - OpenCV中像素邻域差异的高效算法

c++ - 高完整性 C++ 规则 7.2.1 的基本原理是什么

c++ - 如何在 C 中包含第三方库?

c++ - 线程运行时间、cpu上下文切换和性能之间的关系

php - 像素绘制算法

c++ - 为什么使用 boost 会大大增加文件大小?

OpenCV VideoCapture 错误 : VIDIOC_REQBUFS: Inappropriate ioctl for device

opencv - 改进哈里斯角检测器的结果