Exemple #1
0
        public DenoiseAndDemoisaic(int tileSize, CudaContext ctx, CUmodule mod, bool UseCUDNN)
        {
            _tileSize = tileSize;
            start     = new StartLayer(tileSize, tileSize, 3, 1);
            final     = new FinalLayer(tileSize - 16, tileSize - 16, 3, 1, ctx, mod);

            if (UseCUDNN)
            {
                CudaDNNContext cuddn = new CudaDNNContext();
                conv1 = new ConvolutionalLayer(tileSize, tileSize, 3, tileSize - 8, tileSize - 8, 64, 1, 9, 9, ConvolutionalLayer.Activation.PRelu, cuddn, ctx, mod);
                conv2 = new ConvolutionalLayer(tileSize - 8, tileSize - 8, 64, tileSize - 12, tileSize - 12, 64, 1, 5, 5, ConvolutionalLayer.Activation.PRelu, cuddn, ctx, mod);
                conv3 = new ConvolutionalLayer(tileSize - 12, tileSize - 12, 64, tileSize - 16, tileSize - 16, 3, 1, 5, 5, ConvolutionalLayer.Activation.None, cuddn, ctx, mod);
                start.ConnectFollowingLayer(conv1);
                conv1.ConnectFollowingLayer(conv2);
                conv2.ConnectFollowingLayer(conv3);
                conv3.ConnectFollowingLayer(final);
            }
            else
            {
                conv1NPP = new ConvolutionalLayerNPP(tileSize, tileSize, 3, tileSize - 8, tileSize - 8, 64, 1, 9, 9, ConvolutionalLayerNPP.Activation.PRelu, ctx, mod);
                conv2NPP = new ConvolutionalLayerNPP(tileSize - 8, tileSize - 8, 64, tileSize - 12, tileSize - 12, 64, 1, 5, 5, ConvolutionalLayerNPP.Activation.PRelu, ctx, mod);
                conv3NPP = new ConvolutionalLayerNPP(tileSize - 12, tileSize - 12, 64, tileSize - 16, tileSize - 16, 3, 1, 5, 5, ConvolutionalLayerNPP.Activation.None, ctx, mod);
                start.ConnectFollowingLayer(conv1NPP);
                conv1NPP.ConnectFollowingLayer(conv2NPP);
                conv2NPP.ConnectFollowingLayer(conv3NPP);
                conv3NPP.ConnectFollowingLayer(final);
            }

            tileAsPlanes = new CudaDeviceVariable <float>(tileSize * tileSize * 3);
            tile         = new NPPImage_32fC3(tileSize, tileSize);
        }
        public float RunSafe(NPPImage_32fC3 img)
        {
            this.BlockDimensions = new dim3(16, 16, 1);
            this.SetComputeSize((uint)(img.WidthRoi), (uint)(img.HeightRoi), 1);

            return(this.Run(img.DevicePointerRoi, img.WidthRoi, img.HeightRoi, img.Pitch));
        }
