Example #1
0
        static void Main(string[] args)
        {
            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 OpenCLTemplate.CLCalc.Program.Kernel("floatVectorSum");


            //We want to sum 2000 numbers
            int n = 2000;

            //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 / 9;
            }


            //Creates vectors v1 and v2 in the device memory
            OpenCLTemplate.CLCalc.Program.Variable varV1 = new OpenCLTemplate.CLCalc.Program.Variable(v1);
            OpenCLTemplate.CLCalc.Program.Variable varV2 = new OpenCLTemplate.CLCalc.Program.Variable(v2);

            //Arguments of VectorSum kernel
            OpenCLTemplate.CLCalc.Program.Variable[] argsCL = new OpenCLTemplate.CLCalc.Program.Variable[] { varV1, varV2 };

            int[] workers = new int[1] {
                n
            };

            //Execute the kernel
            VectorSum.Execute(argsCL, workers);

            //Read device memory varV1 to host memory v1
            varV1.ReadFromDeviceTo(v1);
        }
Example #2
0
        public static string Calculate(float[] data1, float[] data2, float[] result)
        {
            //Initializes OpenCL Platforms and Devices and sets everything up
            OpenCLTemplate.CLCalc.InitCL(ComputeDeviceTypes.Gpu);

            //Compiles the source codes. The source is a string array because the user may want
            //to split the source into many strings.
            OpenCLTemplate.CLCalc.Program.Compile(new string[] { kernelTask });

            //Gets host access to the OpenCL floatVectorSum kernel
            OpenCLTemplate.CLCalc.Program.Kernel VectorSum = new OpenCLTemplate.CLCalc.Program.Kernel("floatVectorSum");

            //We want to sum 2000 numbers
            int n = data1.Length;

            //Create vectors with 2000 numbers

            //Creates vectors v1 and v2 in the device memory
            OpenCLTemplate.CLCalc.Program.Variable varV1 = new OpenCLTemplate.CLCalc.Program.Variable(data1);
            OpenCLTemplate.CLCalc.Program.Variable varV2 = new OpenCLTemplate.CLCalc.Program.Variable(data2);

            //Arguments of VectorSum kernel
            OpenCLTemplate.CLCalc.Program.Variable[] args = new OpenCLTemplate.CLCalc.Program.Variable[] { varV1, varV2 };

            //How many workers will there be? We need "n", one for each element
            int[] workers = new int[1] {
                n
            };

            var watch = System.Diagnostics.Stopwatch.StartNew(); // ex

            //Execute the kernel
            VectorSum.Execute(args, workers);

            //Read device memory varV1 to host memory v1
            varV1.ReadFromDeviceTo(result);
            watch.Stop();                            // ex
            var gpuTime = watch.ElapsedMilliseconds; // ex

            return(gpuTime.ToString());
        }
