#include <opencv2/opencv.hpp> #include

using namespace cv; using namespace std;

int main(int argc, char** argv) { int center = 320;

// 打开摄像头,图像尺寸640*480(长*高),opencv存储值为480*640(行*列)
VideoCapture cap(0);
Mat frame, gray, dst;
while (1)
{
    cap >> frame;
    // 转化为灰度图
    cvtColor(frame, gray, COLOR_BGR2GRAY);
    // 大津法二值化
    threshold(gray, dst, 0, 255, THRESH_OTSU);
    // 膨胀,白区域变大
    dilate(dst, dst, Mat(), Point(-1, -1), 2);
    // 腐蚀,白区域变小
    // dst = erode(dst, Mat(), iterations=6);
    imshow('dst', dst);
    // 单看第400行的像素值
    Mat color = dst.row(400);
    // 找到白色的像素点个数
    int white_count = countNonZero(color == 255);
    // 找到白色的像素点索引
    int white_count_judge = countNonZero(color == 0); //利用这个变量来查找摄像头是否观察到黑色
    if (white_count_judge == 640)
    {
        cout << '黑色像素点为0' << endl;
    }
    else
    {
        Mat white_index;
        findNonZero(color == 255, white_index);
        // 防止white_count=0的报错
        if (white_count == 0)
        {
            white_count = 1;
        }
        // 找到白色像素的中心点位置
        center = (white_index.at<Point>(0).x + white_index.at<Point>(white_count - 1).x) / 2;
        int direction = center - 320;
        cout << direction << endl;
        // 计算出center与标准中心点的偏移量
    }
    if (waitKey(1) == 'q')
    {
        break;
    }
}

// 释放清理
cap.release();
destroyAllWindows();
return 0;

}

OpenCV 摄像头图像处理:识别黑色区域并计算中心点偏移量

原文地址: https://www.cveoy.top/t/topic/oyPE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录