Ejemplo n.º 1
0
        private void button6_Click(object sender, EventArgs e)
        {
            float[] x = new float[] { 0 };
            float[] y = new float[] { 0 };
            CLCalc.InitCL();
            if (!string.IsNullOrWhiteSpace(textBox1.Text) && !string.IsNullOrWhiteSpace(textBox2.Text))
            {
                x[0] = (float)Convert.ToDouble(textBox1.Text.Replace('.', ','));
                y[0] = (float)Convert.ToDouble(textBox2.Text.Replace('.', ','));
            }

            string s = @"
            __kernel void
            sum(global float4 *x, global float4 *y) {
                x[0] = x[0] + y[0];
            }";

            CLCalc.Program.Compile(new string[] { s });
            CLCalc.Program.Kernel sum = new CLCalc.Program.Kernel("sum");

            CLCalc.Program.Variable varx = new CLCalc.Program.Variable(x);
            CLCalc.Program.Variable vary = new CLCalc.Program.Variable(y);

            CLCalc.Program.Variable[] args = { varx, vary };
            int[] max = new int[] { 1 };

            sum.Execute(args, max);
            varx.ReadFromDeviceTo(x);
            textBox3.Text = Convert.ToString(x[0]);
        }
Ejemplo n.º 2
0
        /// <summary>Computes frame difference</summary>
        private void ComputeFrameDiff()
        {
            //Needs both images to compute
            if (CLBmp == null || CLBmpPrev == null || CLBmp.Width != CLBmpPrev.Width || CLBmp.Height != CLBmpPrev.Height)
            {
                return;
            }

            if (frameDiff == null || frameDiff.Length != ((CLBmp.Height * CLBmp.Width) >> 6))
            {
                //Reduces image size by 8
                frameDiff = new byte[(CLBmp.Height * CLBmp.Width) >> 6];

                CLframeDiff = new CLCalc.Program.Variable(frameDiff);

                MovingRegionBoxes = new List <int>();
            }

            CLCalc.Program.MemoryObject[] args = new CLCalc.Program.MemoryObject[] { CLBmp, CLBmpPrev, CLframeDiff };

            kernelComputeFrameDiff.Execute(args, new int[] { CLBmp.Width >> 3, CLBmp.Height >> 3 });

            CLframeDiff.ReadFromDeviceTo(frameDiff);

            MovingRegionBoxes.Clear();
            BracketMovingRegions(frameDiff, CLBmp.Width >> 3, CLBmp.Height >> 3, MovingRegionBoxes);
        }
Ejemplo n.º 3
0
        private static int[] ExecuteStepDpq(Polynomial x, Polynomial y)
        {
            if (x.Degree != y.Degree)
            {
                throw new InvalidOperationException("Only works for polynomials of same degree!");
            }

            var d = Math.Min(x.Degree, y.Degree);
            var n = d + 1;

            var dpq = new int[n * n];

            CLCalc.InitCL();
            CLCalc.Program.Compile(new[] { KernelCodeStepDpq });
            var kernel = new CLCalc.Program.Kernel("StepDpq");

            var nCl   = new CLCalc.Program.Variable(new[] { n });
            var xCl   = new CLCalc.Program.Variable(x.Coefficients);
            var yCl   = new CLCalc.Program.Variable(y.Coefficients);
            var dpqCl = new CLCalc.Program.Variable(dpq);

            CLCalc.Program.MemoryObject[] args = { nCl, xCl, yCl, dpqCl };

            var workers = new[] { 2 * n - 2 };

            kernel.Execute(args, workers);
            dpqCl.ReadFromDeviceTo(dpq);
            return(dpq);
        }