Example #3
0
        static void Main(string[] args)
        {
            string brute = @"
				__kernel void
				bruteDeForce(global char * alphabet, global double * alphabetSize,  
				global int * maxLen, global double * steps, global char * password,
				global int * match)
				{

				// Vector element index
				int i = get_global_id(0);

				int stepPointer = 0;
				char word[7];
				int pos = 0;
				if (i >= steps[stepPointer]){
					stepPointer++;
				}
	
				int j = 0;
				double sum = 0;
				for (; j <= stepPointer; j++){
					pos = (int)fmod((i - sum) / pow(alphabetSize[0], (double)j), alphabetSize[0]);
					sum = sum + pow((pos + 1),(double)j);
					word[(stepPointer-j)] = alphabet[pos];
				}
				word[j] = '\0';
                      
				}
								"                                ;

            //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[] { brute });

            //Gets host access to the OpenCL floatVectorSum kernel
            CLCalc.Program.Kernel VectorSum = new OpenCLTemplate.CLCalc.Program.Kernel("bruteDeForce");

            int[]  maxLen   = { 3 };
            char[] password = new char[10];
            int[]  match    = { 0 };
            //     char[] alphabet = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
            //'s', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
            //'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ','!','$','%','@','-','_'};

            char[] alphabet = new char[] { 'a', 'b', 'c' };

            int[] alphabetSize = { alphabet.Length };

            double len = 0;

            double[] steps = new double[maxLen[0]];

            for (int i = 1; i <= maxLen[0]; i++)
            {
                len += Math.Pow(alphabetSize[0], i);
                if (i == 1)
                {
                    steps[(i - 1)] = Math.Pow(alphabetSize[0], i);
                }
                else
                {
                    steps[(i - 1)] = Math.Pow(alphabetSize[0], i) + steps[(i - 2)];
                }
            }

            char[] word = new char[maxLen[0]];


            //Creates vectors v1 and v2 in the device memory
            OpenCLTemplate.CLCalc.Program.Variable varAlphabet     = new OpenCLTemplate.CLCalc.Program.Variable(alphabet);
            OpenCLTemplate.CLCalc.Program.Variable varAlphabetSize = new OpenCLTemplate.CLCalc.Program.Variable(alphabetSize);
            OpenCLTemplate.CLCalc.Program.Variable varMaxLen       = new OpenCLTemplate.CLCalc.Program.Variable(maxLen);
            OpenCLTemplate.CLCalc.Program.Variable varSteps        = new OpenCLTemplate.CLCalc.Program.Variable(steps);
            OpenCLTemplate.CLCalc.Program.Variable varPassword     = new OpenCLTemplate.CLCalc.Program.Variable(password);
            OpenCLTemplate.CLCalc.Program.Variable varMatch        = new OpenCLTemplate.CLCalc.Program.Variable(match);

            //Arguments of VectorSum kernel
            OpenCLTemplate.CLCalc.Program.Variable[] argsCL = new OpenCLTemplate.CLCalc.Program.Variable[] { varAlphabet, varAlphabetSize, varMaxLen, varSteps, varPassword, varMatch };

            int[] workers = new int[1] {
                10
            };

            //OpenCLTemplate.CLCalc.Program.DefaultCQ = 0;

            //Execute the kernel
            VectorSum.Execute(argsCL, workers);

            //Read device memory varV1 to host memory v1
            varMatch.ReadFromDeviceTo(match);
            varPassword.ReadFromDeviceTo(password);

            Console.WriteLine(match[0]);
            Console.ReadLine();
        }
