OpenCV-从相机设备获取像素数据

OpenCV - getting pixel data from camera device

本文关键字:像素 像素数 数据 获取 相机 OpenCV-      更新时间:2023-10-16

我使用的是OpenCV 2.4.6。我在网上找到了一些从相机上获取相框的例子。效果很好(它把我丑陋的脸显示在屏幕上)。然而,我绝对无法从帧中获取像素数据。我在这里找到了一些主题:http://answers.opencv.org/question/1934/reading-pixel-values-from-a-frame-of-a-video/但这对我不起作用。

这是代码——在评论的部分,我指出了错误的地方。

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
int main() {
    int c;
    IplImage* img;
    CvCapture* capture = cvCaptureFromCAM(1);
    cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE);
    while(1) {
        img = cvQueryFrame(capture);
        uchar* data = (uchar*)img->imageData; // access violation
        // this does not work either
        //Mat m(img);
        //uchar a = m.data[0]; // access violation
        cvShowImage("mainWin", img);
        c = cvWaitKey(10);
        if(c == 27)
            break;
    }
}

你能给我一些建议吗?

我建议使用较新的Mat结构,而不是IplImage,因为您的问题带有C++标记。对于您的任务,您可以使用Matdata成员-它指向内部Mat存储。例如Mat img; uchar* data = img.data;。以下是的完整示例

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
int main() {
    int c;
    Mat img;
    VideoCapture capture(0);
    namedWindow("mainWin", CV_WINDOW_AUTOSIZE);
    bool readOk = true;
    while(capture.isOpened()) {
        readOk = capture.read(img);
        // make sure we grabbed the frame successfully 
        if (!readOk) {
            std::cout << "No frame" << std::endl;
            break;
        }
        uchar* data = img.data; // this should work
        imshow("mainWin", img);
        c = waitKey(10);
        if(c == 27)
            break;
    }
}