Ejemplo n.º 4
0
 public bool DetectCollisions(CollisionDetector.CollisionObject Obj1, CollisionDetector.CollisionObject Obj2)
 {
     if (CLCalc.CLAcceleration == CLCalc.CLAccelerationType.UsingCL)
     {
         CLCalc.Program.Variable variable1 = this.CLCalcVertexDisplacement(Obj1.Vertex, Obj1.Displacement);
         CLCalc.Program.Variable variable2 = this.CLCalcVertexDisplacement(Obj2.Vertex, Obj2.Displacement);
         int[] Values = new int[1];
         CLCalc.Program.Variable variable3 = new CLCalc.Program.Variable(Values);
         CLCalc.Program.Variable variable4 = new CLCalc.Program.Variable(Obj1.Triangle);
         CLCalc.Program.Variable variable5 = new CLCalc.Program.Variable(Obj2.Triangle);
         int[] GlobalWorkSize = new int[2]
         {
             Obj1.Triangle.Length / 3,
             Obj2.Triangle.Length / 3
         };
         this.kernelCalcExactCollision.Execute((CLCalc.Program.MemoryObject[]) new CLCalc.Program.Variable[5]
         {
             variable1,
             variable4,
             variable2,
             variable5,
             variable3
         }, GlobalWorkSize);
         variable3.ReadFromDeviceTo(Values);
         return(Values[0] > 0);
     }
     else
     {
         float[] Obj1Vertexes  = this.CalcVertexDisplacement(Obj1.Vertex, Obj1.Displacement);
         float[] Obj2Vertexes  = this.CalcVertexDisplacement(Obj2.Vertex, Obj2.Displacement);
         int[]   numCollisions = new int[1];
         this.CalcExactCollision(Obj1Vertexes, Obj1.Triangle, Obj2Vertexes, Obj2.Triangle, numCollisions);
         return(numCollisions[0] > 0);
     }
 }
Ejemplo n.º 5
0
        /// <summary>Returns stored data in a bitmap</summary>
        /// <param name="bmp">Reference bitmap</param>
        public Bitmap GetStoredBitmap(Bitmap bmp)
        {
            varData.ReadFromDeviceTo(Data); // 更新设备内存到现在内存中

            Bitmap resp = new Bitmap(width, height, bmp.PixelFormat);

            BitmapData bmd = resp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
                                           System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);

            //Write data
            unsafe
            {
                for (int y = 0; y < bmd.Height; y++)
                {
                    byte *row = (byte *)bmd.Scan0 + (y * bmd.Stride);

                    for (int x = 0; x < bmd.Width; x++)
                    {
                        row[x * PIXELSIZE]     = Data[3 * (x + width * y)];
                        row[x * PIXELSIZE + 1] = Data[3 * (x + width * y) + 1];
                        row[x * PIXELSIZE + 2] = Data[3 * (x + width * y) + 2];
                    }
                }
            }

            //Unlock bits
            resp.UnlockBits(bmd);

            return(resp);
        }
Ejemplo n.º 6
0
        /// <summary>Classifies multiple samples stored in OpenCL memory</summary>
        /// <param name="Samples">Samples data to classify</param>
        /// <param name="svm">SVM to use as classifier</param>
        public static float[] MultiClassify(SVM svm, CLCalc.Program.Image2D Samples)
        {
            float[] resp = new float[Samples.Height];

            //svm.WriteToDevice();

            if ((Samples.Width << 2) != svm.HostVLen[0])
            {
                throw new Exception("Invalid Samples width, should be the same length of training features");
            }

            if (svm.CLKernelValuesMultiClassify == null || svm.CLKernelValuesMultiClassify.OriginalVarLength != svm.alphaList.Count * Samples.Height)
            {
                svm.CLKernelValuesMultiClassify = new CLCalc.Program.Variable(new float[svm.alphaList.Count * Samples.Height]);
            }

            if (svm.CLAlphas == null || svm.CLAlphas.OriginalVarLength != svm.alphaList.Count)
            {
                svm.CLAlphas = new CLCalc.Program.Variable(svm.alphaList.ToArray());

                float[] ys = new float[svm.TrainingSet.trainingArray.Count];
                for (int i = 0; i < ys.Length; i++)
                {
                    ys[i] = svm.TrainingSet.trainingArray[i].y;
                }

                svm.CLys = new CLCalc.Program.Variable(ys);
            }
            if (svm.CLb == null)
            {
                svm.CLb            = new CLCalc.Program.Variable(new float[] { svm.b });
                svm.CLQtdSupVecs   = new CLCalc.Program.Variable(new int[] { svm.alphaList.Count });
                CLMultiClassifSums = new CLCalc.Program.Variable(new float[Samples.Height]);
            }

            if (CLMultiClassifSums.OriginalVarLength != Samples.Height)
            {
                CLMultiClassifSums = new CLCalc.Program.Variable(new float[Samples.Height]);
            }

            //svm.CLAlphas.WriteToDevice(svm.alphaList.ToArray());
            //svm.CLys.WriteToDevice(ys);
            //svm.CLb.WriteToDevice(new float[] { svm.b });
            //svm.CLQtdSupVecs.WriteToDevice(new int[] { svm.alphaList.Count });

            CLCalc.Program.MemoryObject[] args = new CLCalc.Program.MemoryObject[] { svm.CLTrainingFeatures, svm.CLQtdSupVecs, svm.CLXVecLen, Samples, svm.CLKernelValuesMultiClassify, svm.CLLambda };
            kernelComputeMultiKernelRBF.Execute(args, new int[] { svm.alphaList.Count, Samples.Height });

            CLCalc.Program.Sync();

            args = new CLCalc.Program.MemoryObject[] { svm.CLAlphas, svm.CLQtdSupVecs, svm.CLXVecLen, svm.CLys, svm.CLKernelValuesMultiClassify, svm.CLb, CLMultiClassifSums };
            kernelSumKernels.Execute(args, Samples.Height);

            CLMultiClassifSums.ReadFromDeviceTo(resp);
            return(resp);
        }