Exemple #3
0
        private void Form1_Load(object sender, EventArgs e)
        {
            ctx = new PrimaryContext();
            ctx.SetCurrent();

            modPRelu   = ctx.LoadModulePTX("PRelu.ptx");
            modDeBayer = ctx.LoadModulePTX("DeBayer.ptx");
            modColor   = ctx.LoadModulePTX("ImageColorProcessing.ptx");

            createBayerKernel       = new CreateBayerWithNoiseKernel(ctx, modDeBayer);
            deBayerGreenKernel      = new DeBayerGreenKernel(modDeBayer, ctx);
            deBayerRedBlueKernel    = new DeBayerRedBlueKernel(modDeBayer, ctx);
            setupCurandKernel       = new SetupCurandKernel(ctx, modDeBayer);
            highlightRecoveryKernel = new HighlightRecoveryKernel(modColor, ctx);
            camToXYZKernel          = new ConvertCamToXYZKernel(modColor, ctx);
            convertRGBTosRGBKernel  = new ConvertRGBTosRGBKernel(modColor, ctx);

            //constant variable is set for the entire module!
            createBayerKernel.BayerPattern = new BayerColor[] { BayerColor.Red, BayerColor.Green, BayerColor.Green, BayerColor.Blue };

            //If you do not have CUDNN, set the last parameter to false (use NPP instead)
            denoiseAndDemoisaic = new DenoiseAndDemoisaic(TileSize, ctx, modPRelu, true);
            CuRandStates        = new CudaDeviceVariable <byte>(TileSize * TileSize * 48); //one state has the size of 48 bytes
            setupCurandKernel.RunSafe(CuRandStates, TileSize * TileSize);
            tile = new NPPImage_32fC3(TileSize, TileSize);
            cmb_IsoValue.SelectedIndex = 0;
        }
        /*
         *
         * float3 * __restrict__ inOutImg,
         * const float3 * __restrict__ finalImg,
         * const float3 * __restrict__ weight,
         * int imgWidth,
         * int imgHeight,
         * int imgPitch,
         * float threshold
         */

        public float RunSafe(NPPImage_32fC3 img, NPPImage_32fC3 finalImg, NPPImage_32fC3 weights, float threashold)
        {
            this.BlockDimensions = new dim3(16, 16, 1);
            this.SetComputeSize((uint)(img.WidthRoi), (uint)(img.HeightRoi), 1);

            return(this.Run(img.DevicePointerRoi, finalImg.DevicePointerRoi, weights.DevicePointerRoi, img.WidthRoi, img.HeightRoi, img.Pitch, threashold));
        }
        public float RunSafe(CudaDeviceVariable <ushort> dataIn, NPPImage_32fC3 imgOut, NPPImage_32fC3 totalWeights, NPPImage_32fC4 certaintyMask, NPPImage_32fC3 kernelParam, NPPImage_32fC2 shifts, float3 whiteLevel, float3 blackLevel)
        {
            SetComputeSize((uint)imgOut.WidthRoi, (uint)imgOut.HeightRoi);

            return(base.Run(dataIn.DevicePointer, imgOut.DevicePointerRoi, totalWeights.DevicePointerRoi,
                            certaintyMask.DevicePointerRoi, kernelParam.DevicePointerRoi, shifts.DevicePointerRoi,
                            whiteLevel, blackLevel, imgOut.WidthRoi, imgOut.HeightRoi, imgOut.Pitch, certaintyMask.Pitch, shifts.Pitch));
        }
Exemple #6
0
        private void AllocateImagesNPP(Bitmap size)
        {
            int w = size.Width;
            int h = size.Height;

            if (inputImage8uC3 == null)
            {
                inputImage8uC1 = new NPPImage_8uC1(w, h);
                inputImage8uC3 = new NPPImage_8uC3(w, h);
                inputImage8uC4 = new NPPImage_8uC4(w, h);
                imageBayer     = new NPPImage_32fC1(w, h);
                inputImage32f  = new NPPImage_32fC3(w, h);
                noisyImage8u   = new NPPImage_8uC3(w, h);
                noiseImage32f  = new NPPImage_32fC3(w, h);
                resultImage8u  = new NPPImage_8uC3(w, h);
                resultImage32f = new NPPImage_32fC3(w, h);
                return;
            }

            if (inputImage8uC3.Width >= w && inputImage8uC3.Height >= h)
            {
                inputImage8uC1.SetRoi(0, 0, w, h);
                inputImage8uC3.SetRoi(0, 0, w, h);
                inputImage8uC4.SetRoi(0, 0, w, h);
                imageBayer.SetRoi(0, 0, w, h);
                inputImage32f.SetRoi(0, 0, w, h);
                noisyImage8u.SetRoi(0, 0, w, h);
                noiseImage32f.SetRoi(0, 0, w, h);
                resultImage8u.SetRoi(0, 0, w, h);
                resultImage32f.SetRoi(0, 0, w, h);
            }
            else
            {
                inputImage8uC1.Dispose();
                inputImage8uC3.Dispose();
                inputImage8uC4.Dispose();
                imageBayer.Dispose();
                inputImage32f.Dispose();
                noisyImage8u.Dispose();
                noiseImage32f.Dispose();
                resultImage8u.Dispose();
                resultImage32f.Dispose();

                inputImage8uC1 = new NPPImage_8uC1(w, h);
                inputImage8uC3 = new NPPImage_8uC3(w, h);
                inputImage8uC4 = new NPPImage_8uC4(w, h);
                imageBayer     = new NPPImage_32fC1(w, h);
                inputImage32f  = new NPPImage_32fC3(w, h);
                noisyImage8u   = new NPPImage_8uC3(w, h);
                noiseImage32f  = new NPPImage_32fC3(w, h);
                resultImage8u  = new NPPImage_8uC3(w, h);
                resultImage32f = new NPPImage_32fC3(w, h);
            }
        }
