First, get image pixels
1.1 Get/Set (missile)
Mat mat = new Mat("lenna.png", LoadMode.Color);
for (int y = 0; y < mat.Height; y++)
{
for (int x = 0; x < mat.Width; x++)
{
Vec3b color = mat.Get<Vec3b>(y, x);
byte temp = color.Item0;
color.Item0 = color.Item2; // B <- R
color.Item2 = temp; // R <- Bmat.Set<Vec3b>(y, x, color); }}Copy the code
1.2 GenericIndexer german-russian co-operation (fast)
Mat mat = new Mat("lenna.png", LoadMode.Color);
var indexer = mat.GetGenericIndexer<Vec3b>();
for (int y = 0; y < mat.Height; y++)
{
for (int x = 0; x < mat.Width; x++)
{
Vec3b color = indexer[y, x];
byte temp = color.Item0;
color.Item0 = color.Item2; // B <- R
color.Item2 = temp; // R <- Bindexer[y, x] = color; }}Copy the code
1.3 TypeSpecificMat (faster -)
Mat mat = new Mat("lenna.png", LoadMode.Color);
var mat3 = new Mat<Vec3b>(mat); // cv::Mat_<cv::Vec3b>
var indexer = mat3.GetIndexer();
for (int y = 0; y < mat.Height; y++)
{
for (int x = 0; x < mat.Width; x++)
{
Vec3b color = indexer[y, x];
byte temp = color.Item0;
color.Item0 = color.Item2; // B <- R
color.Item2 = temp; // R <- Bindexer[y, x] = color; }}Copy the code
Second, data conversion
2.1 Mat – > System. Drawing Bitmap
Mat mat = new Mat("foobar.jpg", ImreadModes.Color);
Bitmap bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
Copy the code
2.2 System. Drawing. The Bitmap – > Mat
Bitmap bitmap = new Bitmap("foobar.jpg");
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
Copy the code
2.3 Mat – > byte []
Mat mat = new Mat("foobar.jpg", ImreadModes.Color);
byte[] bytes1 = mat.ToBytes(".png");
byte[] bytes2;
Cv2.ImEncode(".jpg", mat, out bytes2);
Copy the code
2.4 byte [] – > Mat
byte[] imageData = System.IO.File.ReadAllBytes("foobar.jpg");
Mat colorMat = Mat.FromImageData(imageData, ImreadModes.Color);
Mat grayscaleMat = Mat.FromImageData(imageData, ImreadModes.GrayScale);
Mat alt = Cv2.ImDecode(imageData, ImreadModes.GrayScale);
Copy the code
If you feel good, just click three times. (Like + Favorites + follow)