Ejemplo n.º 7
0
        /// <summary>Computes the inverse Discrete Fourier Transform of a double2 vector x whose length is a power of 16.
        /// x = { Re[x0] Im[x0] Re[x1] Im[x1] ... Re[xn] Im[xn] }, n = power of 16 (Length = 2*pow(16,n))</summary>
        public static CLCalc.Program.Variable iFFT16(CLCalc.Program.Variable CLx)
        {
            if (CLScale == null)
            {
                CLScale = new CLCalc.Program.Variable(new double[1]);
            }

            //Trick: DFT-1 (x) = DFT(x*)*/N;
            //Conjugate
            double[] vx = new double[CLx.OriginalVarLength];
            CLx.ReadFromDeviceTo(vx);

            double[] scale = new double[] { 1 };
            CLScale.WriteToDevice(scale);
            kernelConjugate.Execute(new CLCalc.Program.Variable[] { CLx, CLScale }, CLx.OriginalVarLength >> 1);
            CLx.ReadFromDeviceTo(vx);

            CLy = FFT16(ref CLx);

            scale[0] = 1 / (double)(CLx.OriginalVarLength >> 1);
            CLScale.WriteToDevice(scale);
            kernelConjugate.Execute(new CLCalc.Program.Variable[] { CLy, CLScale }, CLy.OriginalVarLength >> 1);
            return(CLy);
        }
Ejemplo n.º 8
0
 public int[] VertexCollision(float[] v1, float[] displacement1, float[] v2, float[] displacement2, float CollisionDistance, out float[] VertexDistances)
 {
     if ((double)CollisionDistance < 0.0)
     {
         throw new Exception("Collision distance should be positive");
     }
     int[] numArray1 = new int[v1.Length / 3];
     VertexDistances = new float[v1.Length / 3];
     for (int index = 0; index < numArray1.Length; ++index)
     {
         numArray1[index]       = -1;
         VertexDistances[index] = -1f;
     }
     float[] numArray2 = new float[1]
     {
         CollisionDistance
     };
     if (CLCalc.CLAcceleration == CLCalc.CLAccelerationType.UsingCL && (long)v1.Length * (long)v2.Length > 10000000L)
     {
         CLCalc.Program.Variable variable1 = this.CLCalcVertexDisplacement(v1, displacement1);
         CLCalc.Program.Variable variable2 = this.CLCalcVertexDisplacement(v2, displacement2);
         CLCalc.Program.Variable variable3 = new CLCalc.Program.Variable(numArray2);
         CLCalc.Program.Variable variable4 = new CLCalc.Program.Variable(numArray1);
         CLCalc.Program.Variable variable5 = new CLCalc.Program.Variable(VertexDistances);
         this.kernelCalcVertexCollision.Execute((CLCalc.Program.MemoryObject[]) new CLCalc.Program.Variable[5]
         {
             variable3,
             variable1,
             variable2,
             variable4,
             variable5
         }, new int[2]
         {
             v1.Length / 3,
             v2.Length / 3
         });
         variable4.ReadFromDeviceTo(numArray1);
         variable5.ReadFromDeviceTo(VertexDistances);
     }
     else
     {
         float[] v1_1 = this.CalcVertexDisplacement(v1, displacement1);
         float[] v2_1 = this.CalcVertexDisplacement(v2, displacement2);
         this.CalcVertexCollisions(numArray2, v1_1, v2_1, numArray1, VertexDistances);
     }
     return(numArray1);
 }
