Search code examples
c#videodirectshowdirectshow.net

Image needs to flip after creating a image from IntPtr buffer


I am trying to get image from webcam using DirectShow filters.
I want to show that image on PictureBox.
For that I have to rotate that image.

Code Sample:

public int BufferCB(double sampleTime, IntPtr pbuffer, int bufferLen)
{
    if (pbuffer == IntPtr.Zero || bufferLen == 0) return 0;
    var timeStamp = TimeSpan.FromSeconds(sampleTime);
    var image = new Bitmap(_videoResolution.Width, _videoResolution.Height, _stride, PixelFormat.Format24bppRgb, pbuffer);
    image.RotateFlip(RotateFlipType.Rotate180FlipX);
    RaiseFrameGrabbedEvent(image, timeStamp, pbuffer);
    return 0;
}

Is there any way to avoid that rotation.


Solution

  • You need to flip the image because normal order of rows in video RGB formats is reverse, that is bottom to top images. Bitmap class constructor takes image rows in top to bottom order.

    You can load flipped image and correct it by image.RotateFlip call.

    Or, you can load image to Bitmap instance row by row, feeding them in reverse order. Perhaps it can also work out at once if you provide negative stride and respective offset for the first row (some APIs accept this, other don't).

    Or, you can setup Sample Grabber to use RGB format with negative stride, in which case grabber buffers will have correct row order, however this requires that there is certain support for such RGB format in your pipeline, which is not likely.

    Eventually, you in most cases you will have to do the flipping either the way you do it now, or by loading the image data to bitmap as I mentioned above.