Search code examples
opencvimage-processingjavacv

JavaCV Display image in color from video capture


I have trouble with display image from camera. I using VideoCapture and when I try display image in grayscale it's works perfect, but when I try display image in color that I get something like that: link Part of my source code:

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;
}

Anyone can tell me what I doing wrong? I'm new in image processing and I don't get why it's not working.


Solution

  • Ok. I resolve this. Solution:

     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;