JavaCV以视频捕获方式显示彩色图像

时间:2017-08-26 16:27:48

标签: opencv image-processing javacv

我从相机显示图像时遇到问题。我使用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;
}

任何人都可以告诉我我做错了什么?我是图像处理方面的新手,我不明白为什么它不起作用。

1 个答案:

答案 0 :(得分:0)

确定。我解决了这个问题 解决方案:

 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;