我使用lwjgl在OpenGL中渲染图像,现在我想将Framebuffer的内容作为RGB存储在OpenCV矩阵中。为了使shure一切正常,我在jFrame的Panel上显示捕获的图像。 但继承人的问题是:虽然显示存储的jpegs一切看起来都很好,但如果我试图显示捕获的Framebuffer我只看到条纹!
以下是截图的代码:
public Mat takeMatScreenshot()
{
int width = m_iResolutionX;
int height = m_iResolutionY;
int pixelCount = width * height;
byte[] pixelValues = new byte[ pixelCount * 3 ];
ByteBuffer pixelBuffer = BufferUtils.createByteBuffer( width * height * 3 );
glBindFramebuffer( GL_FRAMEBUFFER, m_iFramebuffer );
glReadPixels( 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixelBuffer );
for( int i = 0; i < pixelCount; i++ )
{
int line = height - 1 - (i / width); // flipping the image upside down
int column = i % width;
int bufferIndex = ( line * width + column ) * 3;
pixelValues[bufferIndex + 0 ] = (byte)(pixelBuffer.get(bufferIndex + 0) & 0xFF) ;
pixelValues[bufferIndex + 1 ] = (byte)(pixelBuffer.get(bufferIndex + 1) & 0xFF);
pixelValues[bufferIndex + 2 ] = (byte)(pixelBuffer.get(bufferIndex + 2) & 0xFF);
}
Mat image = new Mat(width, height, CvType.CV_8UC3);
image.put(0, 0, pixelValues);
new ImageFrame(image);
return image;
}
这里是显示Mat的代码:
public static Image toBufferedImage(Mat m)
{
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( m.channels() == 3 )
type = BufferedImage.TYPE_3BYTE_BGR;
if( m.channels() == 4 )
type = BufferedImage.TYPE_4BYTE_ABGR;
int bufferSize = m.channels()*m.cols()*m.rows();
byte [] b = new byte[bufferSize];
m.get( 0, 0, b ); // get all the pixels
BufferedImage image = new BufferedImage( m.cols(), m.rows(), type );
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
return image;
}
如果有任何人可以帮助我的话会很棒! 干杯!
答案 0 :(得分:0)
哦不!捂脸! OpenCV Mat对象的构造函数是:Mat(rows,cols)! 所以正确的解决方案是:
Mat image = new Mat(height, width, CvType.CV_8UC3);
image.put(0, 0, pixelValues);