Exemple #7
0
        public float RunSafe(NPPImage_32fC3 img, float[] ColorMatrix)
        {
            float[] RgbToXyz = ColorMatrix;
            float3  xyzX     = new float3(RgbToXyz[0], RgbToXyz[1], RgbToXyz[2]);
            float3  xyzY     = new float3(RgbToXyz[3], RgbToXyz[4], RgbToXyz[5]);
            float3  xyzZ     = new float3(RgbToXyz[6], RgbToXyz[7], RgbToXyz[8]);

            //const int width, const int height, float3 *inOutImage, int strideOut, float3 xyzX, float3 xyzY, float3 xyzZ
            SetComputeSize((uint)img.WidthRoi, (uint)img.HeightRoi, 1);
            return(base.Run(img.WidthRoi, img.HeightRoi, img.DevicePointerRoi, img.Pitch, xyzX, xyzY, xyzZ));
        }
        /*
         *
         * const float3* __restrict__ rawImgRef,
         * const float3* __restrict__ rawImgMoved,
         * float3* __restrict__ robustnessMask,
         * cudaTextureObject_t texUV,
         * int imgWidth,
         * int imgHeight,
         * int imgPitch,
         * float alpha,
         * float beta)
         */
        public float RunSafe(NPPImage_32fC3 rawImgRef, NPPImage_32fC3 rawImgMoved, NPPImage_32fC4 robustnessMask, NPPImage_32fC2 shift, float alpha, float beta, float thresholdM)
        {
            this.BlockDimensions = new dim3(8, 8, 1);
            this.SetComputeSize((uint)(rawImgRef.WidthRoi), (uint)(rawImgRef.HeightRoi), 1);
            this.DynamicSharedMemory = BlockDimensions.x * BlockDimensions.y * float3.SizeOf * 3 * 3;

            CudaResourceDesc      descShift    = new CudaResourceDesc(shift);
            CudaTextureDescriptor texDescShift = new CudaTextureDescriptor(CUAddressMode.Mirror, CUFilterMode.Linear, CUTexRefSetFlags.NormalizedCoordinates);
            CudaTexObject         texShift     = new CudaTexObject(descShift, texDescShift);


            float t = this.Run(rawImgRef.DevicePointerRoi, rawImgMoved.DevicePointerRoi, robustnessMask.DevicePointerRoi, texShift.TexObject, rawImgRef.WidthRoi,
                               rawImgRef.HeightRoi, rawImgRef.Pitch, robustnessMask.Pitch, alpha, beta, thresholdM);

            texShift.Dispose();

            return(t);
        }
