[英]OpenCV - Create CV_8UC3 (3 channel) Mat from BGRA output
I have an AVCaptureSession
which output the CMSampleBuffer
with BGRA
pixels. 我有一个AVCaptureSession
输出带有BGRA
像素的CMSampleBuffer
。 I'm trying to create Mat
object only from BGR
, in the most efficient way, using the data pointers . 我正在尝试使用数据指针以最有效的方式仅从BGR
创建Mat
对象。
CVPixelBufferLockBaseAddress(imageBuffer,0);
void *baseaddress = CVPixelBufferGetBaseAddress(imageBuffer);
CGRect videoRect = CGRectMake(0.0f, 0.0f, CVPixelBufferGetWidth(imageBuffer), CVPixelBufferGetHeight(imageBuffer));
size_t bytesPerRow = (((CVPixelBufferGetBytesPerRow(imageBuffer)
cv::Mat frame(videoRect.size.height, videoRect.size.width,CV_8UC3 , baseaddress, bytesPerRow);
But it dosen't seems to work. 但这似乎没有用。 Any suggestions? 有什么建议么?
Data in a Mat
must be contiguous (with eventually some extra padding at the end of each row). Mat
数据必须是连续的(最终,每行的末尾要有一些额外的填充)。
Your data are like: 您的数据如下:
row 0: B G R A B G R A ... B G R A <padding>
row 1: B G R A B G R A ... B G R A <padding>
...
And you can't read data like: 而且您无法读取以下数据:
row 0: B G R - B G R - ... B G R - <padding>
row 1: B G R - B G R - ... B G R - <padding>
...
What you can do is wrap your BGRA data in a CV_8UC4
matrix (ie build a matrix header on your data): 您可以做的是将BGRA数据包装在CV_8UC4
矩阵中(即在数据上构建矩阵头):
cv::Mat frameBGRA (height, width, CV_8UC4, buffer);
and then copy only the bytes you need: 然后仅复制所需的字节:
cv::Mat frameBGR;
cv::cvtColor(frameBGRA, frameBGR, cv::COLOR_BGRA2BGR);
Another solution would be to manually copy only the needed data into your BGR matrix (4 is the number of channels in BGRA): 另一种解决方案是仅将所需数据手动复制到BGR矩阵中(4是BGRA中的通道数):
// Create the BGR (3 channel) matrix
cv::Mat3b frameBGR(height, width);
for(int r = 0; r < height; ++r) {
for(int c = 0; c < width; ++c) {
// Copy only BGR
frameBGR(r,c)[0] = buffer((r * c * 4) + (c * 4) + 0); // Blue
frameBGR(r,c)[1] = buffer((r * c * 4) + (c * 4) + 1); // Green
frameBGR(r,c)[2] = buffer((r * c * 4) + (c * 4) + 2); // Red
// Don't consider Alpha channel
// buffer((r * c * 4) + (c * 4) + 3); // Alpha
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.