Building .NET Barcode Reader with OpenCV and DBR 5.2

OpenCV is written in C++.  If you install OpenCV library on Windows, you will see OpenCV officially provides wrappers for Python and Java but not for C#. Fortunately, there are many .NET open source projects for wrapping OpenCV C++ APIs, and thus we don’t need to write a wrapper from scratch. In this post, I will share how to use OpenCV library and Dynamsoft Barcode Reader SDK to create a .NET barcode reader app on Windows.


.NET Barcode Reader with OpenCV

I tried difference open source projects and finally decided to use OpenCvSharp which is continuously maintained by open source community.

Install OpenCvSharp and Dynamsoft Barcode Reader via Package Manager in Visual Studio. Tools >  NuGet Package Manager > Package Manager Console:

PM > Install-Package OpenCvSharp3-AnyCPU
PM> Install-Package Dynamsoft.DotNet.Barcode

Create a video capture object:

VideoCapture capture = new VideoCapture(0);

Get a video frame:

Mat image = capture.RetrieveMat();

Render the frame in a Window:

Cv2.ImShow("video", image);

Break the infinite loop when pressing ‘ESC’ key:

int key = Cv2.WaitKey(20);
// 'ESC'
if (key == 27)

Create a barcode reader object:

BarcodeReader reader = new BarcodeReader("t0068MgAAALLyUZ5pborJ8XVc3efbf4XdSvDAVUonA4Z3/FiYqz1MOHaUJD3d/uBmEtXVCn9fw9WIlNw6sRT/DepkdvVW4fs=");

To recognize barcodes, you can use DecodeBuffer() function. However, the type of the first parameter is byte[]. Now the biggest problem is how we can make the function work with Mat type.

Get the data pointer, width, height and element size as follows:

IntPtr data = image.Data;
int width = image.Width;
int height = image.Height;
int elemSize = image.ElemSize();
int buffer_size = width * height * elemSize;

Copy the data to a byte array:

using System.Runtime.InteropServices;
byte[] buffer = new byte[buffer_size];
Marshal.Copy(data, buffer, 0, buffer_size);

Decode the buffer and return barcode results:

BarcodeResult[] results = reader.DecodeBuffer(buffer, width, height, width * elemSize, ImagePixelFormat.IPF_RGB_888);
if (results != null)
    Console.WriteLine("Total result count: " + results.Length);
    foreach (BarcodeResult result in results)

Build and run the program:

.NET barcode reader with OpenCV

API References

Source Code