//static Mat pre_Prosessing() //{ // Mat fdfdfd= new Mat(); // return fdfdfd; 이미지와 배열을 리턴해줘야한다. //}//전처리하는부분 static void Main(string[] args) { Mat src = Cv2.ImRead("./samples2/209.bmp"); Mat gray = new Mat(src.Size(), MatType.CV_8UC1); Mat binary = new Mat(src.Size(), MatType.CV_8UC1); Mat dst = src.Clone(); Mat rotate = new Mat(); Mat Roi = new Mat(); double angle = default; Point[][] contours; HierarchyIndex[] hier; Mat kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3)); Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY); Cv2.Threshold(gray, binary, 40, 255, ThresholdTypes.Binary); Cv2.ImShow("aa", binary); // 존좋탱 //Point[][] contour; //HierarchyIndex[] hieracy; //Cv2.FindContours(binary, out contour, out hieracy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple); //Cv2.DrawContours(src, contour, -1, new Scalar(0, 0, 255), 3); //Cv2.ImShow("cc", src); // 진우탱 : 레이블을 계산 - 2개 초과이면 불량품 Mat ds = gray.Clone(); Mat noise = new Mat(); Cv2.Threshold(ds, ds, 195, 255, ThresholdTypes.Binary); Cv2.BitwiseXor(binary, ds, noise); Cv2.BitwiseXor(noise, ds, noise); Cv2.ImShow("noise", noise); Point[][] contour; HierarchyIndex[] hieracy; Cv2.FindContours(ds, out contour, out hieracy, RetrievalModes.CComp, ContourApproximationModes.ApproxNone); Cv2.DrawContours(src, contour, -1, new Scalar(0, 0, 255), 3); Cv2.ImShow("linecheck", src); Console.WriteLine("개수 : " + contour.Length); if (contour.Length > 2) { Console.WriteLine("불량품"); } else { Console.WriteLine("양품"); } //Cv2.ImShow("bb", binary - gray); //Cv2.MorphologyEx(binary, binary, MorphTypes.Close, kernel, new Point(-1, -1), 5); //Cv2.MorphologyEx(binary, binary, MorphTypes.Erode, kernel, new Point(-1, -1), 20); //Cv2.MorphologyEx(binary, binary, MorphTypes.Dilate, kernel, new Point(-1, -1), 20); //Cv2.FindContours(binary, out contours, out hier, RetrievalModes.External, ContourApproximationModes.ApproxTC89KCOS); //Point[] point_rect = new Point[4]; //for (int i = 0; i < contours.Length; i++) //{ // double perimeter = Cv2.ArcLength(contours[i], true); // double epsilon = perimeter * 0.04; // Point[] approx = Cv2.ApproxPolyDP(contours[i], epsilon, true); // Point[][] draw_approx = new Point[][] { approx }; // // Cv2.DrawContours(dst, contours, -1, new Scalar(0, 0, 255), 2, LineTypes.AntiAlias); // Cv2.DrawContours(dst, draw_approx, -1, new Scalar(255, 0, 0), 2, LineTypes.AntiAlias); // // 좌표를 표시하는 부분 // for (int j = 0; j < approx.Length; j++) // { // Cv2.Circle(dst, approx[j], 1, new Scalar(0, 0, 255), 3); // point_rect[j] = approx[j]; // Console.WriteLine(point_rect[j]); // } //} ////ROI를 검출하는 로직 x의 min, max 과 y의 min,max 찾기 //int max_x = 0; //int min_x = int.MaxValue; //int max_y = 0; //int min_y = int.MaxValue; //angle = calculate_angle(point_rect); //Roi = make_ROI(dst, min_y, max_y, min_x, max_x, point_rect); //rotate = Rotate_rect(Roi, angle); //Console.WriteLine(angle); //Cv2.ImShow("src", src); //Cv2.ImShow("binary", binary); //Cv2.ImShow("dst", dst); //Cv2.ImShow("Roi", Roi); //Cv2.ImShow("Rotate", rotate); Cv2.WaitKey(0); Cv2.DestroyAllWindows(); }
void Form3_FormClosed(object sender, FormClosedEventArgs e) { Cv2.DestroyAllWindows(); timer1.Enabled = true; Show(); }
public static FormExtractionResult ProcessImage(string filename, FormExtractionOptions options = null) { if (options == null) { // Assume recommanded parameters. options = new FormExtractionOptions(); } var orig = new Mat(filename); var image = new Mat(filename, ImreadModes.GrayScale); Cv2.AdaptiveThreshold(image, image, 255, AdaptiveThresholdTypes.MeanC, ThresholdTypes.Binary, 9, 4); // Resize image if too large. if (image.Width > options.ResizeWidth) { var height = options.ResizeWidth * image.Height / image.Width; Cv2.Resize(image, image, new Size(options.ResizeWidth, height)); } Cv2.BitwiseNot(image, image); Cv2.Dilate(image, image, Cv2.GetStructuringElement(MorphShapes.Cross, new Size(2, 2))); MatOfByte mat = new MatOfByte(image); MatIndexer <byte> indexer = mat.GetIndexer(); var row = image.Height; var col = image.Width; Mat newImage = new Mat(row, col, MatType.CV_8UC3); newImage.SetTo(Scalar.Black); // We must determine if it "may" be an interesting blob. Stopwatch watch = new Stopwatch(); watch.Start(); int[] imgData = new int[row * col]; for (int y = 0; y < row; y++) { for (int x = 0; x < col; x++) { imgData[y + x * row] = indexer[y, x]; } } var result = HasBoxes(imgData, row, col, options); watch.Stop(); result.Duration = watch.Elapsed; // Preview if (result.Boxes.Any() && image.Width != 0 && options.ShowDebugImage) { var img = CreateImage(result.DebugImg, hasColor: true); Cv2.BitwiseOr(newImage, img, newImage); Cv2.BitwiseNot(image, image); int width = 400; var height = width * image.Height / image.Width; Cv2.Resize(orig, orig, new Size(width, height)); Cv2.Resize(image, image, new Size(width, height)); Cv2.Resize(newImage, newImage, new Size(width, height)); using (new Window("orig", orig)) using (new Window("pre", image)) using (new Window("post", newImage)) { Cv2.WaitKey(); Cv2.DestroyAllWindows(); } } // Dispose. orig.Dispose(); image.Dispose(); newImage.Dispose(); mat.Dispose(); return(result); }
public void Locate(Mat mat, MyFlags localiseFlags) { if (mat == null || mat.Empty()) { return; } if (localiseFlags == null) { return; } using (Mat hsv = new Mat()) using (Mat ball = new Mat()) using (Mat car1 = new Mat()) using (Mat car2 = new Mat()) //using (Mat merged = new Mat()) using (Mat black = new Mat(mat.Size(), MatType.CV_8UC1)) { Cv2.CvtColor(mat, hsv, ColorConversionCodes.RGB2HSV); MyFlags.LocConfigs configs = localiseFlags.configs; Cv2.InRange(hsv, new Scalar(configs.hue0Lower, configs.saturation0Lower, configs.valueLower), new Scalar(configs.hue0Upper, 255, 255), ball); Cv2.InRange(hsv, new Scalar(configs.hue1Lower, configs.saturation1Lower, configs.valueLower), new Scalar(configs.hue1Upper, 255, 255), car1); Cv2.InRange(hsv, new Scalar(configs.hue2Lower, configs.saturation2Lower, configs.valueLower), new Scalar(configs.hue2Upper, 255, 255), car2); if (localiseFlags.showMask) { Cv2.ImShow("Ball", ball); Cv2.ImShow("CarA", car1); Cv2.ImShow("CarB", car2); } else { Cv2.DestroyAllWindows(); } Point2i[][] contours0, contours1, contours2; contours0 = Cv2.FindContoursAsArray(ball, RetrievalModes.External, ContourApproximationModes.ApproxSimple); contours1 = Cv2.FindContoursAsArray(car1, RetrievalModes.External, ContourApproximationModes.ApproxSimple); contours2 = Cv2.FindContoursAsArray(car2, RetrievalModes.External, ContourApproximationModes.ApproxSimple); foreach (Point2i[] c0 in contours0) { Point2i centre = new Point2i(); Moments moments = Cv2.Moments(c0); centre.X = (int)(moments.M10 / moments.M00); centre.Y = (int)(moments.M01 / moments.M00); double area = moments.M00; if (area <= configs.areaLower / 4) { continue; } centres0.Add(centre); } foreach (Point2i[] c1 in contours1) { Point2i centre = new Point2i(); Moments moments = Cv2.Moments(c1); centre.X = (int)(moments.M10 / moments.M00); centre.Y = (int)(moments.M01 / moments.M00); double area = moments.M00; if (area <= configs.areaLower) { continue; } centres1.Add(centre); } foreach (Point2i[] c2 in contours2) { Point2i centre = new Point2f(); Moments moments = Cv2.Moments(c2); centre.X = (int)(moments.M10 / moments.M00); centre.Y = (int)(moments.M01 / moments.M00); double area = moments.M00; if (area <= configs.areaLower) { continue; } centres2.Add(centre); } foreach (Point2i c0 in centres0) { Cv2.Circle(mat, c0, 1, new Scalar(0x1b, 0xa7, 0xff), -1); } foreach (Point2i c1 in centres1) { Cv2.Circle(mat, c1, 10, new Scalar(0x1b, 0xff, 0xa7), -1); } foreach (Point2i c2 in centres2) { Cv2.Circle(mat, c2, 10, new Scalar(0x00, 0x98, 0xff), -1); } if (localiseFlags.gameState != GameState.Unstart) { for (int i = 0; i < localiseFlags.currPersonNum; ++i) { int x10 = localiseFlags.posPersonStart[i].X - 8; int y10 = localiseFlags.posPersonStart[i].Y - 8; Cv2.Rectangle(mat, new Rect(x10, y10, 16, 16), new Scalar(0xf3, 0x96, 0x21), -1); } } //Cv2.Merge(new Mat[] { car1, car2, black }, merged); //Cv2.ImShow("binary", merged); } }
private void Form1_Load(object sender, EventArgs e) { var model = "opencv_face_detector_uint8.pb"; //tensorflow 학습된 모델 파일 var config = "opencv_face_detector.pbtxt"; // 구성 파일 var confidence = 0.0; var x1 = 0.0; var x2 = 0.0; var y1 = 0.0; var y2 = 0.0; int cnt = 0; video = new VideoCapture(1); //video 1번(ManyCam) 사용 if (!video.IsOpened()) //video 초기화 안될 시 error { Console.WriteLine("error"); return; } Net net = CvDnn.ReadNet(model, config); if (net.Empty()) { Console.WriteLine("error"); return; } frame = new Mat(); while (true) { video.Read(frame); if (frame.Empty()) { break; } //frame blob 입력 설정된 부분을 net Mat blob = CvDnn.BlobFromImage(frame, 1.0, new OpenCvSharp.Size(300, 300), new Scalar(104, 177, 123)); net.SetInput(blob); Mat res = net.Forward(); var detect = res.Reshape(1, res.Cols * res.Rows); for (int i = 0; i < detect.Rows; i++) //Face recongition { confidence = detect.At <float>(i, 2); if (confidence < 0.5) { break; //Face recongition 0.5 이하는 무시 } //get center and width/height x1 = Math.Round(detect.At <float>(i, 3) * frame.Cols); //좌표 계산 y1 = Math.Round(detect.At <float>(i, 4) * frame.Rows); x2 = Math.Round(detect.At <float>(i, 5) * frame.Cols); y2 = Math.Round(detect.At <float>(i, 6) * frame.Rows); string Label = string.Format("Face:" + confidence); // 1. Face recongition을 시각화하는 작업 //2. confidence > 0.955 greenbox 생성 if (confidence > 0.955) { Cv2.Rectangle(frame, new OpenCvSharp.Point(x1, y1), new OpenCvSharp.Point(x2, y2), new Scalar(0, 255, 0)); Cv2.PutText(frame, Label, new OpenCvSharp.Point(x1, y1 - 1), OpenCvSharp.HersheyFonts.Italic, 0.8, new Scalar(0, 255, 0)); } //2. 아닐 시 redbox 생성 else { Cv2.Rectangle(frame, new OpenCvSharp.Point(x1, y1), new OpenCvSharp.Point(x2, y2), new Scalar(0, 0, 255)); Cv2.PutText(frame, Label, new OpenCvSharp.Point(x1, y1 - 1), OpenCvSharp.HersheyFonts.Italic, 0.8, new Scalar(0, 0, 255)); } } Cv2.ImShow("FACE ID", frame); if (confidence > 0.997910) { cnt++; if (cnt >= 30) //30번 인식시 파일 save { _saveName = "C:/images/" + DateTime.Now.ToString("yyyy/MM/dd_hh_mm_ss") + ".jpeg"; Cv2.ImWrite(_saveName, frame); video.Release(); Cv2.DestroyAllWindows(); break; } } if (Cv2.WaitKey(1) == 27) //아스키코드 27 : esc { break; } } Delay(100); inCvImage = Cv2.ImRead(_saveName); //2번 Cv2.Transpose(inCvImage, inCvImage); outCvImage = new Mat(); Cv2.CvtColor(inCvImage, outCvImage, ColorConversionCodes.BGR2GRAY); Cv2.EqualizeHist(outCvImage, outCvImage); Cv2ToOutImage(); //사각박스 내부만 나오게 설정 for (int rgb = 0; rgb < 3; rgb++) { for (int i = 0; i < _outH; i++) { for (int k = 0; k < _outW; k++) { if ((x1 <= i && i <= x2) && (y1 <= k && k <= y2)) { _outImage[rgb, i, k] = (byte)(255 - _outImage[rgb, i, k]); } else { _outImage[rgb, i, k] = 0; } } } } DisplayImage(); connStr = "Server=127.0.0.1; Uid=root; Pwd=1234;Database=HYDB;CHARSET=UTF8"; conn = new MySqlConnection(connStr); //db로 전달 dbUpload(); CCTV ma = new CCTV(); ma.ShowDialog(); Close(); } //1. 얼굴인식 후 저장 및 blob 업로드
//1ms FL = 40 binary threshold public bool Test() { var rootDir = @"P:\Projects\N3 Imaging\Images\06272018_16natural_4_syn_binning\SWUV lamp phos"; var files = Directory.GetFiles(rootDir, "*.bmp", SearchOption.TopDirectoryOnly); Mat combinedMask = null; Mat whiteLight = Cv2.ImRead(@"P:\Projects\N3 Imaging\Images\06272018_16natural_4_syn_binning\whitelight.bmp"); foreach (var file in files) { var fl = Cv2.ImRead(file); Mat mask; var res = PlMask(fl, 20, out mask); if (combinedMask == null) { combinedMask = Mat.Zeros(mask.Size(), mask.Type()); } Cv2.Add(mask, combinedMask, combinedMask); } Mat element = Cv2.GetStructuringElement(MorphShapes.Ellipse, new OpenCvSharp.Size(9, 9), new OpenCvSharp.Point(2, 2)); Cv2.Dilate(combinedMask, combinedMask, element); //find contours on this mask Mat[] contours; var hierarchy = new List <Point>(); Cv2.FindContours(combinedMask, out contours, OutputArray.Create(hierarchy), RetrievalModes.External, ContourApproximationModes.ApproxSimple); //remove small size contours List <Mat> bigContours = new List <Mat>(); foreach (var contour in contours) { if (Cv2.ContourArea(contour) > 400) { bigContours.Add(contour); } } combinedMask = Mat.Zeros(combinedMask.Size(), MatType.CV_8UC1); Cv2.DrawContours(combinedMask, bigContours, -1, Scalar.White); //get centers of contours for (int i = 0; i < bigContours.Count; i++) { var c = bigContours[i]; var m = c.Moments(true); var x = m.M10 / m.M00; var y = m.M01 / m.M00; Cv2.DrawContours(whiteLight, bigContours, i, new Scalar(255, 0, 0), 4); Cv2.PutText(whiteLight, "F", new Point(x, y), HersheyFonts.HersheySimplex, 1, new Scalar(0, 0, 255), 4); } Cv2.ImShow("mask", combinedMask); Cv2.ImShow("whiteLight", whiteLight); Cv2.WaitKey(); Cv2.DestroyAllWindows(); return(true); }