OpenCV 2.3:将Mat转换为RGBA像素阵列 [英] OpenCV 2.3: Convert Mat to RGBA pixel array

查看:1157
本文介绍了OpenCV 2.3:将Mat转换为RGBA像素阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用OpenCV从网络摄像头抓取帧,并使用SFML在窗口中显示它们。



VideoCapture以OpenCV的Mat格式返回帧。为了显示帧,SFML需要一个其uint8格式的一维像素阵列,它(根据我的意思)可以和uchar互换。这个数组期望表示每像素RGBA 32位。



所以,我有一个uchar数组,我循环遍历Mat数据并复制每个像素: / p>

  VideoCapture cap(0); 
垫框架;
cap>>帧;

uchar * camData = new uchar [640 * 480 * 4];
uchar * pixelPtr = frame.data;
for(int i = 0; i {
for(int j = 0; j
camData [i * frame.cols + j + 2] = pixelPtr [i * frame.cols + j + 0]; // B
camData [i * frame.cols + j + 1] = pixelPtr [i * frame.cols + j + 1]; // G
camData [i * frame.cols + j + 0] = pixelPtr [i * frame.cols + j + 2]; // R
camData [i * frame.cols + j + 3] = 255;

}
}
img.LoadFromPixels(640,480,camData); //将像素加载到SFML中用于显示的图像对象

不幸的是,这不工作。在这个循环中的东西是错误的,因为当我加载和显示camData的结果图像加扰。



至于我可以辨别,我的数学在循环是错误的



任何想法?

  VideoCapture cap(0) ; 
垫框架;
cap>>帧;

uchar * camData = new uchar [frame.total()* 4];
Mat continuousRGBA(frame.size(),CV_8UC4,camData);
cv :: cvtColor(frame,continuousRGBA,CV_BGR2RGBA,4);
img.LoadFromPixels(frame.cols,frame.rows,camData);


I am attempting to use OpenCV to grab frames from a webcam and display them in a window using SFML.

VideoCapture returns frames in OpenCV's Mat format. To display the frames, SFML requires a 1D array of pixels in its uint8 format, which (as far as I can tell) is interchangeable with uchar. This array is expected to represent 32 bits per pixel RGBA.

So, I have a uchar array, and I'm looping over the Mat data and copying each pixel:

VideoCapture cap(0);
Mat frame;
cap >> frame;

uchar* camData = new uchar[640*480*4];
uchar* pixelPtr = frame.data;
for(int i = 0; i < frame.rows; i++)
{
    for(int j = 0; j < frame.cols; j++)
    {
        camData[i*frame.cols + j + 2] = pixelPtr[i*frame.cols + j + 0]; // B
        camData[i*frame.cols + j + 1] = pixelPtr[i*frame.cols + j + 1]; // G
        camData[i*frame.cols + j + 0] = pixelPtr[i*frame.cols + j + 2]; // R
        camData[i*frame.cols + j + 3] = 255;

    }
}
img.LoadFromPixels(640, 480, camData); //Load pixels into SFML Image object for display

Unfortunately, this doesn't quite work. Something in that loop is wrong, as the resulting image when I load and display camData is scrambled.

As far as I can discern, either my math in the loop is wrong so the pixels are being assigned wrong, or the Mat data is in some format other than BGR.

Any ideas?

解决方案

OpenCV can do all job for you:

VideoCapture cap(0);
Mat frame;
cap >> frame;

uchar* camData = new uchar[frame.total()*4];
Mat continuousRGBA(frame.size(), CV_8UC4, camData);
cv::cvtColor(frame, continuousRGBA, CV_BGR2RGBA, 4);
img.LoadFromPixels(frame.cols, frame.rows, camData);

这篇关于OpenCV 2.3:将Mat转换为RGBA像素阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