public Snake() { using (IplImage src = new IplImage(Const.ImageCake, LoadMode.GrayScale)) using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 3)) { CvPoint[] contour = new CvPoint[100]; CvPoint center = new CvPoint(src.Width / 2, src.Height / 2); for (int i = 0; i < contour.Length; i++) { contour[i].X = (int)(center.X * Math.Cos(2 * Math.PI * i / contour.Length) + center.X); contour[i].Y = (int)(center.Y * Math.Sin(2 * Math.PI * i / contour.Length) + center.Y); } Console.WriteLine("Press any key to snake\nEsc - quit"); using (CvWindow w = new CvWindow()) { while (true) { src.SnakeImage(contour, 0.45f, 0.35f, 0.2f, new CvSize(15, 15), new CvTermCriteria(1), true); src.CvtColor(dst, ColorConversion.GrayToRgb); for (int i = 0; i < contour.Length - 1; i++) { dst.Line(contour[i], contour[i + 1], new CvColor(255, 0, 0), 2); } dst.Line(contour[contour.Length - 1], contour[0], new CvColor(255, 0, 0), 2); w.Image = dst; int key = CvWindow.WaitKey(); if (key == 27) { break; } } } } }
/// <summary> /// 画像データのファイルストレージへの書き込み /// </summary> /// <param name="fileName">書きこむXML or YAMLファイル</param> private static void SampleFileStorageWriteImage(string fileName) { // cvWrite, cvWriteComment // IplImage構造体の情報をファイルに保存する // (1)画像を読み込む using (IplImage colorImg = new IplImage(Const.ImageLenna, LoadMode.Color)) using (IplImage grayImg = new IplImage(colorImg.Size, BitDepth.U8, 1)) { // (2)ROIの設定と二値化処理 colorImg.CvtColor(grayImg, ColorConversion.BgrToGray); CvRect roi = new CvRect(0, 0, colorImg.Width / 2, colorImg.Height / 2); grayImg.SetROI(roi); colorImg.SetROI(roi); grayImg.Threshold(grayImg, 90, 255, ThresholdType.Binary); // (3)xmlファイルへの書き出し using (CvFileStorage fs = new CvFileStorage(fileName, null, FileStorageMode.Write)) { fs.WriteComment("This is a comment line.", false); fs.Write("color_img", colorImg); fs.StartNextStream(); fs.Write("gray_img", grayImg); } // (4)書きこんだxmlファイルを開く //using (Process p = Process.Start(fileName)) { // p.WaitForExit(); //} } }
/// <summary> /// 指定した分割数でそろばんを全て読み取る /// </summary> /// <param name="source">そろばんの画像</param> /// <param name="threshold">しきい値</param> /// <param name="process_img">処理画像</param> /// <returns>読み取った数値(-1はエラー)</returns> public int[] AllMatching(IplImage source, double threshold, out IplImage process_img) { // グレースケール画像 IplImage cap_gray = new IplImage(PROCESS_SIZE, BitDepth.U8, 1); // キャプチャとリサイズ,グレースケール変換 using (IplImage tmp = new IplImage( PROCESS_SIZE, source.Depth, source.NChannels)) { source.Resize(tmp); tmp.CvtColor(cap_gray, ColorConversion.BgrToGray); } int[] results = new int[DIVIDE_NUM]; int width = cap_gray.Width / (DIVIDE_NUM + 1); int margin = (int)(width * DIVIDE_MARGIN); // 領域ごとに処理 Parallel.For(0, DIVIDE_NUM, i => { IplImage tmp = new IplImage(PROCESS_SIZE, BitDepth.U8, 1); cap_gray.Copy(tmp); int x = (i + 1) * width - width / 2; // 領域を指定 CvRect rect = new CvRect(x - margin, 0, width + margin * 2, PROCESS_SIZE.Height); tmp.SetROI(rect); // 0-9の画像とMatchTemplateし一番高い値を得る results[i] = bestMatchNum(tmp, this.templates[i], threshold); // 領域の指定を解除 tmp.ResetROI(); }); // 分割線の描画 for (int i = 1; i < DIVIDE_NUM + 2; i++) { int x = i * width - width / 2; cap_gray.Line(x, 0, x, PROCESS_SIZE.Height, CvColor.White); } // 読み取り数値を表示 CvFont font = new CvFont(FontFace.HersheyDuplex, 1.0, 1.0); for (int i = 0; i < DIVIDE_NUM; i++) { if (results[i] != -1) { int x = i * width + width / 2; cap_gray.PutText(results[i].ToString(), new CvPoint(x, 30), font, CvColor.White); } } // 分割線, 読み取り数値画像を返す process_img = cap_gray; return results; }
private static void createAGrayScaleClone2() { using (var src = new IplImage(@"..\..\images\ocv02.jpg", LoadMode.Color)) //using (var dst = new IplImage(new CvSize(src.Width, src.Height), BitDepth.U8, 1)) using (var dst = new IplImage(src.Size, BitDepth.U8, 1)) { src.CvtColor(dst, ColorConversion.BgrToGray); using (new CvWindow("src", image: src)) using (new CvWindow("dst", image: dst)) { Cv.WaitKey(); } } }
public Threshold() { using (IplImage src = new IplImage(Const.ImageLenna, LoadMode.Color)) using (IplImage srcGray = new IplImage(src.Size, BitDepth.U8, 1)) using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 1)) using (CvWindow window = new CvWindow("SampleThreshold")) { src.CvtColor(srcGray, ColorConversion.BgrToGray); srcGray.Smooth(srcGray, SmoothType.Gaussian, 5); int threshold = 90; window.CreateTrackbar("threshold", threshold, 255, delegate(int pos) { srcGray.Threshold(dst, pos, 255, ThresholdType.Binary); window.Image = dst; }); srcGray.Threshold(dst, threshold, 255, ThresholdType.Binary); window.Image = dst; CvWindow.WaitKey(); } }
/// <summary> /// Генерирует радужную линейку заданных размеров /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> private static IplImage GenerateRainbowLine(int width, int height) { IplImage result = new IplImage(new CvSize(width, height), BitDepth.U8, 3); IntPtr ptr = result.ImageData; for (int x = 0; x < result.Width; x++) { for (int y = 0; y < result.Height; y++) { int offset = (result.WidthStep * y) + (x * 3); byte val = (byte)Math.Round(180.0 * (x + 1) / result.Width); Marshal.WriteByte(ptr, offset + 0, val); Marshal.WriteByte(ptr, offset + 1, 255); Marshal.WriteByte(ptr, offset + 2, 255); } } result.CvtColor(result, ColorConversion.HsvToRgb); return result; }
/// <summary> /// /// </summary> /// <param name="fileName"></param> private static void SampleFileStorageWriteImage(string fileName) { // cvWrite, cvWriteComment using (IplImage colorImg = new IplImage(FilePath.Image.Lenna, LoadMode.Color)) using (IplImage grayImg = new IplImage(colorImg.Size, BitDepth.U8, 1)) { colorImg.CvtColor(grayImg, ColorConversion.BgrToGray); CvRect roi = new CvRect(0, 0, colorImg.Width / 2, colorImg.Height / 2); grayImg.SetROI(roi); colorImg.SetROI(roi); grayImg.Threshold(grayImg, 90, 255, ThresholdType.Binary); using (CvFileStorage fs = new CvFileStorage(fileName, null, FileStorageMode.Write)) { fs.WriteComment("This is a comment line.", false); fs.Write("color_img", colorImg); fs.StartNextStream(); fs.Write("gray_img", grayImg); } } }
public Edge() { using (IplImage src = new IplImage(Const.ImageLenna, LoadMode.Color)) using (IplImage gray = new IplImage(src.Size, BitDepth.U8, 1)) using (IplImage temp = new IplImage(src.Size, BitDepth.S16, 1)) using (IplImage dstSobel = new IplImage(src.Size, BitDepth.U8, 1)) using (IplImage dstLaplace = new IplImage(src.Size, BitDepth.U8, 1)) using (IplImage dstCanny = new IplImage(src.Size, BitDepth.U8, 1)) { //src.CvtColor(gray, ColorConversion.RgbToGray); src.CvtColor(gray, ColorConversion.BgrToGray); // Sobel Cv.Sobel(gray, temp, 1, 0, ApertureSize.Size3); Cv.ConvertScaleAbs(temp, dstSobel); // Laplace Cv.Laplace(gray, temp); Cv.ConvertScaleAbs(temp, dstLaplace); // Canny Cv.Canny(gray, dstCanny, 50, 200, ApertureSize.Size3); using (new CvWindow("src", src)) using (new CvWindow("sobel", dstSobel)) using (new CvWindow("laplace", dstLaplace)) using (new CvWindow("canny", dstCanny)) { CvWindow.WaitKey(); } dstSobel.SaveImage("sobel.png"); dstLaplace.SaveImage("laplace.png"); dstCanny.SaveImage("canny.png"); } }
/// <summary> /// Отделяет изображение от фона /// </summary> /// <param name="source">Исходное изображение</param> /// <param name="destinatation">Результат разделения</param> private void separateBackground(IplImage source, IplImage destinatation) { // Преобразуем иходное изображение в HSV source.CvtColor(hsvImg, ColorConversion.RgbToHsv); // Разбиваем изображение на отельные каналы hsvImg.CvtPixToPlane(hImg, sImg, vImg, null); // Если диапазон Hue состоит из 2х частей if (BackgroundRange.HMin > BackgroundRange.HMax) { hImg.InRangeS(CvScalar.RealScalar(BackgroundRange.HMin), CvScalar.RealScalar(HsvRange.MAX_H), tmpImg); hImg.InRangeS(CvScalar.RealScalar(HsvRange.MIN_H), CvScalar.RealScalar(BackgroundRange.HMax), hImg); Cv.Or(tmpImg, hImg, hImg); } // Если диапазон Hue состоит из 1 части else hImg.InRangeS(CvScalar.RealScalar(BackgroundRange.HMin), CvScalar.RealScalar(BackgroundRange.HMax), hImg); // Ограничиваем значение остальных цветовых компонент sImg.InRangeS(CvScalar.RealScalar(BackgroundRange.SMin), CvScalar.RealScalar(BackgroundRange.SMax), sImg); vImg.InRangeS(CvScalar.RealScalar(BackgroundRange.VMin), CvScalar.RealScalar(BackgroundRange.VMax), vImg); // Формируем окончательный результат Cv.And(hImg, sImg, destinatation); Cv.And(destinatation, vImg, destinatation); Cv.Not(destinatation, destinatation); }
static void Main(string[] args) { Stopwatch timer = new Stopwatch(); IplImage bestMatch = new IplImage(); CvMat mapMatrix; CvPoint2D32f center; double[] maxArray = new double[8]; int numberOfFiles = 50;//Can change the number of input files if I want double angle = 0.0, scale = 1.0, bestAngle = 0.0; mapMatrix = new CvMat(2, 3, MatrixType.F32C1); while (fileReader < numberOfFiles)//Number of files to read in folder { uavSourceImg = new IplImage("C:\\OpenCvSharp\\SummerPractice13RotateAndScale4DataInfo2\\Testing Different UAV Inputs\\RenameFolder\\Kamien " + fileReader + ".bmp", LoadMode.AnyColor); tempImg = new IplImage("C:\\OpenCvSharp\\SummerPractice1\\SummerDatabase\\BigGoogleTemplate2.jpg", LoadMode.AnyColor);//Big template test CvRect drawRectangle = new CvRect(200, 200, 300, 300); timer.Start(); while (angle < 15.0)//Angle change while loop. Can change if necessary { while (i < 10)//Scaling while loop. Can change this if necessary. { //***********************DECLARATION //tempImg = theBigTemplate.GetSubImage(drawRectangle); CvSize destSize; graySource = new IplImage(uavSourceImg.Size, BitDepth.U8, 1); grayTemp = new IplImage(tempImg.Size, BitDepth.U8, 1); tempDestImg = new IplImage(grayTemp.Size, BitDepth.U8, 1); double minValue, maxValue; CvPoint minLoc, maxLoc; //**********************END DECLARATIONS //**********************CONVERT TO GRAY uavSourceImg.CvtColor(graySource, ColorConversion.BgrToGray); tempImg.CvtColor(grayTemp, ColorConversion.BgrToGray); //**********************END CONVERT TO GRAY //**********************ROTATION center = new CvPoint2D32f(grayTemp.Width * 0.5, grayTemp.Height * 0.5); grayTemp.Copy(tempDestImg); Cv._2DRotationMatrix(center, angle, scale, out mapMatrix); Cv.WarpAffine(grayTemp, tempDestImg, mapMatrix, Interpolation.FillOutliers, Cv.ScalarAll(255)); //**********************END ROTATION theRotatedSubTemp = tempDestImg.GetSubImage(drawRectangle); //**********************RESIZE PART CvSize size = new CvSize(graySource.Width / i, graySource.Height / i);//Manipulate the source image size CvSize size2 = new CvSize(theRotatedSubTemp.Width / i, theRotatedSubTemp.Height / i);//theRotatedSubTemp test graySourceHolder = new IplImage(size, BitDepth.U8, 1);//1 for grayholder ORIGINAL grayTempHolder = new IplImage(size2, BitDepth.U8, 1); graySource.Resize(graySourceHolder);//ORIGINAL(resize the grayscale source image before template matching) theRotatedSubTemp.Resize(grayTempHolder);//TEST theRotatedSubTemp //*********************END RESIZE PART //*********************TEMPLATE MATCHING PART destSize = new CvSize(graySourceHolder.Width - grayTempHolder.Width + 1, graySourceHolder.Height - grayTempHolder.Height + 1); //TEST RESIZE BEFORE WITH RESIZED TEMPLATE resizeDestImg = new IplImage(destSize, BitDepth.F32, 1); graySourceHolder.MatchTemplate(grayTempHolder, resizeDestImg, MatchTemplateMethod.CCoeffNormed); resizeDestImg.MinMaxLoc(out minValue, out maxValue, out minLoc, out maxLoc); graySourceHolder.Rectangle(maxLoc.X, maxLoc.Y, maxLoc.X + grayTempHolder.Width, maxLoc.Y + grayTempHolder.Height, CvColor.Red, 3);//Testing resize before with resized template //********************END TEMPLATE MATCHING PART Console.WriteLine("Divided by {0}, there was a {1} percent match", i, maxValue); if (maxValue > theBestMax) { theBestMax = maxValue; bestMatch = graySourceHolder.Clone(); bestAngle = angle; iHolder = i; } Cv.NamedWindow("Rotating Template", WindowMode.AutoSize); Cv.NamedWindow("Sub Template", WindowMode.AutoSize); Cv.ShowImage("Rotating Template", tempDestImg); Cv.ShowImage("Sub Template", theRotatedSubTemp); //Cv.WaitKey(0); Cv.WaitKey(1); i++; Cv.ReleaseData(graySourceHolder); Cv.ReleaseData(grayTempHolder); Cv.ReleaseData(tempDestImg); Cv.ReleaseData(graySource); Cv.ReleaseData(grayTemp); Cv.ReleaseData(resizeDestImg); Cv.ReleaseData(theRotatedSubTemp);//Added for big template test }//End 3rd Inner while loop angle += 1.5; //This changes the angle tilt of the template. Can change if necessary. i = 1;//This changes the scale divider. Can change if necessary. Console.WriteLine("***************************************SHIFTING TEMPLATE\n"); //Cv.DestroyAllWindows(); }//End 2nd Inner while loop //***************SHOWING RESULT INFO timer.Stop(); //This section writes the results to a text file using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\OpenCvSharp\\SummerPractice12RotateAndScale3DataInfo\\Data Info Folder\\Best Match Data.txt", true)) { file.WriteLine("{0}\t{1}\t\t{2}\t1/{3}", timer.ElapsedMilliseconds, theBestMax.ToString("#.###"), bestAngle, iHolder); } Console.WriteLine("---------RESULTS"); //*************END SHOWING RESULT INFO //*************IMPORTANT SAVES bestMatch.SaveImage("C:\\OpenCvSharp\\SummerPractice12RotateAndScale3DataInfo\\Data Info Folder\\Best Match" + fileReader.ToString() + ".jpg"); Console.WriteLine("ITEM SAVED IN DATA INFO FOLDER!"); //*************END IMPORTANT SAVES Cv.WaitKey(1); fileReader++; theBestMax = double.MinValue; iHolder = int.MinValue; bestAngle = double.MinValue; angle = 0.0; i = 1; Cv.ReleaseData(bestMatch);//TEST if(fileReader < numberOfFiles) Console.WriteLine("Switching Input..."); }//End while loop }