Ejemplo n.º 9
0
        /// <summary>Computes the Discrete Fourier Transform of a float2 vector x whose length is a power of 16.
        /// x = { Re[x0] Im[x0] Re[x1] Im[x1] ... Re[xn] Im[xn] }, n = power of 16 (Length = 2*pow(16,n))</summary>
        public static float[] FFT16(float[] x)
        {
            if (CLx == null || CLx.OriginalVarLength != x.Length)
            {
                CLx = new CLCalc.Program.Variable(x);
                CLy = new CLCalc.Program.Variable(x);
            }

            //Writes original content
            CLx.WriteToDevice(x);

            CLy = FFT16(ref CLx);


            float[] y = new float[x.Length];
            CLy.ReadFromDeviceTo(y);
            return(y);
        }
Ejemplo n.º 10
0
        /// <summary>Computes the inverse Discrete Fourier Transform of a double2 vector x whose length is a power of 16.
        /// x = { Re[x0] Im[x0] Re[x1] Im[x1] ... Re[xn] Im[xn] }, n = power of 16 (Length = 2*pow(16,n))</summary>
        public static double[] iFFT16(double[] x)
        {
            if (CLx == null || CLx.OriginalVarLength != x.Length)
            {
                CLx = new CLCalc.Program.Variable(x);
                CLy = new CLCalc.Program.Variable(x);
            }

            //Writes original content
            CLx.WriteToDevice(x);

            CLy = iFFT16(CLx);

            double[] y = new double[x.Length];
            CLy.ReadFromDeviceTo(y);

            return(y);
        }
Ejemplo n.º 11
0
        private void button3_Click(object sender, EventArgs e)
        {
            float[] x = new float[] { 1, 2, 3, 0.123f };
            float[] y = new float[] { 1, 2, 1, 1 };

            string s = @"
                       kernel void
                       sum (global float4 * x, global float4 * y)
                       {
                           x[0] = x[0] + y[0];
                       }
";

            CLCalc.Program.Compile(new string[] { s });
            CLCalc.Program.Kernel sum = new CLCalc.Program.Kernel("sum");

            CLCalc.Program.Variable   varx = new CLCalc.Program.Variable(x);
            CLCalc.Program.Variable   vary = new CLCalc.Program.Variable(y);
            CLCalc.Program.Variable[] args = { varx, vary };

            int[] max = new int[] { 1 };

            sum.Execute(args, max);

            varx.ReadFromDeviceTo(x);

            //float[] t = new float[1] { 0 };
            //float[] pos = new float[] { 1, 2, 3, 4, 5, 6 };
            //float[] vel = new float[] { 1, 0, 0, 0, 0, 0 };
            //float[] forces = new float[] { 0, 1, 0, 0, 0, 0 };

            //float[] masses = new float[] { 1, 1 };
            //float[] colSizes = new float[] { 0.1f, 0.1f };


            //CLCalc.InitCL();

            //CLCalc.CLPrograms.floatBodyPhysics phys = new CLCalc.CLPrograms.floatBodyPhysics(10);
            //CLCalc.CLPrograms.floatBodyPhysics phys2 = new CLCalc.CLPrograms.floatBodyPhysics(20);


            //CLCalc.FinishCL();
        }
