Mike from PSG
Mike from PSG

Reputation: 5764

OpenCV Convert Bitmap to Mat

I'm working with c# and OpenCV. I have a Bitmap that I want to write as a frame of video using the VideoWriter provided by OpenCV. I've done this in Python so know it will work. I just need the conversion step from Bitmap to Mat.

My (partial) code looks roughly like this...

VideoWriter video = new VideoWriter(filename, fps, frameSize, false);
Bitmap image = SomethingReturningABitmap();
// NEED CONVERT FROM Bitmap to Mat
Mat frame = new Mat();
video.Write(frame);

Upvotes: 7

Views: 10566

Answers (1)

Tabrock
Tabrock

Reputation: 1169

I'm using the Bitmap Converter OpenCV Extensions to convert my Bitmap to a Mat object in memory.

PSTK ps = new PSTK();
Image img = ps.CaptureScreen();    
Bitmap bmpScreenshot = new Bitmap(img);
image = BitmapConverter.ToMat(bmpScreenshot);

One could also do the below but then you will incur significant overhead for writing and reading the data from disk.

myBitmap.Save("TempFile.PNG");
Mat myMatImage = CvInvoke.Imread("TempFile.PNG");

I wanted to see what the difference looked like, roughly. I was processing a 1920x1080 screen cast of my desktop for 500 frames using each method and here's what I found.

On average, for the Bitmap.Save/Cv2.ImRead method, it took 0.1403 seconds per frame. On average, for the Bitmap Converter method, it took 0.09604 seconds per frame. It takes roughly 50% longer to save and re-read the file using my home desktop machine. Core I7 2nd gen, 16GB RAM.

Upvotes: 6

Related Questions