Exemple #9
0
        public void RunImage(NPPImage_32fC3 input, NPPImage_32fC3 output)
        {
            NppiRect roiOrig = new NppiRect(input.PointRoi, input.SizeRoi);

            output.Set(new float[] { 0, 0, 0 });
            IEnumerable <Tiler.RoiInputOutput> rois = Tiler.GetROIs(new NppiRect(new NppiPoint(8, 8), new NppiSize(input.WidthRoi - 16, input.HeightRoi - 16)), _tileSize, 8);

            foreach (var item in rois)
            {
                input.SetRoi(item.inputROI);
                output.SetRoi(item.positionInFinalImage);
                tile.ResetRoi();

                input.Copy(tile);

                NPPImage_32fC1 npp32fCR = new NPPImage_32fC1(tileAsPlanes.DevicePointer, _tileSize, _tileSize, _tileSize * sizeof(float));
                NPPImage_32fC1 npp32fCG = new NPPImage_32fC1(tileAsPlanes.DevicePointer + (_tileSize * _tileSize * sizeof(float)), _tileSize, _tileSize, _tileSize * sizeof(float));
                NPPImage_32fC1 npp32fCB = new NPPImage_32fC1(tileAsPlanes.DevicePointer + 2 * (_tileSize * _tileSize * sizeof(float)), _tileSize, _tileSize, _tileSize * sizeof(float));

                tile.Copy(npp32fCR, 0);
                tile.Copy(npp32fCG, 1);
                tile.Copy(npp32fCB, 2);

                start.Inference(tileAsPlanes);

                CudaDeviceVariable <float> res = final.GetResult();
                int size = _tileSize - 16;
                npp32fCR = new NPPImage_32fC1(res.DevicePointer, size, size, size * sizeof(float));
                npp32fCG = new NPPImage_32fC1(res.DevicePointer + (size * size * sizeof(float)), size, size, size * sizeof(float));
                npp32fCB = new NPPImage_32fC1(res.DevicePointer + 2 * (size * size * sizeof(float)), size, size, size * sizeof(float));

                tile.SetRoi(0, 0, _tileSize - 16, _tileSize - 16);

                npp32fCR.Copy(tile, 0);
                npp32fCG.Copy(tile, 1);
                npp32fCB.Copy(tile, 2);

                tile.SetRoi(item.outputROI);
                tile.Copy(output);
            }
            input.SetRoi(roiOrig);
            output.SetRoi(roiOrig);
        }
        public float RunSafe(CudaDeviceVariable <ushort> dataIn, NPPImage_32fC3 imgOut, NPPImage_32fC3 totalWeights, NPPImage_32fC4 certaintyMask, NPPImage_32fC4 kernelParam, NPPImage_32fC2 shifts, float3 whiteLevel, float3 blackLevel)
        {
            SetComputeSize((uint)imgOut.WidthRoi, (uint)imgOut.HeightRoi);

            CudaResourceDesc      descKernel    = new CudaResourceDesc(kernelParam);
            CudaTextureDescriptor texDescKernel = new CudaTextureDescriptor(CUAddressMode.Clamp, CUFilterMode.Linear, CUTexRefSetFlags.NormalizedCoordinates);
            CudaTexObject         texKernel     = new CudaTexObject(descKernel, texDescKernel);

            CudaResourceDesc      descShift    = new CudaResourceDesc(shifts);
            CudaTextureDescriptor texDescShift = new CudaTextureDescriptor(CUAddressMode.Mirror, CUFilterMode.Linear, CUTexRefSetFlags.NormalizedCoordinates);
            CudaTexObject         texShift     = new CudaTexObject(descShift, texDescShift);

            float t = base.Run(dataIn.DevicePointer, imgOut.DevicePointerRoi, totalWeights.DevicePointerRoi,
                               certaintyMask.DevicePointerRoi, texKernel.TexObject, texShift.TexObject,
                               whiteLevel, blackLevel, imgOut.WidthRoi, imgOut.HeightRoi, imgOut.Pitch, certaintyMask.Pitch, kernelParam.Pitch, shifts.Pitch);

            texShift.Dispose();
            texKernel.Dispose();
            return(t);
        }