Ejemplo n.º 12
0
        private void button1_Click(object sender, EventArgs e)
        {
            CLCalc.InitCL();


            double[] a = new double[] { 2, 147483647, 2, 7 };
            double[] b = new double[] { 1, 2, 7, 4 };
            double[] c = new double[4];

            CLCalc.Program.Variable v1 = new CLCalc.Program.Variable(a);
            CLCalc.Program.Variable v2 = new CLCalc.Program.Variable(b);
            CLCalc.Program.Variable v3 = new CLCalc.Program.Variable(c);

            CLCalc.CLPrograms.VectorSum VecSum = new CLCalc.CLPrograms.VectorSum();
            CLCalc.CLPrograms.MinDifs   Mdifs  = new CLCalc.CLPrograms.MinDifs();

            //string[] s = new string[] { VecSum.intVectorSum, VecSum.floatVectorSum };
            string[] s = new string[] { VecSum.doubleVectorSum };


            CLCalc.Program.Compile(s);

            CLCalc.Program.Kernel k = new CLCalc.Program.Kernel("doubleVectorSum");
            //CLCalc.Program.Kernel k2 = new CLCalc.Program.Kernel("intVectorSum");
            //CLCalc.Program.Kernel k = new CLCalc.Program.Kernel("floatMinDifs");

            CLCalc.Program.Variable[] vv = new CLCalc.Program.Variable[3] {
                v1, v2, v3
            };

            int[] max = new int[1] {
                a.Length
            };

            k.Execute(vv, max);

            CLCalc.Program.Sync();

            v3.ReadFromDeviceTo(c);

            CLCalc.FinishCL();
        }
Ejemplo n.º 13
0
        private static void GPU()
        {
            string vecSum = @"
                     __kernel void
                    floatVectorSum(__global       float * v1,
                                   __global       float * v2)
                    {
                        // Vector element index
                        int i = get_global_id(0);
                        v1[i] = v1[i] + v2[i];
                    }";

            //Initializes OpenCL Platforms and Devices and sets everything up
            CLCalc.InitCL();
            //Compiles the source codes. The source is a string array because the user may want
            //to split the source into many strings.
            CLCalc.Program.Compile(new string[] { vecSum });
            //Gets host access to the OpenCL floatVectorSum kernel
            CLCalc.Program.Kernel VectorSum = new CLCalc.Program.Kernel("floatVectorSum");
            //We want to sum 2000 numbers
            int n = 20000000;

            //Create vectors with 2000 numbers
            float[] v1 = new float[n], v2 = new float[n];
            //Creates population for v1 and v2
            for (int i = 0; i < n; i++)
            {
                v1[i] = (float)i / 10;
                v2[i] = -(float)i / 8;
            }
            //Creates vectors v1 and v2 in the device memory
            CLCalc.Program.Variable varV1 = new CLCalc.Program.Variable(v1);
            CLCalc.Program.Variable varV2 = new CLCalc.Program.Variable(v2);
            //Arguments of VectorSum kernel
            CLCalc.Program.Variable[] args = new CLCalc.Program.Variable[] { varV1, varV2 };
            //How many workers will there be? We need "n", one for each element
            //int[] workers = new int[1] { n };
            //Execute the kernel
            VectorSum.Execute(args, 20000000);
            //Read device memory varV1 to host memory v1
            varV1.ReadFromDeviceTo(v1);
        }
Ejemplo n.º 14
0
        public void DoubleSumTest()
        {
            string text = File.ReadAllText("Examples/SumTest.cl");

            CLCalc.InitCL();
            CLCalc.Program.Compile(new string[] { text });

            int count = 2000;
            var a     = new double[count];
            var b     = new double[count];
            var ab    = new double[count];

            for (int i = 0; i < count; i++)
            {
                a[i] = i / 10.0;
                b[i] = -i / 9.0;
            }

            using (CLCalc.Program.Kernel Kernel = new CLCalc.Program.Kernel("doubleVectorSum"))
            {
                using (CLCalc.Program.Variable
                       varA = new CLCalc.Program.Variable(a),
                       varB = new CLCalc.Program.Variable(b))
                {
                    var args    = new CLCalc.Program.Variable[] { varA, varB };
                    var workers = new int[1] {
                        count
                    };
                    Kernel.Execute(args, workers);
                    varA.ReadFromDeviceTo(ab);
                }
            }
            for (int i = 0; i < count; i++)
            {
                Assert.AreEqual(-i / 90.0, ab[i], 1E-13);
            }
        }
