Skip to content
shimat edited this page Oct 23, 2019 · 4 revisions

This page shows methods for accessing Mat's pixel.

Get/Set (slow)

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 <- B
        mat.Set<Vec3b>(y, x, color);
    }
}

GenericIndexer (reasonably 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 <- B
        indexer[y, x] = color;
    }
}

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 <- B
        indexer[y, x] = color;
    }
}