OpenCvSharp Mat.Set does not give expected result

Question:

Note: These questions are about OpenCVSharp v3.1.20160114.

Question 1.

As in below example, I expect a red square but result is a black with weird color stripes.

    public void TestMethod()
    {
        var mat = new Mat(300, 300, MatType.CV_8UC3, Scalar.White);
        for (int i = 100; i < 200; i++)
            for (int j = 100; j < 200; j++)
                mat.Set(i, j, Scalar.Red);
        Cv2.ImShow("red square", mat);
        Cv2.WaitKey();
    }

Result

enter image description here

I edit Scalar.Red to 16711680 (#FF0000 in integer) and it works. Is this expected behavior? or a bug in OpenCvSharp?

Question 2.

why multiple-vertical-stripe-colors at the right side of the box? As I turned to red square, It still has yellow color at the right side.

Weired yellow strip at the right side

enter image description here

Question 3.

Python can access each channel and set value(color) as below.

mat.itemset((pixel[1], pixel[0], 2), 255) # Red channel to 255. 

Is there any similar method in OpenCvSharp?

Asked By: Youngjae

||

Answers:

I think the main problem is that you’re trying to set the color of a 3 channel image at once. If you follow the code in the URL or the snippet below I think all 3 of your questions are answered.

I followed these instructions and didn’t have any problems.
https://github.com/shimat/opencvsharp/wiki/Accessing-Pixel

//Option1
var mat = new Mat(300, 300, MatType.CV_8UC3, Scalar.White);
for (int i = 100; i < 200; i++)
    for (int j = 100; j < 200; j++)
    {
        Vec3b color = mat.Get<Vec3b>(i, j);
        color.Item0 = 0;
        color.Item1 = 0;
        color.Item2 = 255;
        mat.Set<Vec3b>(i, j, color);
        //mat.Set(i, j, Scalar.Red);
    }
Cv2.ImShow("red square", mat);
Cv2.WaitKey();
}

//Option2
var mat = new Mat(300, 300, MatType.CV_8UC3, Scalar.White);
var indexer = mat.GetGenericIndexer<Vec3b>();
for (int i = 100; i < 200; i++)
    for (int j = 100; j < 200; j++)
    {
        Vec3b color = mat.Get<Vec3b>(i, j);
        color.Item0 = 0;
        color.Item1 = 0;
        color.Item2 = 255;
        indexer[i, j] = color;
    }
Cv2.ImShow("red square", mat);
Cv2.WaitKey();
}

This code shows two of the three options in the URL above that document pixel level access in OpenCvSharp.

Answered By: Darren
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.