OpenCVSharpグラデーションをつけた線を引く

コンピュータ

線の色にグラデーションをつけてみました。

ソースコード

using OpenCvSharp;

namespace console3;

class Program1
{
    static double GetDistance(int x1, int y1, int x2, int y2)
    {
        int xa = x1 - x2;
        int ya = y1 - y2;
        return Math.Sqrt(Math.Pow(xa, 2)+Math.Pow(ya, 2));
    }
   static void DrawGradationLine(ref Mat mat, int x1, int y1, int x2, int y2, ref Scalar c1, ref Scalar c2)
    {
        int dx = Math.Abs(x2-x1);
        int dy = Math.Abs(y2-y1);
        int sx = (x1 < x2) ? 1 : -1;
        int sy = (y1 < y2) ? 1 : -1;
        int err = dx - dy;

        double dc = GetDistance(x1, y1, x2, y2);

        while(true)
        {
            double dcc = GetDistance(x1, y1, x2, y2);
            double dc1 = dcc / dc;
            double dc2 = 1.0 - dc1;

            var pic = mat.At<Vec4b>(y1, x1);
            pic[0] = (byte)(c1[0] * dc1 + c2[0] * dc2);
            pic[1] = (byte)(c1[1] * dc1 + c2[1] * dc2);
            pic[2] = (byte)(c1[2] * dc1 + c2[2] * dc2);
            pic[3] = 255;
            mat.Set<Vec4b>(y1, x1, pic);

            if ((x1 == x2) && (y1 == y2)) break;
            int e2 = 2 * err;
            if (e2 > dy)
            {
                err = err - dy;
                x1 = x1 + sx;
            }
            if (e2 < dx)
            {
                err = err + dx;
                y1 = y1 + sy;
            }
        }
    }
    static void Main()
    {
        int width = 300;
        int height = 300;
        var mat = new Mat(width, height, MatType.CV_8UC4);

        Cv2.Rectangle(mat, new OpenCvSharp.Rect(0, 0, width, height), new Scalar(255,255,255,255), -1);

        var color1 = new Scalar(0, 0, 0, 255);
        var color2 = new Scalar(255, 255, 255, 255);
        DrawGradationLine(ref mat, 10, 10, 290, 290, ref color1, ref color2);
        DrawGradationLine(ref mat, 10, 11, 290, 291, ref color1, ref color2);
        DrawGradationLine(ref mat, 10, 12, 290, 292, ref color1, ref color2);
        DrawGradationLine(ref mat, 10, 13, 290, 293, ref color1, ref color2);
        DrawGradationLine(ref mat, 10, 14, 290, 294, ref color1, ref color2);

        Cv2.ImShow("Result", mat);
        Cv2.WaitKey();
    }
}

実行結果

コメント