Ejemplo n.º 15
0
        public static Polynomial MultiplyKaratsubaOpenCl(Polynomial x, Polynomial y)
        {
            if (x.Degree != y.Degree)
            {
                throw new InvalidOperationException("Only works for polynomials of same degree!");
            }

            var d = Math.Min(x.Degree, y.Degree);
            var n = d + 1;

            var di  = ExecuteStepDi(x, y);
            var dpq = ExecuteStepDpq(x, y);
            var z   = new int[2 * n - 1];

            z[0]         = di[0];
            z[2 * n - 2] = di[n - 1];

            CLCalc.InitCL();
            CLCalc.Program.Compile(new[] { KernelCodeStepKaratsuba });
            var kernel = new CLCalc.Program.Kernel("StepKaratsuba");

            var nCl   = new CLCalc.Program.Variable(new[] { n });
            var xCl   = new CLCalc.Program.Variable(x.Coefficients);
            var yCl   = new CLCalc.Program.Variable(y.Coefficients);
            var diCl  = new CLCalc.Program.Variable(di);
            var dpqCl = new CLCalc.Program.Variable(dpq);
            var zCl   = new CLCalc.Program.Variable(z);

            CLCalc.Program.MemoryObject[] args = { nCl, xCl, yCl, diCl, dpqCl, zCl };

            var workers = new[] { 2 * n - 3 };

            kernel.Execute(args, workers);
            zCl.ReadFromDeviceTo(z);
            return(new Polynomial(z));
        }
Ejemplo n.º 16
0
        /// <summary>Computes the Discrete Fourier Transform of a double2 vector x whose length is a power of 16. 
        /// x = { Re[x0] Im[x0] Re[x1] Im[x1] ... Re[xn] Im[xn] }, n = power of 16 (Length = 2*pow(16,n))</summary>
        public static double[] FFT16(double[] x)
        {
            if (CLx == null || CLx.OriginalVarLength != x.Length)
            {
                CLx = new CLCalc.Program.Variable(x);
                CLy = new CLCalc.Program.Variable(x);
            }

            //Writes original content
            CLx.WriteToDevice(x);

            CLy = FFT16(ref CLx);

            double[] y = new double[x.Length];
            CLy.ReadFromDeviceTo(y);
            return y;
        }
