JavaCV 从视频捕获中显示彩色图像

JavaCV Display image in color from video capture

我无法显示来自相机的图像。我使用 VideoCapture 并且当我尝试以灰度显示图像时它工作完美,但是当我尝试以彩色显示图像时我得到类似的东西: link 我的部分源代码:

public void CaptureVideo()
{
    VideoCapture videoCapture = new VideoCapture(0);
    Mat frame = new Mat();

    while (videoCapture.isOpened() && _canWorking)
    {
        videoCapture.read(frame);

        if (!frame.empty())
        {
            Image img = MatToImage(frame);
            videoView.setImage(img);
        }

        try { Thread.sleep(33); } catch (InterruptedException e) { e.printStackTrace(); }
    }
    videoCapture.release();
}

private Image MatToImage(Mat original)
{
    BufferedImage image = null;
    int width = original.size().width(), height = original.size().height(), channels = original.channels();
    byte[] sourcePixels = MatToBytes(original, width, height, channels);

    if (original.channels() > 1)
    {
        image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    }
    else
    {
        image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
    }
    final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    System.arraycopy(sourcePixels, 0, targetPixels, 0, sourcePixels.length);

    return SwingFXUtils.toFXImage(image, null);
}

private byte[] MatToBytes(Mat mat, int width, int height, int channels)
{
    byte[] output = new byte[width * height * channels];
    UByteRawIndexer indexer = mat.createIndexer();

    int i = 0;
    for (int j = 0; j < mat.rows(); j ++)
    {
        for (int k = 0; k < mat.cols(); k++)
        {
            output[i] = (byte)indexer.get(j,k);
            i++;
        }
    }
    return  output;
}

谁能告诉我我做错了什么?我是图像处理的新手,我不明白为什么它不起作用。

好的。我解决这个问题。 解决方案:

 byte[] output = new byte[_frame.size().width() * _frame.size().height() * _frame.channels()];
    UByteRawIndexer indexer = mat.createIndexer();

    int index = 0;
    for (int i = 0; i < mat.rows(); i ++)
    {
        for (int j = 0; j < mat.cols(); j++)
        {
            for (int k = 0; k < mat.channels(); k++)
            {
                output[index] = (byte)indexer.get(i, j, k);
                index++;
            }
        }
    }
    return  output;