Exemple #11
0
 public float RunSafe(NPPImage_32fC3 img, float3 whiteBalanceFactors, float maxMultiplier)
 {
     //const int width, const int height, float3 *inOutImage, int strideOut, float3 WhiteBalanceFactors
     SetComputeSize((uint)img.WidthRoi, (uint)img.HeightRoi, 1);
     return(base.Run(img.WidthRoi, img.HeightRoi, img.DevicePointerRoi, img.Pitch, whiteBalanceFactors, maxMultiplier));
 }
 public float RunSafe(NPPImage_32fC3 kernelImg, float Dth, float Dtr, float kDetail, float kDenoise, float kStretch, float kShrink)
 {
     this.SetComputeSize((uint)(kernelImg.WidthRoi), (uint)(kernelImg.HeightRoi), 1);
     return(this.Run(kernelImg.DevicePointerRoi, kernelImg.WidthRoi, kernelImg.HeightRoi, kernelImg.Pitch, Dth, Dtr, kDetail, kDenoise, kStretch, kShrink));
 }
 public float RunSafe(NPPImage_32fC1 imgDx, NPPImage_32fC1 imgDy, NPPImage_32fC3 outImg)
 {
     this.SetComputeSize((uint)(outImg.WidthRoi), (uint)(outImg.HeightRoi), 1);
     return(this.Run(imgDx.DevicePointerRoi, imgDy.DevicePointerRoi, outImg.DevicePointerRoi, outImg.WidthRoi, outImg.HeightRoi, imgDx.Pitch, outImg.Pitch));
 }
 /// <summary>
 /// 16-bit floating point to 32-bit conversion.
 /// </summary>
 /// <param name="dst">Destination image</param>
 public void Convert(NPPImage_32fC3 dst)
 {
     status = NPPNativeMethods.NPPi.BitDepthConversion.nppiConvert_16f32f_C3R(_devPtrRoi, _pitch, dst.DevicePointerRoi, dst.Pitch, _sizeRoi);
     Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "nppiConvert_16f32f_C3R", status));
     NPPException.CheckNppStatus(status, this);
 }
Exemple #15
0
 public float RunSafe(NPPImage_32fC1 imgIn, NPPImage_32fC3 imgOut, float3 blackPoint, float3 scale)
 {
     //const int width, const int height, const float* __restrict__ imgIn, int strideIn, float3 *outImage, int strideOut, float3 blackPoint, float3 scale
     SetComputeSize((uint)imgIn.Width, (uint)imgIn.Height, 1);
     return(base.Run(imgIn.Width, imgIn.Height, imgIn.DevicePointer, imgIn.Pitch, imgOut.DevicePointer, imgOut.Pitch, blackPoint, scale));
 }
Exemple #16
0
 public float RunSafe(NPPImage_32fC3 imgIn, NPPImage_32fC1 imgOut)
 {
     SetComputeSize((uint)imgIn.Width, (uint)imgIn.Height, 1);
     return(base.Run(imgIn.DevicePointer, imgOut.DevicePointer, imgIn.Width, imgIn.Height, imgIn.Pitch, imgOut.Pitch));
 }
Exemple #17
0
 public float RunSafe(CudaDeviceVariable <ushort> imgIn, NPPImage_32fC3 imgOut, float[] maxVal, float[] minVal)
 {
     SetComputeSize((uint)imgOut.WidthRoi, (uint)imgOut.HeightRoi);
     return(base.Run(imgIn.DevicePointer, imgOut.DevicePointer, maxVal[0], maxVal[1], maxVal[2], minVal[0], minVal[1], minVal[2], imgOut.WidthRoi, imgOut.HeightRoi, imgOut.Pitch));
 }
Exemple #18
0
 public float RunSafe(CudaDeviceVariable <byte> states, NPPImage_32fC3 imgIn, NPPImage_32fC1 imgOut, float alpha, float beta)
 {
     SetComputeSize((uint)imgOut.WidthRoi, (uint)imgOut.HeightRoi);
     return(base.Run(states.DevicePointer, imgIn.DevicePointerRoi, imgOut.DevicePointerRoi, imgOut.WidthRoi, imgOut.HeightRoi, imgIn.Pitch, imgOut.Pitch, alpha, beta));
 }
Exemple #19
0
 public float RunSafe(NPPImage_32fC3 img)
 {
     //convertXYZTosRGBKernel(const int width, const int height, float3 *inOutImage, int strideOut)
     SetComputeSize((uint)img.WidthRoi, (uint)img.HeightRoi, 1);
     return(base.Run(img.WidthRoi, img.HeightRoi, img.DevicePointerRoi, img.Pitch));
 }
Exemple #20
0
        static void Main(string[] args)
        {
            CudaContext                 ctx = null;
            DeBayersSubSampleKernel     kernelDeBayersSubSample    = null;
            DeBayersSubSampleDNGKernel  kernelDeBayersSubSampleDNG = null;
            SetupCurandKernel           kernelSetupCurand          = null;
            CreateBayerWithNoiseKernel  kernelCreateBayerWithNoise = null;
            CudaDeviceVariable <ushort> rawImg;

            string outputPathOwn = @"C:\Users\kunz_\Desktop\TrainingDataNN\FromOwnDataset\";
            string outputPath5k  = @"C:\Users\kunz_\Desktop\TrainingDataNN\From5kDataset\";


            const int patchSize = 66;

            //These are the noise levels I measured for each ISO of my camera:
            double[] noiseLevels        = new double[] { 6.66667E-05, 0.0001, 0.000192308, 0.000357143, 0.000714286, 0.001388889, 0.0025 };
            string[] noiseLevelsFolders = new string[] { "ISO100", "ISO200", "ISO400", "ISO800", "ISO1600", "ISO3200", "ISO6400" };


            //Process files from my own dataset:
            string[] files = File.ReadAllLines("FileListOwnImages.txt");


            if (ctx == null)
            {
                ctx = new PrimaryContext();
                ctx.SetCurrent();
                CUmodule mod = ctx.LoadModulePTX("DeBayer.ptx");
                kernelDeBayersSubSample    = new DeBayersSubSampleKernel(ctx, mod);
                kernelDeBayersSubSampleDNG = new DeBayersSubSampleDNGKernel(ctx, mod);
                kernelSetupCurand          = new SetupCurandKernel(ctx, mod);
                kernelCreateBayerWithNoise = new CreateBayerWithNoiseKernel(ctx, mod);
            }

            FileStream   fs = new FileStream("ImagesCompleted.txt", FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);

            PEFFile pef = new PEFFile(files[0]);

            BayerColor[] bayerPattern = new BayerColor[pef.BayerPattern.Length];
            for (int i = 0; i < pef.BayerPattern.Length; i++)
            {
                bayerPattern[i] = (BayerColor)pef.BayerPattern[i];
            }
            kernelDeBayersSubSample.BayerPattern = bayerPattern;



            rawImg = new CudaDeviceVariable <ushort>(pef.RawWidth * pef.RawHeight);
            NPPImage_32fC3 img                 = new NPPImage_32fC3(pef.RawWidth / 2, pef.RawHeight / 2);
            NPPImage_32fC3 imgsmall            = new NPPImage_32fC3(pef.RawWidth / 8, pef.RawHeight / 8);
            NPPImage_32fC3 patch               = new NPPImage_32fC3(patchSize, patchSize);
            NPPImage_32fC1 patchBayerWithNoise = new NPPImage_32fC1(patchSize, patchSize);
            //NPPImage_8uC3 img8u = new NPPImage_8uC3(patchSize, patchSize);
            //Bitmap bmp = new Bitmap(patchSize, patchSize, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            CudaDeviceVariable <byte> states = new CudaDeviceVariable <byte>(patchSize * patchSize * 48); //one state has the size of 48 bytes

            kernelSetupCurand.RunSafe(states, patchSize * patchSize);

            NppiRect maxRoi = new NppiRect(10, 10, pef.RawWidth / 8 - 10, pef.RawHeight / 8 - 10);

            List <NppiRect> ROIs = GetROIs(maxRoi, patchSize);

            float3[] imgGroundTruth  = new float3[patchSize * patchSize];
            float[]  noisyPatchBayer = new float[patchSize * patchSize];


            int counter = 0;

            int fileCounter = 0;

            FileStream   fsWB1 = new FileStream("WhiteBalancesOwn.txt", FileMode.Create, FileAccess.Write);
            StreamWriter swWB1 = new StreamWriter(fsWB1);

            foreach (var file in files)
            {
                pef = new PEFFile(file);

                float  whiteLevelAll = pef.WhiteLevel.Value;
                float3 whitePoint    = new float3(whiteLevelAll, whiteLevelAll, whiteLevelAll);
                float3 blackPoint    = new float3(pef.BlackPoint.Value[0], pef.BlackPoint.Value[1], pef.BlackPoint.Value[3]);
                whitePoint -= blackPoint;
                float  scale   = pef.Scaling.Value;
                float3 scaling = new float3(pef.WhitePoint.Value[0] / scale, pef.WhitePoint.Value[1] / scale, pef.WhitePoint.Value[3] / scale);

                int RoiCounter = 0;
                foreach (var roi in ROIs)
                {
                    swWB1.WriteLine((counter + RoiCounter).ToString("0000000") + "\t" + scaling.x.ToString(CultureInfo.InvariantCulture) + "\t" + scaling.y.ToString(CultureInfo.InvariantCulture) + "\t" + scaling.z.ToString(CultureInfo.InvariantCulture));

                    RoiCounter++;
                }
                fileCounter++;
                Console.WriteLine("Done " + fileCounter + " of " + files.Length);


                rawImg.CopyToDevice(pef.RawImage);
                kernelDeBayersSubSample.RunSafe(rawImg, img, (float)Math.Pow(2.0, pef.BitDepth));

                imgsmall.ResetRoi();
                img.ResizeSqrPixel(imgsmall, 0.25, 0.25, 0, 0, InterpolationMode.SuperSampling);

                RoiCounter = 0;
                foreach (var roi in ROIs)
                {
                    imgsmall.SetRoi(roi);
                    imgsmall.Copy(patch);
                    patch.CopyToHost(imgGroundTruth);
                    WriteRAWFile(outputPathOwn + @"GroundTruth\img_" + (counter + RoiCounter).ToString("0000000") + ".bin", imgGroundTruth, patchSize, patchSize);

                    RoiCounter++;
                }

                RoiCounter = 0;
                foreach (var roi in ROIs)
                {
                    imgsmall.SetRoi(roi);
                    for (int i = 0; i < 7; i++)
                    {
                        imgsmall.Copy(patch);
                        kernelCreateBayerWithNoise.RunSafe(states, patch, patchBayerWithNoise, (float)noiseLevels[i], 0);

                        patchBayerWithNoise.CopyToHost(noisyPatchBayer);
                        WriteRAWFile(outputPathOwn + noiseLevelsFolders[i] + @"\img_" + (counter + RoiCounter).ToString("0000000") + ".bin", noisyPatchBayer, patchSize, patchSize);
                    }
                    RoiCounter++;
                }
                fileCounter++;
                counter += ROIs.Count;
                Console.WriteLine("Done " + fileCounter + " of " + files.Length);
                sw.WriteLine(file);
                sw.Flush();
            }
            sw.Close();
            sw.Dispose();

            swWB1.Flush();
            swWB1.Close();


            rawImg.Dispose();
            img.Dispose();
            imgsmall.Dispose();
            patch.Dispose();
            patchBayerWithNoise.Dispose();



            //Move on to DNG images from 5k dataset:
            files = File.ReadAllLines("FileListe5KKomplett.txt");
            fs    = new FileStream("ImagesCompleted5k.txt", FileMode.Append, FileAccess.Write);
            sw    = new StreamWriter(fs);

            DNGFile dng = new DNGFile(files[0]);

            int maxWidth  = 7000;
            int maxHeight = 5000;


            rawImg              = new CudaDeviceVariable <ushort>(maxWidth * maxHeight);
            img                 = new NPPImage_32fC3(maxWidth, maxHeight); // /2
            imgsmall            = new NPPImage_32fC3(maxWidth, maxHeight); // /8
            patch               = new NPPImage_32fC3(patchSize, patchSize);
            patchBayerWithNoise = new NPPImage_32fC1(patchSize, patchSize);



            imgGroundTruth  = new float3[patchSize * patchSize];
            noisyPatchBayer = new float[patchSize * patchSize];


            counter = 0;

            fileCounter = 0;
            int roiCount = 0;

            FileStream   fsWB2 = new FileStream("WhiteBalances5k.txt", FileMode.Create, FileAccess.Write);
            StreamWriter swWB2 = new StreamWriter(fsWB2);


            foreach (var file in files)
            {
                dng = new DNGFile(file);

                bayerPattern = new BayerColor[dng.BayerPattern.Length];
                for (int i = 0; i < dng.BayerPattern.Length; i++)
                {
                    bayerPattern[i] = (BayerColor)dng.BayerPattern[i];
                }
                kernelDeBayersSubSampleDNG.BayerPattern = bayerPattern;

                maxRoi = new NppiRect(10, 10, dng.RawWidth / 8 - 10, dng.RawHeight / 8 - 10);

                ROIs      = GetROIs(maxRoi, patchSize);
                roiCount += ROIs.Count;

                float[] wb         = dng.AsShotNeutral;
                int     RoiCounter = 0;
                foreach (var roi in ROIs)
                {
                    swWB2.WriteLine((counter + RoiCounter).ToString("0000000") + "\t" + (1.0f / wb[0]).ToString(CultureInfo.InvariantCulture) + "\t" + (1.0f / wb[1]).ToString(CultureInfo.InvariantCulture) + "\t" + (1.0f / wb[2]).ToString(CultureInfo.InvariantCulture));

                    RoiCounter++;
                }
                fileCounter++;
                Console.WriteLine("Done " + fileCounter + " of " + files.Length);


                Console.WriteLine("RoiCoint: " + ROIs.Count);
                unsafe
                {
                    fixed(ushort *ptr = dng.RawImage)
                    {
                        rawImg.CopyToDevice((IntPtr)ptr, 0, 0, dng.RawWidth * dng.RawHeight * 2);
                    }
                }
                NppiRect rect = new NppiRect(0, 0, dng.RawWidth / 2, dng.RawHeight / 2);
                img.SetRoi(rect);
                kernelDeBayersSubSampleDNG.RunSafe(rawImg, img, dng.MaxVal, dng.MinVal);
                rect = new NppiRect(0, 0, dng.RawWidth / 8, dng.RawHeight / 8);
                imgsmall.SetRoi(rect);
                img.ResizeSqrPixel(imgsmall, 0.25, 0.25, 0, 0, InterpolationMode.SuperSampling);

                RoiCounter = 0;
                foreach (var roi in ROIs)
                {
                    imgsmall.SetRoi(roi);
                    imgsmall.Copy(patch);
                    patch.CopyToHost(imgGroundTruth);
                    WriteRAWFile(outputPath5k + @"GroundTruth\img_" + (counter + RoiCounter).ToString("0000000") + ".bin", imgGroundTruth, patchSize, patchSize);

                    RoiCounter++;
                }

                RoiCounter = 0;
                foreach (var roi in ROIs)
                {
                    imgsmall.SetRoi(roi);
                    for (int i = 0; i < 7; i++)
                    {
                        imgsmall.Copy(patch);
                        kernelCreateBayerWithNoise.RunSafe(states, patch, patchBayerWithNoise, (float)noiseLevels[i], 0);

                        patchBayerWithNoise.CopyToHost(noisyPatchBayer);
                        WriteRAWFile(outputPath5k + noiseLevelsFolders[i] + @"\img_" + (counter + RoiCounter).ToString("0000000") + ".bin", noisyPatchBayer, patchSize, patchSize);
                    }
                    RoiCounter++;
                }
                fileCounter++;
                counter += ROIs.Count;
                Console.WriteLine("Done " + fileCounter + " of " + files.Length);
                sw.WriteLine(file);
                sw.Flush();
            }
            sw.Close();
            sw.Dispose();

            swWB2.Flush();
            swWB2.Close();
            Console.WriteLine("Total cropped ROIs: " + roiCount);


            rawImg.Dispose();
            img.Dispose();
            imgsmall.Dispose();
            patch.Dispose();
            patchBayerWithNoise.Dispose();
            states.Dispose();

            ctx.Dispose();
        }