Ejemplo n.º 17
0
        /// <summary>Shades a bitmap</summary>
        /// <param name="bmp">Bitmap to shade</param>
        /// <param name="bmp">Actually render?</param>
        /// <returns></returns>
        public void Shade(Bitmap bmp, PictureBox pb, bool doRender)
        {
            Bitmap   bmp2 = new Bitmap(bmp.Width, bmp.Height);
            Graphics g    = Graphics.FromImage(bmp2);

            g.DrawImage(bmp, 0, 0, bmp.Width, bmp.Height);

            //draws points onto thresholded bitmap
            for (int i = 0; i < Colors.Count; i++)
            {
                if (Points[i].Count > 1)
                {
                    g.DrawLines(new Pen(Color.Black, 2), Points[i].ToArray());
                }
            }


            #region Initializations
            if (CLbmpSrc == null || CLbmpSrc.Width != bmp.Width || CLbmpSrc.Height != bmp.Height)
            {
                CLbmpSrc     = new CLCalc.Program.Image2D(bmp2);
                CLbmpThresh  = new CLCalc.Program.Image2D(bmp);
                CLthreshInfo = new CLCalc.Program.Variable(typeof(byte), bmp.Width * bmp.Height);
                CLbmpStroke  = new CLCalc.Program.Image2D(bmp);
                CLbmpDists   = new CLCalc.Program.Image2D(bmp);

                CLimgFinal1 = new CLCalc.Program.Image2D(new Bitmap(bmp2.Width, bmp2.Height));
                CLimgFinal2 = new CLCalc.Program.Image2D(new Bitmap(bmp2.Width, bmp2.Height));

                CLTotalPixWeight = new CLCalc.Program.Variable(typeof(float), bmp.Width * bmp.Height);
                lastPixWeight    = new float[bmp.Width * bmp.Height];
                CLWeight         = new CLCalc.Program.Variable(typeof(float), bmp.Width * bmp.Height);
                lastImage        = new Bitmap(bmp.Width, bmp.Height);
            }
            else
            {
                CLbmpSrc.WriteBitmap(bmp2);
                CLimgFinal1.WriteBitmap(new Bitmap(bmp2.Width, bmp2.Height));
                CLimgFinal2.WriteBitmap(new Bitmap(bmp2.Width, bmp2.Height));
                kernelinitTotalWeight.Execute(new CLCalc.Program.MemoryObject[] { CLTotalPixWeight }, new int[] { CLbmpSrc.Width, CLbmpSrc.Height });
            }
            #endregion

            System.Diagnostics.Stopwatch sw   = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch swCL = new System.Diagnostics.Stopwatch();
            sw.Start();

            //computes threshold
            kernelThreshold.Execute(new CLCalc.Program.MemoryObject[] { CLcfgVars, CLbmpSrc, CLthreshInfo, CLbmpThresh }, new int[] { bmp.Width, bmp.Height });

            if (!doRender)
            {
                return;
            }

            //Reuse last render?
            if (ReUseLastRender)
            {
                CLTotalPixWeight.WriteToDevice(lastPixWeight);
                CLimgFinal1.WriteBitmap(lastImage);
            }
            else
            {
                lastRenderedIdx = 0;
            }

            //generates images for points
            for (int i = lastRenderedIdx; i < Colors.Count; i++)
            {
                Bitmap bmpStroke = new Bitmap(bmp.Width, bmp.Height);

                if (Points[i].Count > 1)
                {
                    if (DistanceMaps[i] == null)
                    {
                        Graphics g2 = Graphics.FromImage(bmpStroke);
                        g2.DrawLines(new Pen(Colors[i], 2), Points[i].ToArray());

                        CLbmpStroke.WriteBitmap(bmpStroke);

                        int[] changed = new int[] { 0 };
                        swCL.Start();
                        changed[0] = 1;
                        kernelinitWeight.Execute(new CLCalc.Program.MemoryObject[] { CLWeight }, new int[] { CLbmpSrc.Width, CLbmpSrc.Height });

                        int n = 0;
                        while (changed[0] > 0 && n < MAXPROPAGITERS)
                        {
                            n++;
                            changed[0] = 0;
                            CLchanged.WriteToDevice(changed);
                            kernelPropagateDist.Execute(new CLCalc.Program.MemoryObject[] { CLchanged, CLbmpStroke, CLthreshInfo, CLWeight, CLbmpDists },
                                                        new int[] { CLbmpSrc.Width, CLbmpSrc.Height });

                            CLchanged.ReadFromDeviceTo(changed);
                        }
                        swCL.Stop();

                        DistanceMaps[i] = new float[CLWeight.OriginalVarLength];
                        CLWeight.ReadFromDeviceTo(DistanceMaps[i]);
                    }
                    else
                    {
                        CLWeight.WriteToDevice(DistanceMaps[i]);
                    }



                    //composes total weight
                    CLcolor.WriteToDevice(new float[] { (float)Colors[i].B, (float)Colors[i].G, (float)Colors[i].R });

                    kernelAddToTotalWeight.Execute(new CLCalc.Program.MemoryObject[] { CLTotalPixWeight, CLWeight, CLcolor, CLimgFinal1, CLimgFinal2, CLthreshInfo }, new int[] { CLbmpSrc.Width, CLbmpSrc.Height });
                    //swaps final images - result is always on CLimgFinal1
                    CLCalc.Program.Image2D temp = CLimgFinal1;
                    CLimgFinal1 = CLimgFinal2;
                    CLimgFinal2 = temp;

                    if (pb != null)
                    {
                        pb.Image = GetRenderedImage();
                        pb.Refresh();
                    }
                }
                bmpStroke.Dispose();
            }
            sw.Stop();

            lastRenderedIdx = Colors.Count;
            //saves total pixel weight and final image
            CLTotalPixWeight.ReadFromDeviceTo(lastPixWeight);
            if (lastImage != null)
            {
                lastImage.Dispose();
            }
            lastImage = CLimgFinal1.ReadBitmap();
        }
Ejemplo n.º 18
0
        /// <summary>Equalizes image histogram using OpenCL</summary>
        private void CLEqualizeHistogram(ref Bitmap bmp)
        {
            if (CLCalc.CLAcceleration == CLCalc.CLAccelerationType.Unknown)
            {
                CLCalc.InitCL();
            }
            if (CLCalc.CLAcceleration != CLCalc.CLAccelerationType.UsingCL)
            {
                return;
            }

            float[] PartialHistograms = new float[NLumIntens * bmp.Width];
            float[] histLuminance     = new float[NLumIntens];

            if (kernelComputeHistograms == null || CLN == null || CLHistogram == null)
            {
                CLHistogram         = new CLCalc.Program.Variable(histLuminance);
                CLPartialHistograms = new CLCalc.Program.Variable(PartialHistograms);
            }
            InitKernels();


            System.Diagnostics.Stopwatch swTotal               = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch swCopyBmp             = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch swRescaling           = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch swComputeHistPartial  = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch swComputeHistConsolid = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch swHistIntegral        = new System.Diagnostics.Stopwatch();

            swTotal.Start();

            swCopyBmp.Start();
            if (CLbmp == null || CLbmp.Height != bmp.Height || CLbmp.Width != bmp.Width)
            {
                CLbmp               = new CLCalc.Program.Image2D(bmp);
                CLNewBmp            = new CLCalc.Program.Image2D(bmp);
                CLPartialHistograms = new CLCalc.Program.Variable(PartialHistograms);
            }
            else
            {
                CLbmp.WriteBitmap(bmp);
                CLN.WriteToDevice(new int[] { NLumIntens });
                CLWidth.WriteToDevice(new int[] { bmp.Width });
                CLHeight.WriteToDevice(new int[] { bmp.Height });
            }
            swCopyBmp.Stop();

            swComputeHistPartial.Start();

            //Partial histograms
            CLCalc.Program.MemoryObject[] args = new CLCalc.Program.MemoryObject[] { CLbmp, CLPartialHistograms, CLHeight, CLN };

            kernelComputeHistograms.Execute(args, bmp.Width);
            CLCalc.Program.Sync();
            swComputeHistPartial.Stop();



            swComputeHistConsolid.Start();

            args = new CLCalc.Program.MemoryObject[] { CLPartialHistograms, CLHistogram, CLHeight, CLN };
            kernelConsolidateHist.Execute(args, NLumIntens);

            CLHistogram.ReadFromDeviceTo(histLuminance);

            swComputeHistConsolid.Stop();


            swHistIntegral.Start();
            //Perform histogram integration - better performance in CPU
            //Compute histogram integrals in-place
            for (int i = 1; i < NLumIntens; i++)
            {
                histLuminance[i] += histLuminance[i - 1];
            }

            float scale = 0.9f / histLuminance[NLumIntens - 1];

            //Scales histograms
            for (int i = 0; i < NLumIntens; i++)
            {
                histLuminance[i] *= scale;
            }

            //Writes histogram integral
            CLHistogram.WriteToDevice(histLuminance);
            swHistIntegral.Stop();

            swRescaling.Start();
            //Computes equalized image
            args = new CLCalc.Program.MemoryObject[] { CLbmp, CLNewBmp, CLHistogram, CLN };
            kernelPerformNormalization.Execute(args, new int [] { bmp.Width, bmp.Height });

            bmp = CLNewBmp.ReadBitmap();
            swRescaling.Stop();


            swTotal.Stop();
        }
Ejemplo n.º 19
0
        /// <summary>Computes the inverse Discrete Fourier Transform of a float2 vector x whose length is a power of 4. 
        /// x = { Re[x0] Im[x0] Re[x1] Im[x1] ... Re[xn] Im[xn] }, n = power of 4 (Length = 2*pow(4,n))</summary>
        public static float[] iFFT4(float[] x)
        {
            if (CLx == null || CLx.OriginalVarLength != x.Length)
            {
                CLx = new CLCalc.Program.Variable(x);
                CLy = new CLCalc.Program.Variable(x);
            }

            //Writes original content
            CLx.WriteToDevice(x);

            CLy = iFFT4(CLx);

            float[] y = new float[x.Length];
            CLy.ReadFromDeviceTo(y);

            return y;
        }