【问题标题】:OpenCV Access RGB values in a MAT objectOpenCV 访问 MAT 对象中的 RGB 值
【发布时间】:2014-09-10 23:54:36
【问题描述】:

我正在尝试使用 OpenCV 从网络摄像头中抓取帧并将其转换为 aHSV(Hue,Saturation,Value) Mat 对象并对其设置阈值。

当我打印阈值图像像素值时,它给我所有像素的 [0,0,0],即使是黑色像素值也是 [0,0,0]。 如果所选像素为黑色,我需要进行一些计算;如何访问像素值?。

    imgOriginal=frame from camera 


    Mat imgHSV;

    cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV

    Mat imgThresholded;
    inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image

    //morphological opening (remove small objects from the foreground)
    erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
    dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); 

    //morphological closing (fill small holes in the foreground)
    dilate( imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); 
    erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );


    //************************************



    std::vector<cv::Vec3b> pixels(imgThresholded.rows * imgThresholded.cols);
    cv::Mat m(imgThresholded.rows, imgThresholded.cols, CV_8UC3, &pixels[0]);
    imgThresholded.copyTo(m);


    for(int i =0;i<1000;i++)
    cout<<pixels[0];
    if(pixels[0][0]==black)
    // do some calculations!

【问题讨论】:

    标签: c++ opencv image-processing


    【解决方案1】:
    for(int i =0;i<1000;i++)
        cout<<pixels[0];
    

    只会打印第一个像素 1000 次。 我想你的意思是:

    Vec3b black(0, 0, 0);
    
    for(int i =0;i<1000;i++)
    {
        cout << pixels[i];
        if pixels[i] == black)
        {
           /* ... */
        }
    }
    

    但是为什么要麻烦将像素复制到 std::vector 呢?你可以这样做

    Vec3b black(0, 0, 0);
    
    Mat img(imgThresholded); // just to make a short name
    
    for(int y = 0; y < img.rows; ++y)
    {
        Vec3b* row = img.ptr<Vec3b>(y);
        for(int x = 0; x < img.cols; ++x)
        {
            Vec3b& pixel = row[x];
            if(pixel == black)
            {
                /* ... */
            }
        }
     }
    

    【讨论】:

    • 感谢它的工作...从 Vec3b 我如何提取 R G B 值.... int R= int G= int B=
    • 如果我的代码中的img是RGB,那么R=pixel[2], G=pixel[1], B=pixel[0]
    • 什么是变量类型?诠释?
    • uchar R = pixel[2];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2010-12-23
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多