Example #4
0
        /*public void Calculate()
         * {
         *  System.Diagnostics.Stopwatch myStopwatch = new System.Diagnostics.Stopwatch();
         *  myStopwatch.Start();
         *  dataIter = new int[Resolution, Resolution];
         *  dataAbs = new float[Resolution, Resolution];
         *
         *  double x = XCenter - ImageWidth / 2.0d;
         *  double y = ImageWidth / 2.0d - YCenter;
         *  object locker = new object();
         *
         *  for (int xpix = 0; xpix < Resolution; xpix++)
         *  {
         *      Parallel.For(0, Resolution, ypix =>
         *      {
         *
         *          (int, float) tuple;
         *          lock (locker)
         *          {
         *              y = YCenter - ImageWidth / 2 + ImageWidth / Resolution * ypix;
         *              tuple = CalculateIters(x, y, MaxIter);
         *          }
         *          lock (dataIter)
         *              dataIter[xpix, ypix] = tuple.Item1;
         *          lock (dataAbs)
         *              dataAbs[xpix, ypix] = tuple.Item2;
         *
         *
         *      });
         *      x += ImageWidth / Resolution;
         *      Console.WriteLine($"{100 * xpix / Resolution}%");
         *  }
         *  myStopwatch.Stop();
         *
         *
         * }
         */
        public void CalculateOpenCL()
        {
            dataIter = new int[Resolution, Resolution];
            dataAbs  = new float[Resolution, Resolution];
            string vecSum = @"
            __kernel void
            mandelbrot(__global    int * iter,
                   __global    float * abs, 
                   __constant double *xc,__constant double *yc,__constant double *width,__constant int *res,__constant int *maxiter)
            {
                int xpix=get_global_id(0);
                int ypix=get_global_id(1);


                double x = *xc - *width/2 + *width/(*res)*xpix;
                double y = *yc - *width/2 + *width/(*res)*ypix;
                double Re = 0;
                double Im = 0;
                int i;
                float mag = 0;
                for (i = 0; i < *maxiter; i++)
                {

                    double buff = Re;
                    Re = Re * Re - Im * Im + x;
                    Im = 2 * buff * Im + y;

                    mag = Re * Re + Im * Im;
                    if (mag >= 4) break;
                }
                if (i == *maxiter) i = -1;
                iter[mad_sat(ypix,*res,xpix)]=i;
                abs[mad_sat(ypix,*res,xpix)]=mag;
            }
            ";

            //Инициализация платформы. В скобках можно задавать параметры. По умолчанию инициализируются только GPU.
            //OpenCLTemplate.CLCalc.InitCL(Cloo.ComputeDeviceTypes.All) позволяет инициализировать не только
            //GPU но и CPU.
            OpenCLTemplate.CLCalc.InitCL();
            //Команда выдаёт список проинициализированных устройств.
            List <Cloo.ComputeDevice> L = OpenCLTemplate.CLCalc.CLDevices;

            //Команда устанавливает устройство с которым будет вестись работа
            OpenCLTemplate.CLCalc.Program.DefaultCQ = 0;
            //Компиляция программы vecSum
            OpenCLTemplate.CLCalc.Program.Compile(new string[] { vecSum });
            //Присовоение названия скомпилированной программе, её загрузка.
            OpenCLTemplate.CLCalc.Program.Kernel Mandelbrot = new OpenCLTemplate.CLCalc.Program.Kernel("mandelbrot");
            int n = Resolution;

            dataIter     = new int[Resolution, Resolution];
            dataAbs      = new float[Resolution, Resolution];
            lineDataIter = new int[Resolution * Resolution];
            lineDataAbs  = new float[Resolution * Resolution];

            //Загружаем вектора в память устройства
            OpenCLTemplate.CLCalc.Program.Variable var_iter    = new OpenCLTemplate.CLCalc.Program.Variable(lineDataIter);
            OpenCLTemplate.CLCalc.Program.Variable var_abs     = new OpenCLTemplate.CLCalc.Program.Variable(lineDataAbs);
            OpenCLTemplate.CLCalc.Program.Variable var_xc      = new OpenCLTemplate.CLCalc.Program.Variable(new double[] { XCenter });
            OpenCLTemplate.CLCalc.Program.Variable var_yc      = new OpenCLTemplate.CLCalc.Program.Variable(new double[] { YCenter });
            OpenCLTemplate.CLCalc.Program.Variable var_width   = new OpenCLTemplate.CLCalc.Program.Variable(new double[] { ImageWidth });
            OpenCLTemplate.CLCalc.Program.Variable var_res     = new OpenCLTemplate.CLCalc.Program.Variable(new int[] { Resolution });
            OpenCLTemplate.CLCalc.Program.Variable var_maxiter = new OpenCLTemplate.CLCalc.Program.Variable(new int[] { MaxIter });

            //Объявление того, кто из векторов кем является
            OpenCLTemplate.CLCalc.Program.Variable[] args = new OpenCLTemplate.CLCalc.Program.Variable[] { var_iter, var_abs, var_xc, var_yc,
                                                                                                           var_width, var_res, var_maxiter };

            //Сколько потоков будет запущенно
            int[] workers = new int[2] {
                n, n
            };

            //Исполняем ядро VectorSum с аргументами args и колличеством потоков workers
            Mandelbrot.Execute(args, workers);

            //выгружаем из памяти
            var_iter.ReadFromDeviceTo(lineDataIter);
            var_abs.ReadFromDeviceTo(lineDataAbs);

            /*
             * for (int i = 0; i < Resolution; i++)
             * {
             *  for (int j = 0; j < Resolution; j++)
             *  {
             *      dataIter[i, j] = lineDataIter[Resolution * j + i];
             *      dataAbs[i, j] = lineDataAbs[Resolution * j + i];
             *  }
             * }
             */
        }
