Skip to content

Convert screenshot to OpenCV Mat #36

Description

@rxerox

Hi,

First, many thanks for this code/project.

Do you have a sample code to convert the screencapture to an OpenCV image ? Or a link to do this ?

Thanks.

Activity

  1. DarthAffe commented on Jul 15, 2024

    @DarthAffe
    Owner

    hey, this is just based on the docs and not tested. it assumes that emgu.cv is used and opencv has BGRA as internal color format (I couldn't verify that).

    IImage image = default; // get your image here
    Mat material = new Mat(image.Height, image.Width, DepthType.Cv8U, image.ColorFormat.BytesPerPixel);
    image.CopyTo(new Span<byte>((void*)material.DataPointer, image.Width * image.Height * image.ColorFormat.BytesPerPixel));

    or

    RefImage<ColorBGRA> image = default; // get your image here
    Mat material = new Mat(image.Height, image.Width, DepthType.Cv8U, ColorBGRA.ColorFormat.BytesPerPixel);
    image.CopyTo(new Span<ColorBGRA>((void*)material.DataPointer, image.Width * image.Height));

    I'm currently working on abstracting this kind of conversion a bit more to make it easier in the future.

  2. rxerox commented on Jul 17, 2024

    @rxerox
    Author

    Hi, nice and quick answer. Your right, I'am using emgu.cv, and I try your 2nd sample code : it's work fine.

    Again, many thanks ;)

  3. glasscake commented on Jun 17, 2025

    @glasscake

    hey, this is just based on the docs and not tested. it assumes that emgu.cv is used and opencv has BGRA as internal color format (I couldn't verify that).

    IImage image = default; // get your image here
    Mat material = new Mat(image.Height, image.Width, DepthType.Cv8U, image.ColorFormat.BytesPerPixel);
    image.CopyTo(new Span((void*)material.DataPointer, image.Width * image.Height * image.ColorFormat.BytesPerPixel));
    or

    RefImage image = default; // get your image here
    Mat material = new Mat(image.Height, image.Width, DepthType.Cv8U, ColorBGRA.ColorFormat.BytesPerPixel);
    image.CopyTo(new Span((void*)material.DataPointer, image.Width * image.Height));
    I'm currently working on abstracting this kind of conversion a bit more to make it easier in the future.

    Just for reference I got this code working with OpenCVSharp using the following:

    IImage<ColorBGRA> image = fullscreen.Image;
    Mat material = new Mat(image.Height, image.Width, MatType.CV_8UC4);
    image.CopyTo(new Span<ColorBGRA>((void*)material.DataPointer, image.Width * image.Height));
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions