public Text() { // cvInitFont, cvPutText // フォントを初期化して,テキストを描画する List<FontFace> font_face = new List<FontFace>( (FontFace[])Enum.GetValues(typeof(FontFace)) ); font_face.Remove(FontFace.Italic); // (1)画像を確保し初期化する using (IplImage img = Cv.CreateImage(new CvSize(450, 600), BitDepth.U8, 3)) { Cv.Zero(img); // (2)フォント構造体を初期化する CvFont[] font = new CvFont[font_face.Count * 2]; for (int i = 0; i < font.Length; i += 2) { font[i] = new CvFont(font_face[i / 2], 1.0, 1.0); font[i + 1] = new CvFont(font_face[i / 2] | FontFace.Italic, 1.0, 1.0); } // (3)フォントを指定して,テキストを描画する for (int i = 0; i < font.Length; i++) { CvColor rcolor = CvColor.Random(); Cv.PutText(img, "OpenCV sample code", new CvPoint(15, (i + 1) * 30), font[i], rcolor); } // (4)画像の表示,キーが押されたときに終了 using (CvWindow w = new CvWindow(img)) { CvWindow.WaitKey(0); } } }
public VideoWriter() { // (1)カメラに対するキャプチャ構造体を作成する using (CvCapture capture = CvCapture.FromCamera(0)) { // (2)キャプチャサイズを取得する(この設定は,利用するカメラに依存する) int width = capture.FrameWidth; int height = capture.FrameHeight; double fps = 15;//capture.Fps; // (3)ビデオライタ構造体を作成する using (CvVideoWriter writer = new CvVideoWriter("cap.avi", FourCC.Prompt, fps, new CvSize(width, height))) using (CvFont font = new CvFont(FontFace.HersheyComplex, 0.7, 0.7)) using (CvWindow window = new CvWindow("Capture", WindowMode.AutoSize)) { // (4)カメラから画像をキャプチャし,ファイルに書き出す for (int frames = 0; ; frames++) { IplImage frame = capture.QueryFrame(); string str = string.Format("{0}[frame]", frames); frame.PutText(str, new CvPoint(10, 20), font, new CvColor(0, 255, 100)); writer.WriteFrame(frame); window.ShowImage(frame); int key = CvWindow.WaitKey((int)(1000 / fps)); if (key == '\x1b') { break; } } } } }
public FitLine() { CvSize imageSize = new CvSize(500, 500); // cvFitLine CvPoint2D32f[] points = GetRandomPoints(20, imageSize); CvLine2D line = Cv.FitLine2D(points, DistanceType.L2, 0, 0.01, 0.01); using (IplImage img = new IplImage(imageSize, BitDepth.U8, 3)) { img.Zero(); // draw line { CvPoint pt1, pt2; line.FitSize(img.Width, img.Height, out pt1, out pt2); img.Line(pt1, pt2, CvColor.Green, 1, LineType.Link8); } // draw points and distances using (CvFont font = new CvFont(FontFace.HersheySimplex, 0.33, 0.33)) { foreach (CvPoint2D32f p in points) { double d = line.Distance(p); img.Circle(p, 2, CvColor.White, -1, LineType.AntiAlias); img.PutText(string.Format("{0:F1}", d), new CvPoint((int) (p.X + 3), (int) (p.Y + 3)), font, CvColor.Green); } } CvWindow.ShowImages(img); } }
public Contour() { // cvContourArea, cvArcLength // 輪郭によって区切られた領域の面積と,輪郭の長さを求める const int SIZE = 500; // (1)画像を確保し初期化する using (CvMemStorage storage = new CvMemStorage()) using (IplImage img = new IplImage(SIZE, SIZE, BitDepth.U8, 3)) { img.Zero(); // (2)点列を生成する CvSeq<CvPoint> points = new CvSeq<CvPoint>(SeqType.PolyLine, storage); CvRNG rng = new CvRNG((ulong)DateTime.Now.Ticks); double scale = rng.RandReal() + 0.5; CvPoint pt0 = new CvPoint { X = (int)(Math.Cos(0) * SIZE / 4 * scale + SIZE / 2), Y = (int)(Math.Sin(0) * SIZE / 4 * scale + SIZE / 2) }; img.Circle(pt0, 2, CvColor.Green); points.Push(pt0); for (int i = 1; i < 20; i++) { scale = rng.RandReal() + 0.5; CvPoint pt1 = new CvPoint { X = (int)(Math.Cos(i * 2 * Math.PI / 20) * SIZE / 4 * scale + SIZE / 2), Y = (int)(Math.Sin(i * 2 * Math.PI / 20) * SIZE / 4 * scale + SIZE / 2) }; img.Line(pt0, pt1, CvColor.Green, 2); pt0.X = pt1.X; pt0.Y = pt1.Y; img.Circle(pt0, 3, CvColor.Green, Cv.FILLED); points.Push(pt0); } img.Line(pt0, points.GetSeqElem(0).Value, CvColor.Green, 2); // (3)包含矩形,面積,長さを求める CvRect rect = points.BoundingRect(false); double area = points.ContourArea(); double length = points.ArcLength(CvSlice.WholeSeq, 1); // (4)結果を画像に書き込む img.Rectangle(new CvPoint(rect.X, rect.Y), new CvPoint(rect.X + rect.Width, rect.Y + rect.Height), CvColor.Red, 2); string text_area = string.Format("Area: wrect={0}, contour={1}", rect.Width * rect.Height, area); string text_length = string.Format("Length: rect={0}, contour={1}", 2 * (rect.Width + rect.Height), length); using (CvFont font = new CvFont(FontFace.HersheySimplex, 0.7, 0.7, 0, 1, LineType.AntiAlias)) { img.PutText(text_area, new CvPoint(10, img.Height - 30), font, CvColor.White); img.PutText(text_length, new CvPoint(10, img.Height - 10), font, CvColor.White); } // (5)画像を表示,キーが押されたときに終了 using (CvWindow window = new CvWindow("BoundingRect", WindowMode.AutoSize)) { window.Image = img; CvWindow.WaitKey(0); } } }
public Moments() { // (1)画像を読み込む.3チャンネル画像の場合はCOIがセットされていなければならない using (IplImage srcImg = new IplImage(Const.ImageLenna, LoadMode.AnyColor | LoadMode.AnyDepth)) { if (srcImg.NChannels == 3 && srcImg.COI == 0) { srcImg.COI = 1; } // (2)入力画像の3次までの画像モーメントを計算する CvMoments moments = new CvMoments(srcImg, false); srcImg.COI = 0; // (3)モーメントやHuモーメント不変量を,得られたCvMoments構造体の値を使って計算する. double spatialMoment = moments.GetSpatialMoment(0, 0); double centralMoment = moments.GetCentralMoment(0, 0); double normCMoment = moments.GetNormalizedCentralMoment(0, 0); CvHuMoments huMoments = new CvHuMoments(moments); // (4)得られたモーメントやHuモーメント不変量を文字として画像に描画 using (CvFont font = new CvFont(FontFace.HersheySimplex, 1.0, 1.0, 0, 2, LineType.Link8)) { string[] text = new string[10]; text[0] = string.Format("spatial={0:F3}", spatialMoment); text[1] = string.Format("central={0:F3}", centralMoment); text[2] = string.Format("norm={0:F3}", spatialMoment); text[3] = string.Format("hu1={0:F10}", huMoments.Hu1); text[4] = string.Format("hu2={0:F10}", huMoments.Hu2); text[5] = string.Format("hu3={0:F10}", huMoments.Hu3); text[6] = string.Format("hu4={0:F10}", huMoments.Hu4); text[7] = string.Format("hu5={0:F10}", huMoments.Hu5); text[8] = string.Format("hu6={0:F10}", huMoments.Hu6); text[9] = string.Format("hu7={0:F10}", huMoments.Hu7); CvSize textSize = font.GetTextSize(text[0]); for (int i = 0; i < 10; i++) { srcImg.PutText(text[i], new CvPoint(10, (textSize.Height + 3) * (i + 1)), font, CvColor.Black); } } // (5)入力画像とモーメント計算結果を表示,キーが押されたときに終了 using (CvWindow window = new CvWindow("Image", WindowMode.AutoSize)) { window.ShowImage(srcImg); Cv.WaitKey(0); } } }
public Moments() { using (IplImage srcImg = new IplImage(FilePath.Image.Lenna, LoadMode.AnyColor | LoadMode.AnyDepth)) { if (srcImg.NChannels == 3 && srcImg.COI == 0) { srcImg.COI = 1; } CvMoments moments = new CvMoments(srcImg, false); srcImg.COI = 0; double spatialMoment = moments.GetSpatialMoment(0, 0); double centralMoment = moments.GetCentralMoment(0, 0); double normCMoment = moments.GetNormalizedCentralMoment(0, 0); CvHuMoments huMoments = new CvHuMoments(moments); // drawing using (CvFont font = new CvFont(FontFace.HersheySimplex, 1.0, 1.0, 0, 2, LineType.Link8)) { string[] text = new string[10]; text[0] = string.Format("spatial={0:F3}", spatialMoment); text[1] = string.Format("central={0:F3}", centralMoment); text[2] = string.Format("norm={0:F3}", spatialMoment); text[3] = string.Format("hu1={0:F10}", huMoments.Hu1); text[4] = string.Format("hu2={0:F10}", huMoments.Hu2); text[5] = string.Format("hu3={0:F10}", huMoments.Hu3); text[6] = string.Format("hu4={0:F10}", huMoments.Hu4); text[7] = string.Format("hu5={0:F10}", huMoments.Hu5); text[8] = string.Format("hu6={0:F10}", huMoments.Hu6); text[9] = string.Format("hu7={0:F10}", huMoments.Hu7); CvSize textSize = font.GetTextSize(text[0]); for (int i = 0; i < 10; i++) { srcImg.PutText(text[i], new CvPoint(10, (textSize.Height + 3) * (i + 1)), font, CvColor.Black); } } using (var window = new CvWindow("Image", WindowMode.AutoSize)) { window.ShowImage(srcImg); Cv.WaitKey(0); } } }
/// <summary> /// 画像上にテキストを描画します. /// </summary> /// <param name="img">文字列描画の対象となる画像.</param> /// <param name="text">画像上に描画されるテキスト.</param> /// <param name="location">画像上のテキストの開始位置 Point(x,y).</param> /// <param name="font">テキストを描画するのに利用されるフォント.</param> #else /// <summary> /// Create the font to be used to draw text on an image /// </summary> /// <param name="img">Image where the text should be drawn</param> /// <param name="text">Text to write on the image</param> /// <param name="location">Point(x,y) where the text should start on the image</param> /// <param name="font">Font to use to draw the text</param> #endif public static void AddText(CvArr img, string text, CvPoint location, CvFont font) { if (img == null) { throw new ArgumentNullException("img"); } if (text == null) { throw new ArgumentNullException("text"); } if (font == null) { throw new ArgumentNullException("font"); } NativeMethods.cvAddText(img.CvPtr, text, location, font.CvPtr); }
/// <summary> /// 画像上にテキストを描画します. /// </summary> /// <param name="img">文字列描画の対象となる画像.</param> /// <param name="text">画像上に描画されるテキスト.</param> /// <param name="location">画像上のテキストの開始位置 Point(x,y).</param> /// <param name="font">テキストを描画するのに利用されるフォント.</param> #else /// <summary> /// Create the font to be used to draw text on an image /// </summary> /// <param name="img">Image where the text should be drawn</param> /// <param name="text">Text to write on the image</param> /// <param name="location">Point(x,y) where the text should start on the image</param> /// <param name="font">Font to use to draw the text</param> #endif public static void AddText(CvArr img, string text, CvPoint location, CvFont font) { if (img == null) { throw new ArgumentNullException(nameof(img)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } if (font == null) { throw new ArgumentNullException(nameof(font)); } NativeMethods.cvAddText(img.CvPtr, text, location, font.CvPtr); GC.KeepAlive(img); GC.KeepAlive(font); }
void RenderTracks(IplImage imgDest) { foreach (Trak track in tracks) { CvFont font = new CvFont(FontFace.HersheyDuplex, 0.5, 0.5, 0, 1); if (track.Inactive == 0) { Cv.PutText(imgDest, track.Label.ToString(), track.Centroid, font, CvColor.Green); } if (track.Inactive > 0) Cv.Rectangle( imgDest, new CvPoint(track.MinX, track.MinY), new CvPoint(track.MaxX - 1, track.MaxY - 1), new CvColor(0, 0, 50)); else Cv.Rectangle( imgDest, new CvPoint(track.MinX, track.MinY), new CvPoint(track.MaxX - 1, track.MaxY - 1), new CvColor(0, 0, 255)); } }
/// <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; }
/// <summary> /// 画像上にテキストを描画します. /// </summary> /// <param name="img">文字列描画の対象となる画像.</param> /// <param name="text">画像上に描画されるテキスト.</param> /// <param name="location">画像上のテキストの開始位置 Point(x,y).</param> /// <param name="font">テキストを描画するのに利用されるフォント.</param> #else /// <summary> /// Create the font to be used to draw text on an image /// </summary> /// <param name="img">Image where the text should be drawn</param> /// <param name="text">Text to write on the image</param> /// <param name="location">Point(x,y) where the text should start on the image</param> /// <param name="font">Font to use to draw the text</param> #endif public static void AddText(CvArr img, string text, CvPoint location, CvFont font) { if (img == null) throw new ArgumentNullException("img"); if (text == null) throw new ArgumentNullException("text"); if (font == null) throw new ArgumentNullException("font"); NativeMethods.cvAddText(img.CvPtr, text, location, font.CvPtr); }
void debug描画(ref IplImage src) { string[] debug = Tobii.debug.Split('\n'); CvFont フォント = new CvFont(FontFace.HersheyComplex, 0.5, 0.5); Cv.PutText(src, debug[0], new CvPoint(10, 20), フォント, new CvColor(255, 255, 255)); Cv.PutText(src, debug[1], new CvPoint(10, 40), フォント, new CvColor(255, 255, 255)); Cv.PutText(src, debug[2], new CvPoint(10, 60), フォント, new CvColor(255, 255, 255)); }
/// <summary> /// Classical Multidimensional Scaling /// </summary> public MDS() { // creates distance matrix int size = CityDistance.GetLength(0); CvMat t = new CvMat(size, size, MatrixType.F64C1, CityDistance); // adds Torgerson's additive constant to t t += Torgerson(t); // squares all elements of t t.Mul(t, t); // centering matrix G CvMat g = CenteringMatrix(size); // calculates inner product matrix B CvMat b = g * t * g.T() * -0.5; // calculates eigenvalues and eigenvectors of B CvMat vectors = new CvMat(size, size, MatrixType.F64C1); CvMat values = new CvMat(size, 1, MatrixType.F64C1); Cv.EigenVV(b, vectors, values); for (int r = 0; r < values.Rows; r++) { if (values[r] < 0) values[r] = 0; } // multiplies sqrt(eigenvalue) by eigenvector CvMat result = vectors.GetRows(0, 2); for (int r = 0; r < result.Rows; r++) { for (int c = 0; c < result.Cols; c++) { result[r, c] *= Math.Sqrt(values[r]); } } // scaling Cv.Normalize(result, result, 0, 800, NormType.MinMax); //Console.WriteLine(vectors); //Console.WriteLine(values); //Console.WriteLine(result); // opens a window using (IplImage img = new IplImage(800, 600, BitDepth.U8, 3)) using (CvFont font = new CvFont(FontFace.HersheySimplex, 0.5f, 0.5f)) using (CvWindow window = new CvWindow("City Location Estimation")) { img.Zero(); for (int c = 0; c < size; c++) { double x = result[0, c]; double y = result[1, c]; x = x * 0.7 + img.Width * 0.1; y = y * 0.7 + img.Height * 0.1; img.Circle((int)x, (int)y, 5, CvColor.Red, -1); img.PutText(CityNames[c], new CvPoint((int)x+5, (int)y+10), font, CvColor.White); } window.Image = img; Cv.WaitKey(); } }
static void Main(string[] args) { // CreateCameraCaptureの引数はカメラのIndex(通常は0から始まる) using (var capture = Cv.CreateCameraCapture(0)) { Console.WriteLine("Hit any key to quit"); /* double fps=12.0; int interval=1; double zoom=1.0; string OutputFile; */ double fps ; int interval ; double zoom=1.0 ; string OutputFile; var opts = new Options(); bool isSuccess = CommandLine.Parser.Default.ParseArguments(args, opts); if(!isSuccess) { opts.GetUsage(); Console.WriteLine(Environment.GetCommandLineArgs()[0] + " -o Outputfilename(string) -f fps(double) -i CaptureInterval(int)"); Environment.Exit(0); } fps = opts.fps; interval = opts.interval; zoom = opts.zoom; OutputFile = opts.OutputFile; Console.WriteLine(OutputFile); if (fps > 30 | interval < 0.1) { Console.WriteLine(" :-p"); Environment.Exit(1); } Int32 codec = 0; // コーデック(AVI) IplImage frame = new IplImage(); /* double width = capture.FrameWidth/2; double height = capture.FrameHeight/2; //double width = 640, height = 240; Cv.SetCaptureProperty(capture, CaptureProperty.FrameWidth, width); Cv.SetCaptureProperty(capture, CaptureProperty.FrameHeight, height); CvSize size = new CvSize((int)width, (int)height); CvVideoWriter vw = new CvVideoWriter(OutputFile, codec, fps, size, true); */ int width = (int)(Cv.GetCaptureProperty(capture, CaptureProperty.FrameWidth)*zoom); int height = (int)(Cv.GetCaptureProperty(capture, CaptureProperty.FrameHeight)*zoom); //Cv.SetCaptureProperty(capture, CaptureProperty.FrameWidth, width); //Cv.SetCaptureProperty(capture, CaptureProperty.FrameWidth, height); //Bitmap bitmap = new Bitmap(width, height); CvSize size = new CvSize(width, height); CvVideoWriter vw = new CvVideoWriter(OutputFile, codec, fps, size, true); //CvFont font = new CvFont(FontFace.HersheyTriplex, 0.7, 0.7); //(FontFace.HersheyPlain, 1.0, 1.0, 0, 2); double fontSize; if(width>600) fontSize=1.0; else fontSize=0.5; CvFont font = new CvFont(FontFace.HersheyPlain,fontSize,fontSize); // 何かキーを押すまでは、Webカメラの画像を表示し続ける while (Cv.WaitKey(1) == -1) { System.Threading.Thread.Sleep(1000*interval); // カメラからフレームを取得 frame = Cv.QueryFrame(capture); string str = DateTime.Now.ToString(); // Window「Capture」を作って、Webカメラの画像を表示 if (frame != null) { frame.PutText(str, new CvPoint(10, 20), font, new CvColor(200,100,50)); Cv.ShowImage("Timelapse", frame); //frame.SaveImage("result.bmp"); //bitmap = BitmapConverter.ToBitmap(frame); //OpenCvSharp.IplImage ipl2 = (OpenCvSharp.IplImage)BitmapConverter.ToIplImage(bitmap); vw.WriteFrame(frame); // vw.WriteFrame(ipl2); frame.Dispose(); } } Cv.DestroyWindow("Capture"); vw.Dispose(); } }
/// <summary> /// Video writer /// </summary> /// <param name="frame"></param> /// <param name="frames"></param> public void VideoWriter(IplImage frame, int frames) { CvFont font = new CvFont(FontFace.HersheyComplex, 0.5, 0.5); string str = string.Format("{0}[Frame]", frames); frame.PutText(str, new CvPoint(10, 20), font, new CvColor(255, 0, 0)); this.writer.WriteFrame(frame); }