Example #5
0
        /*
         * public Bitmap MakeBitmap()
         * {
         *  Bitmap canvas = new Bitmap(Resolution, Resolution);
         *
         *  for (int x = 0; x < Resolution; x++)
         *  {
         *      for (int y = 0; y < Resolution; y++)
         *      {
         *          canvas.SetPixel(x, y, MandelbrotColor(dataIter[x, y], dataAbs[x, y], MaxIter));
         *      }
         *  }
         *
         *  return canvas;
         * }
         */
        /*
         * public Bitmap MakeBitmap(double shift, int iterCycle)
         * {
         *  Bitmap canvas = new Bitmap(Resolution, Resolution);
         *  Stopwatch stopwatch = new Stopwatch();
         *  stopwatch.Start();
         *
         *  for (int x = 0; x < Resolution; x++)
         *  {
         *
         *      for (int y = 0; y < Resolution; y++)
         *      {
         *          canvas.SetPixel(x, Resolution - y - 1, MandelbrotColor(dataIter[x, y], dataAbs[x, y], MaxIter, shift, iterCycle));
         *      }
         *
         *  }
         *
         *  stopwatch.Stop();
         *
         *  return canvas;
         * }
         */
        public Bitmap MakeBitmapOpenCL(double shift, int iterCycle)
        {
            string programStr = @"
            
__kernel void
            program(__write_only image2d_t bitmap, __constant int *res,
                   __constant int *shift, __constant int *cycle,
                   __constant int *iter, __constant int *maxiter,
                   __constant float *abs, __constant float *pos,
                   __constant int *R, __constant int *G, __constant int *B, __constant int *n)
            {
               int2 coor=(int2)(get_global_id(0),get_global_id(1));
               int i =*(iter+mad_sat(coor.x,*res,coor.y));
               float mag=*(abs+mad_sat(coor.x,*res,coor.y));
               uint4 color = (uint4)(0,0,0,255);
               int red,green,blue;
               if(i!=-1)
               {
                   float smooth=i-log2(log2(mag))+4+*shift;
                   while(smooth>=0)
                   {
                       smooth-=*cycle;
                   }
                   smooth+=*cycle;
                   
                   float cpos=smooth / (float)(*cycle);
                   for(int i = 1; i<(*n); i++)
                   {
                       if(cpos<(*(pos+i)))
                       {
                           red = round(R[i - 1] + (cpos - pos[i - 1])  / (pos[i] - pos[i - 1])* (R[i] - R[i - 1]));
                           green = round(G[i - 1] + (cpos - pos[i - 1])  / (pos[i] - pos[i - 1])* (G[i] - G[i - 1]));
                           blue = round(B[i - 1] + (cpos - pos[i - 1])  / (pos[i] - pos[i - 1])* (B[i] - B[i - 1]));
                           break;
                       }  
                    }
                    color=(uint4)(blue,green,red,255);                 
               }              
               write_imageui(bitmap, (int2)(coor.y,*res-1-coor.x), color);
               
            }
            ";

            OpenCLTemplate.CLCalc.InitCL();
            List <Cloo.ComputeDevice> L = OpenCLTemplate.CLCalc.CLDevices;

            //Команда устанавливает устройство с которым будет вестись работа
            OpenCLTemplate.CLCalc.Program.DefaultCQ = 0;
            //Компиляция программы vecSum
            OpenCLTemplate.CLCalc.Program.Compile(new string[] { programStr });

            //Присовоение названия скомпилированной программе, её загрузка.
            OpenCLTemplate.CLCalc.Program.Kernel program = new OpenCLTemplate.CLCalc.Program.Kernel("program");

            byte[] matrix = new byte[Resolution * Resolution * 4];

            float[] pos = new float[ColorGradient.controlPoints.Count];
            int[]   R   = new int[ColorGradient.controlPoints.Count];
            int[]   G   = new int[ColorGradient.controlPoints.Count];
            int[]   B   = new int[ColorGradient.controlPoints.Count];

            for (int i = 0; i < ColorGradient.controlPoints.Count; i++)
            {
                pos[i] = float.Parse(ColorGradient.controlPoints[i].Position.ToString());
                R[i]   = ColorGradient.controlPoints[i].Color.R;
                G[i]   = ColorGradient.controlPoints[i].Color.G;
                B[i]   = ColorGradient.controlPoints[i].Color.B;
            }

            OpenCLTemplate.CLCalc.Program.Image2D  var_bitmap  = new OpenCLTemplate.CLCalc.Program.Image2D(matrix, Resolution, Resolution);
            OpenCLTemplate.CLCalc.Program.Variable var_res     = new OpenCLTemplate.CLCalc.Program.Variable(new int[] { Resolution });
            OpenCLTemplate.CLCalc.Program.Variable var_maxiter = new OpenCLTemplate.CLCalc.Program.Variable(new int[] { MaxIter });
            OpenCLTemplate.CLCalc.Program.Variable var_shift   = new OpenCLTemplate.CLCalc.Program.Variable(new int[] { Convert.ToInt32(Math.Round(shift)) });
            OpenCLTemplate.CLCalc.Program.Variable var_cycle   = new OpenCLTemplate.CLCalc.Program.Variable(new int[] { iterCycle });
            OpenCLTemplate.CLCalc.Program.Variable var_iter    = new OpenCLTemplate.CLCalc.Program.Variable(lineDataIter);
            OpenCLTemplate.CLCalc.Program.Variable var_abs     = new OpenCLTemplate.CLCalc.Program.Variable(lineDataAbs);
            OpenCLTemplate.CLCalc.Program.Variable var_pos     = new OpenCLTemplate.CLCalc.Program.Variable(pos);
            OpenCLTemplate.CLCalc.Program.Variable var_R       = new OpenCLTemplate.CLCalc.Program.Variable(R);
            OpenCLTemplate.CLCalc.Program.Variable var_G       = new OpenCLTemplate.CLCalc.Program.Variable(G);
            OpenCLTemplate.CLCalc.Program.Variable var_B       = new OpenCLTemplate.CLCalc.Program.Variable(B);
            OpenCLTemplate.CLCalc.Program.Variable var_n       = new OpenCLTemplate.CLCalc.Program.Variable(new int[] { ColorGradient.controlPoints.Count });
            //var_bitmap.WriteToDevice(matrix);
            OpenCLTemplate.CLCalc.Program.MemoryObject[] args = new OpenCLTemplate.CLCalc.Program.MemoryObject[] { var_bitmap, var_res,
                                                                                                                   var_shift, var_cycle, var_iter, var_maxiter, var_abs, var_pos, var_R, var_G, var_B, var_n };

            program.Execute(args, new int[] { Resolution, Resolution });


            var_bitmap.ReadFromDeviceTo(matrix);
            Stopwatch stop = new Stopwatch();

            stop.Start();

            /*
             * for (int i = 0; i < matrix.Length; i += 4)
             * {
             *  bitmap.SetPixel(i / 4 / Resolution,  (i / 4) % Resolution, Color.FromArgb(matrix[i + 2], matrix[i + 1], matrix[i + 0]));
             * }
             */
            Bitmap bmp = new Bitmap(Resolution, Resolution, PixelFormat.Format32bppPArgb);

            //Create a BitmapData and Lock all pixels to be written
            BitmapData bmpData = bmp.LockBits(
                new Rectangle(0, 0, bmp.Width, bmp.Height),
                ImageLockMode.WriteOnly, bmp.PixelFormat);

            //Copy the data from the byte array into BitmapData.Scan0
            Marshal.Copy(matrix, 0, bmpData.Scan0, matrix.Length);
            //Unlock the pixels
            bmp.UnlockBits(bmpData);


            stop.Stop();
            //MessageBox.Show(stop.ElapsedMilliseconds.ToString());



            return(bmp);
        }
        //opencl方式进行 隐藏信息
        Boolean hideInfoToBMPOpenCL()
        {
            string ss = textBoxInfo.Text;

            char[] ch = new char[ss.Length];
            for (int i = 0; i < ss.Length; i++) //获得需要隐藏的信息 转成字节
            {
                ch[i] = Convert.ToChar(ss[i]);
            }
            byte[] temp = new byte[(ss.Length + 2) * 16];  // 将信息和两个#号一起转成16位信息
            int    m, n;

            // 开始嵌入#
            for (n = 0; n < 16; n++)
            {
                temp[n] = Convert.ToByte(0x0001 & '#' >> n);
            }
            // 中间是隐藏信息
            for (m = 1; m < ss.Length + 1; m++)
            {
                for (n = 0; n < 16; n++)
                {
                    temp[16 * m + n] = Convert.ToByte(0x0001 & ch[m - 1] >> n);
                }
            }
            // 结束时#
            for (n = 0; n < 16; n++)
            {
                temp[16 * m + n] = Convert.ToByte(0x0001 & '#' >> n);
            }

            //创建一个文件对象
            // 读取文件
            FileStream fs = new FileStream(textBoxPath.Text.Trim(), FileMode.Open, FileAccess.Read);

            if (fs.Length < ((ss.Length + 2) * 16 + 56))
            {
                MessageBox.Show("发送失败,文字信息的长度过长,请选择其他图片", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }
            fs.Close();



            /*
             * string vechidetextinfo = @"
             *       __kernel void
             *      hidetextinfo(__global  uchar * image,
             *      __global int * length,
             *      __global   uchar * info)
             *      {
             *           for (int i = 0; i < length[0]; i++)
             *              image[54+i]=image[54+i]&0xfe|info[i];
             *      }";
             * //初始化平台和设备
             * OpenCLTemplate.CLCalc.InitCL();
             *
             * //编译源码
             * OpenCLTemplate.CLCalc.Program.Compile(new string[] { vechidetextinfo });
             *
             * //得到内核句柄
             * OpenCLTemplate.CLCalc.Program.Kernel VectorSum = new OpenCLTemplate.CLCalc.Program.Kernel("hidetextinfo");
             * Bitmap bmp = new Bitmap(textBoxPath.Text.Trim());
             * ImageData imgdata = new ImageData(bmp);// 读取字节数据
             *
             * OpenCLTemplate.CLCalc.Program.Variable varV1 = new OpenCLTemplate.CLCalc.Program.Variable(new int[] { temp.Length });
             * OpenCLTemplate.CLCalc.Program.Variable varV2 = new OpenCLTemplate.CLCalc.Program.Variable(temp);
             * //变量参数化
             * OpenCLTemplate.CLCalc.Program.Variable[] args = new OpenCLTemplate.CLCalc.Program.Variable[] { imgdata.varData,varV1, varV2 };
             *
             * //n个worders
             * int[] workers = new int[1] { 1 };
             *
             * //执行worders
             * VectorSum.Execute(args, workers);
             * bmp = imgdata.GetStoredBitmap(bmp);
             * bmp.Save("temp.bmp");  // 保存到缓存中
             * // 嵌入文件成功  可以发送了
             * return true;
             */



            //下面是并行方式
            string vechidetextinfo = @"
                     __kernel void
                    hidetextinfo(__global  uchar * image,
                    __global   uchar * info)
                    {
                         int i=get_global_id(0);
                         image[54+i]=image[54+i]&0xfe|info[i];
                    }";

            //初始化平台和设备
            OpenCLTemplate.CLCalc.InitCL();

            //编译源码
            OpenCLTemplate.CLCalc.Program.Compile(new string[] { vechidetextinfo });

            //得到内核句柄
            OpenCLTemplate.CLCalc.Program.Kernel VectorSum = new OpenCLTemplate.CLCalc.Program.Kernel("hidetextinfo");
            Bitmap    bmp     = new Bitmap(textBoxPath.Text.Trim());
            ImageData imgdata = new ImageData(bmp);// 读取字节数据

            OpenCLTemplate.CLCalc.Program.Variable varV1 = new OpenCLTemplate.CLCalc.Program.Variable(temp);
            //变量参数化
            OpenCLTemplate.CLCalc.Program.Variable[] args = new OpenCLTemplate.CLCalc.Program.Variable[] { imgdata.varData, varV1 };

            //n个worders
            int[] workers = new int[1] {
                temp.Length
            };

            //执行worders
            VectorSum.Execute(args, workers);
            bmp = imgdata.GetStoredBitmap(bmp);
            bmp.Save("temp.bmp");  // 保存到缓存中
            // 嵌入文件成功  可以发送了
            return(true);
        }
        /// <summary>
        /// OpenCL Test 2
        /// Es wird die Funktion sumTwoIntegers genutzt
        /// Die zwei Integers Arrays übergeben bekommt und Summiert
        /// Die Berechnungen werden über die GPU Console ausgeben
        /// und das Ergebnis nochmals über die CPU Console
        /// </summary>
        private void test2()
        {
            //Erstellt einen neuen Kernel für die Benutzung mit dem Namen "sumTwoIntegers"
            OpenCLTemplate.CLCalc.Program.Kernel VectorSum = new OpenCLTemplate.CLCalc.Program.Kernel("sumTwoIntegers");

            //Wir wollen 10 Zahlen summieren
            int n = 10;

            //Erstelle 2 Vektoren mit je n Zahlen
            int[] lInteger1 = new int[n];
            int[] lInteger2 = new int[n];

            //Zufallszahl generieren mittels Random
            Random lRandom = new Random();

            //Vektoren mit Random Zahlen füllen
            for (int i = 0; i < n; i++)
            {
                lInteger1[i] = lRandom.Next(0, n);
                lInteger2[i] = lRandom.Next(0, n);
            }

            //Zwei Variablen im Gerätespeicher erstellen
            OpenCLTemplate.CLCalc.Program.Variable lVariable1 = new OpenCLTemplate.CLCalc.Program.Variable(lInteger1);
            OpenCLTemplate.CLCalc.Program.Variable lVariable2 = new OpenCLTemplate.CLCalc.Program.Variable(lInteger2);

            //Dem Kernel sagen, mit welchen Variablen er arbeiten soll
            OpenCLTemplate.CLCalc.Program.Variable[] lArgsVariable = new OpenCLTemplate.CLCalc.Program.Variable[] { lVariable1, lVariable2 };

            //Definiert die Anzahl der benötigten Worker, für jedes Element einen
            int[] lWorkers = new int[1] { n };

            //Kernel ausführen
            VectorSum.Execute(lArgsVariable, lWorkers);

            //Inhalt der Gerätespeicher Variable lInteger1 in die Host Variable lVariable1 einlesen
            lVariable1.ReadFromDeviceTo(lInteger1);

            //Ausgabe über die CPU Console -> TextBox in der Form
            for (int i = 0; i < n; i++)
                Console.WriteLine(String.Format("Ergebnis {0} : {1}", i + 1, lInteger1[i]));
        }
        /// <summary>
        /// Berechnung mittels der GPU
        /// </summary>
        private void calculateMandelwithGPU()
        {
            //Erstellt einen neuen Kernel für die Benutzung mit dem Namen "calculateMandel"
            OpenCLTemplate.CLCalc.Program.Kernel VectorSum = new OpenCLTemplate.CLCalc.Program.Kernel("calculateMandel");

            //Anzahl aller Pixel die Berechnet werden müssen
            int n = plBack.Width * plBack.Height;
            int[] lCalculation = new int[n];

            //Start Variablen für die Berechnung
            double[] lStartValues = new double[6];
            lStartValues[0] = _Sx;
            lStartValues[1] = _Sy;
            lStartValues[2] = _Fx;
            lStartValues[3] = _Fy;
            lStartValues[4] = plBack.Width;
            lStartValues[5] = plBack.Height;

            //Erstellt die Vektoren v1 und v2 im Geräte Speicher, mit den Startvariablen und der Anzahl aller zu berechnender Pixel als Werte
            OpenCLTemplate.CLCalc.Program.Variable lVariable1 = new OpenCLTemplate.CLCalc.Program.Variable(lCalculation);
            OpenCLTemplate.CLCalc.Program.Variable lVariable2 = new OpenCLTemplate.CLCalc.Program.Variable(lStartValues);

            //Dem Kernel sagen, welche Variablen er benutzen soll
            OpenCLTemplate.CLCalc.Program.Variable[] lArgsVariable = new OpenCLTemplate.CLCalc.Program.Variable[] { lVariable1, lVariable2 };

            //Festlegen, wieviele Worker benötigt werden. Für jedes Element einen.
            int[] lWorkers = new int[1] { n };

            //Den Kernel ausführen
            VectorSum.Execute(lArgsVariable, lWorkers);

            //Den Inhalt der Gerätevariable lCalculation in die Host Variable lVariable1 einlesen.
            lVariable1.ReadFromDeviceTo(lCalculation);

            //Ausgabe über die CPU Console -> TextBox in der Form
            int lW = plBack.Width;
            int lH = plBack.Height;
            Bitmap b = new Bitmap(lW, lH);
            for (int i = 0; i < n; i++)
            {
                int s = i % lW;
                int z = i / lW;
                b.SetPixel(s, z, _DrawColors[lCalculation[i]]);
            }
            plBack.BackgroundImage = (Image)b;
        }
Example #9
0
        public List <string[]> Run()
        {
            int size = 0;
            // Initialize result symbol list and similarity coefficients
            List <string[]> res_symb = new List <string[]>();

            for (int i = 1; i < imgs.Count(); i++)
            {
                res_symb.Add(new string[imgs[i].GetLength(0)]);
                size += imgs[i].GetLength(0);
            }


            // Buffer data
            string[] buf_res    = new string[size];
            double[] similarity = new double[size];


            var Iterate = new Action <int>(process =>
            {
                List <double[][]> alls = new List <double[][]>();

                double[][] mains = Resizer.ResizeImage(imgs[0][process], imgs[0][process].Width, imgs[0][process].Height);

                for (int i = 1; i < imgs.Count(); i++)
                {
                    for (int j = 0; j < imgs[i].GetLength(0); j++)
                    {
                        alls.Add(Resizer.ResizeImage(imgs[i][j], mains.GetLength(0), mains[0].GetLength(0)));
                    }
                }

                // Preparation
                List <double> mains1 = new List <double>();
                for (int i = 0; i < mains.GetLength(0); i++)
                {
                    for (int j = 0; j < mains[i].GetLength(0); j++)
                    {
                        mains1.Add(mains[i][j]);
                    }
                }

                List <double> alls1 = new List <double>();
                foreach (double[][] element in alls)
                {
                    for (int i = 0; i < element.GetLength(0); i++)
                    {
                        for (int j = 0; j < element[i].GetLength(0); j++)
                        {
                            alls1.Add(element[i][j]);
                        }
                    }
                }

                int[] ress = new int[alls.Count()];
                for (int i = 0; i < alls.Count(); i++)
                {
                    ress[i] = 0;
                }

                var CPUCalc = new Action(() =>
                {
                    Parallel.For(0, alls1.Count(), i =>
                    {
                        ////// First Neuron Layer
                        double buf = Math.Abs(mains1[i % mains1.Count()] - alls1[i]);

                        ////// Second Neuron Layer
                        if (buf <= 0.7)
                        {
                            Interlocked.Increment(ref ress[i / mains1.Count()]);
                        }
                    });
                });

                var GPUCalc = new Action(() =>
                {
                    OpenCLTemplate.CLCalc.Program.Variable varV1 = new OpenCLTemplate.CLCalc.Program.Variable(alls1.ToArray());
                    OpenCLTemplate.CLCalc.Program.Variable varV2 = new OpenCLTemplate.CLCalc.Program.Variable(mains1.ToArray());
                    OpenCLTemplate.CLCalc.Program.Variable varV3 = new OpenCLTemplate.CLCalc.Program.Variable(new int[1] {
                        mains1.Count()
                    });
                    OpenCLTemplate.CLCalc.Program.Variable varV4 = new OpenCLTemplate.CLCalc.Program.Variable(ress);

                    OpenCLTemplate.CLCalc.Program.Variable[] args = new OpenCLTemplate.CLCalc.Program.Variable[] { varV1, varV2, varV3, varV4 };
                    int[] workers = new int[1] {
                        alls1.Count()
                    };

                    // Cannot execute GPU from different threads at the same time
                    //lock(GPULock)
                    //{
                    VectorSum.Execute(args, workers);
                    varV4.ReadFromDeviceTo(ress);
                    //}
                });

                if (process < symbols.Count() * percent)
                {
                    CPUCalc();
                }
                else
                {
                    GPUCalc();
                }

                Parallel.For(0, alls.Count(), i =>
                {
                    lock (WriteLock)
                    {
                        ////// Third Neuron Layer
                        if ((double)ress[i] / mains1.Count() > similarity[i])
                        {
                            similarity[i] = (double)ress[i] / mains1.Count();
                            buf_res[i]    = symbols[process];
                        }
                        ;
                    }
                });
            });

            var GoCPU = new Action(() =>
            {
                Parallel.For(0, (int)((double)symbols.Count() * percent), new ParallelOptions {
                    MaxDegreeOfParallelism = cores
                }, Iterate);
            });

            var GoGPU = new Action(() =>
            {
                Parallel.For((int)((double)symbols.Count() * percent), symbols.Count(), new ParallelOptions {
                    MaxDegreeOfParallelism = cores
                }, Iterate);
            });

            Parallel.Invoke(() => GoCPU(), () => GoGPU());

            // Final
            int count = 0;

            for (int i = 0; i < res_symb.Count(); i++)
            {
                for (int j = 0; j < res_symb[i].GetLength(0); j++)
                {
                    res_symb[i][j] = buf_res[count];
                    count++;
                }
            }

            return(res_symb);
        }