private void OnDrawGizmosSelected() { if (meshFilter == null) { return; } Mesh mesh = meshFilter.sharedMesh; Transform transform = meshFilter.transform; //Gizmos.color = Color.white; //Gizmos.DrawWireCube(transform.TransformPoint(tileBounds.center), tileBounds.size); var edge = EdgeDetector.FindMeshEdge(axis, tileBounds, mesh); Gizmos.color = Color.yellow; for (int i = 0; i < edge.EdgesCount; i++) { Vector3[] edgeVertices = edge.GetEdgeVertices(i); Vector3 worldV0 = transform.TransformPoint(edgeVertices[0]); Vector3 worldV1 = transform.TransformPoint(edgeVertices[1]); Gizmos.DrawLine(worldV0, worldV1); Gizmos.DrawSphere(worldV0, 0.01f); Gizmos.DrawSphere(worldV1, 0.01f); } }
public void testEdgeDetection() { String testPath = "testEdge/"; String[] pictures = Directory.GetFiles(testPath); EdgeDetector eD = new EdgeDetector(testPath); eD.execute(); String directory = "Edged/"; String[] edgedPictures = Directory.GetFiles(directory); Assert.AreEqual(edgedPictures.Length, pictures.Length, "Some images were not preccessed in Edge Detection"); int edgedCount = 0; for (int i = 0; i < edgedPictures.Length; i++) { bool isBlackOrWhite = true; Bitmap finalImages = new Bitmap(edgedPictures[i]); for (int j = 0; j < finalImages.Width; j++) { for (int k = 0; k < finalImages.Height; k++) { if(finalImages.GetPixel(j,k).R > 0 && finalImages.GetPixel(j,k).R < 255) { isBlackOrWhite = false; break; } } if(!isBlackOrWhite) break; } if (isBlackOrWhite) edgedCount++; Assert.AreEqual(true, isBlackOrWhite, "Image is not an edged image"); } Assert.AreEqual(edgedPictures.Length, edgedCount, "Not all images were Edged"); }
private void DirectionToFile_Click(object sender, RoutedEventArgs e) { if (_currentImage == null) { return; } Stopwatch performanceCounter = new Stopwatch(); performanceCounter.Start(); CanvasARGB canvas = Get_ProgressOrOrigInput(); CanvasPixel canvasPixel = CanvasPixel.CreateBitmpaFromCanvas(canvas); CanvasEdgeVO canvasEdges = CanvasEdgeVO.CreateEdgesFromCanvas(canvasPixel); EdgeDetector.EdgeReducer(canvasEdges, 255); EdgesWriteToFile(canvasEdges, "directions3.txt"); CanvasPixel evisualise = VisualiseDetectedEdges(canvasEdges); _lastImage = CanvasPixel.CreateBitmpaFromCanvas(evisualise); performanceCounter.Stop(); Helper_SetAppTitle(string.Format("{0,000} s ", performanceCounter.Elapsed.TotalSeconds)); ShowImage(false); }
public void EdgeTrackingTest() { var drive = new Drive(Path.Combine(Dir.CarusoTestDirectory, Dir.EdgeTrackingDirectory), Drive.Reason.Read); var image = new Bitmap(drive.Files("simple").First()); var left = EdgeDetector.EdgePoints(image, Direction.FromLeft); Assert.IsTrue(left[0] == -1); Assert.IsTrue(left[75] == 46); Assert.IsTrue(left[363] == 46); Assert.IsTrue(left[364] == 6); Assert.IsTrue(left[405] == 6); Assert.IsTrue(left[406] == 46); Assert.IsTrue(left[424] == 46); Assert.IsTrue(left[425] == -1); Assert.IsTrue(left[499] == -1); var right = EdgeDetector.EdgePoints(image, Direction.FromRight); Assert.IsTrue(right[0] == -1); Assert.IsTrue(right[75] == 154); Assert.IsTrue(right[218] == 154); Assert.IsTrue(right[219] == 188); Assert.IsTrue(right[294] == 188); Assert.IsTrue(right[295] == 154); Assert.IsTrue(right[424] == 154); Assert.IsTrue(right[425] == -1); Assert.IsTrue(right[499] == -1); }
public GroundedPounceState(IPlayerEntity playerController, IStateMachine stateMachine) : base(playerController, stateMachine) { playerController.FeetHitbox.enabled = false; _hitbox = playerController.FeetHitbox; jumpDirection = new Vector2(horizontalForce, verticalForce); jumpForce = playerController.PlayerControllerSettings.JumpVelocity; edgeDetector = new EdgeDetector(base.IsGrounded); }
public void UpdateMeshEdges() { edges = new MeshEdge[6]; edges[0] = EdgeDetector.FindMeshEdge(Vector3.up, bounds, mainMesh.sharedMesh); edges[1] = EdgeDetector.FindMeshEdge(Vector3.down, bounds, mainMesh.sharedMesh); edges[2] = EdgeDetector.FindMeshEdge(Vector3.right, bounds, mainMesh.sharedMesh); edges[3] = EdgeDetector.FindMeshEdge(Vector3.left, bounds, mainMesh.sharedMesh); edges[4] = EdgeDetector.FindMeshEdge(Vector3.forward, bounds, mainMesh.sharedMesh); edges[5] = EdgeDetector.FindMeshEdge(Vector3.back, bounds, mainMesh.sharedMesh); }
private void Slide(bool _sliding, bool ceiling, float _move) { //Vector2 _targetVelocity; if (!_sliding && grounded) { if (ceiling) { _sliding = true; } } if (_sliding) { if (idleCollider != null && slidingCollider != null && grounded && !EdgeDetector.GetEdge()) { idleCollider.enabled = false; slidingCollider.enabled = true; } else { idleCollider.enabled = true; slidingCollider.enabled = false; } if (GameMaster.GetCurrentStamina() > 0 && Mathf.Abs(_move) > 0) { if (grounded) { targetVelocity.x = _move * slideSpeed; GameMaster.UpdateStamina(-1f); } } else { targetVelocity.x = _move * maxSpeed; } } else if (!_sliding) { if (idleCollider != null && slidingCollider != null) { idleCollider.enabled = true; slidingCollider.enabled = false; } targetVelocity.x = _move * maxSpeed; } }
private void PrintEdgesHash() { Mesh mesh = meshFilter.sharedMesh; var edgeXp = EdgeDetector.FindMeshEdge(Vector3.right, tileBounds, mesh); var edgeXn = EdgeDetector.FindMeshEdge(Vector3.left, tileBounds, mesh); var edgeYp = EdgeDetector.FindMeshEdge(Vector3.up, tileBounds, mesh); var edgeYn = EdgeDetector.FindMeshEdge(Vector3.down, tileBounds, mesh); var edgeZp = EdgeDetector.FindMeshEdge(Vector3.forward, tileBounds, mesh); var edgeZn = EdgeDetector.FindMeshEdge(Vector3.back, tileBounds, mesh); Debug.Log("X+ " + edgeXp.GetHashCode() + " | X- " + edgeXn.GetHashCode()); Debug.Log("Y+ " + edgeYp.GetHashCode() + " | Y- " + edgeYn.GetHashCode()); Debug.Log("Z+ " + edgeZp.GetHashCode() + " | Z- " + edgeZn.GetHashCode()); }
protected override void DetectEdge() { base.DetectEdge(); bool walkingCollider = false; bool slideCollider = false; if (EdgeDetector.GetEdge()) { walkingCollider = idleCollider.enabled; slideCollider = slidingCollider.enabled; slidingCollider.enabled = false; idleCollider.enabled = true; } else if (EdgeDetector.GetOnEdge() && !EdgeDetector.GetEdge()) { slidingCollider.enabled = slideCollider; idleCollider.enabled = walkingCollider; EdgeDetector.SetOnEdge(false); } }
public void SmootheningTest() { int[] testarray = Enumerable.Range(1, 1000).ToArray(); const int nsize = 100; int[] firstExpected = new int[nsize]; int[] secondExpected = new int[testarray.Length - nsize]; for (int ii = 1; ii <= nsize; ii++) { double summation = ((ii) * (ii + 1) / 2.0); firstExpected[ii - 1] = (int)(summation / (double)ii); } for (int ii = nsize + 1; ii < testarray.Length; ii++) { double summation = ((ii) * (ii + 1) / 2.0) - ((ii - nsize) * (ii - nsize + 1) / 2.0); secondExpected[ii - nsize - 1] = (int)(summation / (double)nsize); } var expected = (firstExpected.Concat(secondExpected)).Take(500); var actual = EdgeDetector.Smoothen(testarray, nsize).Take(500); Assert.IsTrue(expected.Zip(actual, (first, second) => first == second).All(x => x)); }
public Bitmap Draw() { var _bitmap = bitmap.Clone() as Bitmap; return(EdgeDetector.ToTopHap(_bitmap)); }
public Bitmap Draw() { var _bitmap = bitmap.Clone() as Bitmap; return(EdgeDetector.ToBoundary(_bitmap)); }
public Bitmap Draw() { var _bitmap = bitmap.Clone() as Bitmap; return(EdgeDetector.Smoothed(_bitmap)); }
/// <summary> /// Handles a new CPU image. /// </summary> /// <param name="width">Width of the image, in pixels.</param> /// <param name="height">Height of the image, in pixels.</param> /// <param name="rowStride">Row stride of the image, in pixels.</param> /// <param name="pixelBuffer">Pointer to raw image buffer.</param> /// <param name="bufferSize">The size of the image buffer, in bytes.</param> private byte[] onImageAvailable( int width, int height, int rowStride, IntPtr pixelBuffer, int bufferSize) { if (edgeDetectionBackgroundTexture == null || edgeDetectionResultImage == null || edgeDetectionBackgroundTexture.width != width || edgeDetectionBackgroundTexture.height != height) { edgeDetectionBackgroundTexture = new Texture2D(width, height, TextureFormat.R8, false, false); edgeDetectionResultImage = new byte[width * height]; cameraImageToDisplayUvTransformation = Frame.CameraImage.ImageDisplayUvs; } // CACHING - TODO //if (m_CachedOrientation != Screen.orientation || // m_CachedScreenDimensions.x != Screen.width || // m_CachedScreenDimensions.y != Screen.height) //{ // m_CameraImageToDisplayUvTransformation = Frame.CameraImage.ImageDisplayUvs; // m_CachedOrientation = Screen.orientation; // m_CachedScreenDimensions = new Vector2(Screen.width, Screen.height); //} // Detect edges within the image. if (EdgeDetector.Detect( edgeDetectionResultImage, pixelBuffer, width, height, rowStride)) { Debug.Log("Egdes detected"); // Look for circles if (edgeDetectionResultImage != null) { //Debug.Log("Image size: " + width + " " + height); var result = cvController.detectCircles(edgeDetectionResultImage, width, height, 320, 240, 15, 20, 40); if (result.Count > 0) { Debug.Log("Drawing circles"); foreach (var circle in result) { int[,] points; bool pointsAvailable = cvController.circlePoints.TryGetValue(circle.Item1, out points); if (pointsAvailable) { for (int j = 0; j < points.Length / 2; j++) { int ycoord = circle.Item3 + points[j, 1]; int xcoord = circle.Item2 + points[j, 0]; if (xcoord >= 0 && xcoord < width && ycoord >= 0 && ycoord < height) { edgeDetectionResultImage[ycoord * width + xcoord] = 0x96; } } } } } } // Update the rendering texture with the edge image. edgeDetectionBackgroundTexture.LoadRawTextureData(edgeDetectionResultImage); edgeDetectionBackgroundTexture.Apply(); EdgeDetectionBackgroundImage.material.SetTexture( "_ImageTex", edgeDetectionBackgroundTexture); const string TOP_LEFT_RIGHT = "_UvTopLeftRight"; const string BOTTOM_LEFT_RIGHT = "_UvBottomLeftRight"; EdgeDetectionBackgroundImage.material.SetVector(TOP_LEFT_RIGHT, new Vector4( cameraImageToDisplayUvTransformation.TopLeft.x, cameraImageToDisplayUvTransformation.TopLeft.y, cameraImageToDisplayUvTransformation.TopRight.x, cameraImageToDisplayUvTransformation.TopRight.y)); EdgeDetectionBackgroundImage.material.SetVector(BOTTOM_LEFT_RIGHT, new Vector4( cameraImageToDisplayUvTransformation.BottomLeft.x, cameraImageToDisplayUvTransformation.BottomLeft.y, cameraImageToDisplayUvTransformation.BottomRight.x, cameraImageToDisplayUvTransformation.BottomRight.y)); return(edgeDetectionResultImage); } return(null); }
static void Main(string[] args) { //Thread capturaVideoThread = new Thread(new ThreadStart(Program.CapturarVideo)); //capturaVideoThread.Start(); VideoCapture captura = new VideoCapture("D:\\Dictuc\\out1.avi"); VideoWriter salida = new VideoWriter("D:\\Dictuc\\outSegmentado.avi", FourCC.XVID, 10.0, new Size(captura.FrameWidth, captura.FrameHeight), true); Mat imagenProcesada = new Mat(); int numImg = 0; while (true) { //captura.Read(imagen); imagen = Cv2.ImRead("D:\\uvas2.jpg"); mutex.WaitOne(); imagen.CopyTo(imagenProcesada); mutex.ReleaseMutex(); Mat imagenRuidoFiltrado = FiltradoRuido(imagenProcesada); Mat imagenGrisContraste = EscalaGrisesEqualizada(imagenRuidoFiltrado); Mat imagenGrisFrecAltasProc = FrecuenciasAltasPotenciadasContraste(imagenGrisContraste); EdgeDetector edgeDetector = new EdgeDetector() { Threshold = (byte)18, SparseDistance = 3, WeightPreviousPoint = (float)2.0, WeightCurrentPoint = (float)1.0, WeightAfterPoint = (float)2.0, }; EdgeDetector edgeDetector2 = new EdgeDetector() { Threshold = (byte)20, SparseDistance = 5, WeightPreviousPoint = (float)0.5, WeightCurrentPoint = (float)1.0, WeightAfterPoint = (float)0.5, }; Mat imagenBordes = edgeDetector.EdgeImage(imagenGrisContraste); Mat imagenBordes2 = edgeDetector2.EdgeImage(imagenGrisContraste); Mat imagenBinaria, imagenAberturaRelleno; CalculoMatrizBinariaYRelleno(imagenBordes2, out imagenBinaria, out imagenAberturaRelleno); Mat mascaraInv = 255 - imagenAberturaRelleno; Mat DistSureFg = new Mat(); Mat AreasSureFg = new Mat(); Mat Unknown = new Mat(); AreasSureFg += 1; Cv2.DistanceTransform(imagenAberturaRelleno, DistSureFg, DistanceTypes.L1, DistanceMaskSize.Mask5); int numAreas = Cv2.ConnectedComponents(imagenAberturaRelleno, AreasSureFg, PixelConnectivity.Connectivity8); float[,] distValues = new float[DistSureFg.Rows, DistSureFg.Cols]; for (int i = 0; i < DistSureFg.Rows; i++) { for (int j = 0; j < DistSureFg.Cols; j++) { distValues[i, j] = DistSureFg.At <float>(i, j); } } Segment[] segments = new Segment[numAreas]; for (int i = 0; i < AreasSureFg.Rows; i++) { for (int j = 0; j < AreasSureFg.Cols; j++) { int m = AreasSureFg.At <Int32>(i, j); byte pixelSurrounding = 0; float distance = (float)0; //if (i >= 1) //{ // distance = distValues[i - 1, j]; // if (distance == 2) // { // pixelSurrounding |= Segment.PIXEL_SURROUNDED_LEFT; // } //} //if (i < AreasSureFg.Rows - 1) //{ // distance = distValues[i + 1, j]; // if (distance == 2) // { // pixelSurrounding |= Segment.PIXEL_SURROUNDED_RIGHT; // } //} //if (j >= 1) //{ // distance = distValues[i, j - 1]; // if (distance == 2) // { // pixelSurrounding |= Segment.PIXEL_SURROUNDED_DOWN; // } //} //if (j < AreasSureFg.Cols - 1) //{ // distance = distValues[i, j + 1]; // if (distance == 2) // { // pixelSurrounding |= Segment.PIXEL_SURROUNDED_UP; // } //} SegmentPixelData newPixel = new SegmentPixelData() { Distance = distValues[i, j], CoordsXY = new int[] { i, j }, Concave = 0, Indexes = new int[] { -1, -1 }, PixelsSurrounding = pixelSurrounding, SubsegmentLabel = 0, }; if (segments[m] == null) { segments[m] = new Segment() { SegmentId = m, PixelData = new List <SegmentPixelData>(), }; } else { segments[m].MaxDistance = (segments[m].MaxDistance > newPixel.Distance) ? (int)segments[m].MaxDistance : (int)newPixel.Distance; segments[m].PixelData.Add(newPixel); } } } Mat Centroides = new Mat(); imagenAberturaRelleno.CopyTo(Centroides); var indexadorCentroides = Centroides.GetGenericIndexer <byte>(); var indexadorFiguras = AreasSureFg.GetGenericIndexer <Int32>(); foreach (var s in segments.Where(s => s.Circularity <= 0.9)) { int distancia = 0; if (s.Circularity > 0.7) { distancia = 5; } else if (s.Circularity > 0.5) { distancia = 5; } else if (s.Circularity > 0.25) { distancia = 6; } else { distancia = 6; } distancia = (distancia < s.MaxDistance) ? distancia : s.MaxDistance - 1; foreach (var p in s.PixelData.Where(p => p.Distance <= distancia)) { if (imagenAberturaRelleno.At <byte>(p.CoordsXY[0], p.CoordsXY[1]) != (byte)0) { indexadorCentroides[p.CoordsXY[0], p.CoordsXY[1]] = 0; } } } Cv2.Subtract(imagenAberturaRelleno + 255, Centroides, Unknown); #region segmentStuff //List<int> indexConcavos = segments.Where(s => s.Circularity > 1).Select(s => s.SegmentId).ToList(); //foreach (var s in segments.Where(s => s.Circularity < 1.1 && s.Circularity > 0.9)) //{ // foreach (var p in s.PixelData/*.Where(p => p.Distance == 1)*/) // { // if (imagenAberturaRelleno.At<byte>(p.CoordsXY[0], p.CoordsXY[1]) != (byte)0) // { // indexadorFiguras[p.CoordsXY[0], p.CoordsXY[1]] = 255; // } // } //} //foreach (var s in segments.Where(s => s.Circularity >= 1.1)) //{ // foreach (var p in s.PixelData/*.Where(p => p.Distance == 1)*/) // { // if (imagenAberturaRelleno.At<byte>(p.CoordsXY[0], p.CoordsXY[1]) != (byte)0) // { // indexadorFiguras[p.CoordsXY[0], p.CoordsXY[1]] = 255; // } // } //} //foreach (var s in segments) //{ // s.SetPixelConcavity(); // s.Segmentation(); // foreach (var p in s.PixelData.Where(p => p.Distance == 1)) // { // if (p.Concave == 1) // { // indexadorFiguras[p.CoordsXY[0], p.CoordsXY[1]] = 255; // } // if (p.Concave == -1) // { // indexadorFiguras[p.CoordsXY[0], p.CoordsXY[1]] = 255; // } // } //} //foreach (var s in segments) //{ // //s.SetPixelConcavity(); // //s.Segmentation(); // foreach (var p in s.PixelData.Where(p => p.Distance == 2)) // { // indexadorFiguras[p.CoordsXY[0], p.CoordsXY[1]] = 230; // } //} //imagenAberturaRelleno.CopyTo(SureFg); #endregion Mat colormap = new Mat(); Mat Marcadores = new Mat(); Cv2.ConnectedComponents(Centroides, Marcadores); Marcadores = Marcadores + 1; var indexador2 = Marcadores.GetGenericIndexer <Int32>(); for (int i = 0; i < Unknown.Rows; i++) { for (int j = 0; j < Unknown.Cols; j++) { if (Unknown.At <byte>(i, j) == 255) { indexador2[i, j] = 0; } } } Marcadores.CopyTo(colormap); colormap.ConvertTo(colormap, MatType.CV_8UC3); Cv2.ApplyColorMap(colormap, colormap, ColormapTypes.Rainbow); Cv2.ImWrite("D:\\Dictuc\\marcadores.png", Marcadores); //Mat img1 = new Mat(); //imagen.CopyTo(img1); Mat DistColor = new Mat(); //imagenGrisContraste = 255 - imagenGrisContraste; Cv2.CvtColor(imagenAberturaRelleno, DistColor, ColorConversionCodes.GRAY2BGR); DistColor.ConvertTo(DistColor, MatType.CV_8U); Cv2.Watershed(DistColor, Marcadores); Cv2.ImWrite("D:\\Dictuc\\watersheedIn.png", DistColor); var indexador4 = imagen.GetGenericIndexer <Vec3i>(); //for (int i = 0; i < imagen.Rows; i++) //{ // for (int j = 0; j < imagen.Cols; j++) // { // //if (Centroides.At<byte>(i, j) > 0) // // indexador4[i, j] = new Vec3i(0, 0, 255); // if (Marcadores.At<Int32>(i, j) == -1) // indexador4[i, j] = new Vec3i(255, 20, 20); // } //} for (int i = 0; i < imagen.Rows; i++) { for (int j = 0; j < imagen.Cols; j++) { //if (Centroides.At<byte>(i, j) > 0) // indexador4[i, j] = new Vec3i(0, 0, 255); if (imagenBordes.At <char>(i, j) > 0) { indexador4[i, j] = new Vec3i(255, 20, 20); } } } Mat seg = new Mat(); Marcadores.CopyTo(seg); var indexador5 = seg.GetGenericIndexer <int>(); for (int i = 0; i < Marcadores.Rows; i++) { for (int j = 0; j < Marcadores.Cols; j++) { indexador5[i, j] = (Math.Abs(indexador5[i, j]) > 1) ? 255 : 0; } } Mat kE1 = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(1, 1)); Cv2.Erode(seg, seg, kE1, iterations: 3); int thrs1 = 1500; int thrs2 = 1800; Mat edge1 = new Mat(); seg.ConvertTo(seg, MatType.CV_8U); Cv2.Canny(seg, edge1, thrs1, thrs2, apertureSize: 5); SimpleBlobDetector.Params params1 = new SimpleBlobDetector.Params() { MinThreshold = 0, MaxThreshold = 255, FilterByArea = true, MinArea = 15, FilterByCircularity = false, MinCircularity = (float)0.01, FilterByConvexity = false, MinConvexity = (float)0.1, FilterByInertia = false, MinInertiaRatio = (float)0.01, }; SimpleBlobDetector detectorBlobs = SimpleBlobDetector.Create(params1); KeyPoint[] segmentosBlob = detectorBlobs.Detect(edge1); Mat segmentosBlobMat = new Mat(1, segmentosBlob.Count(), MatType.CV_32FC1); var indexador6 = segmentosBlobMat.GetGenericIndexer <float>(); for (int i = 0; i < segmentosBlob.Count(); i++) { indexador6[0, i] = segmentosBlob[i].Size; } Mat hist = new Mat(); Rangef[] ranges = { new Rangef(0, (float)segmentosBlob.Max(x => x.Size)) }; Cv2.CalcHist(new Mat[] { segmentosBlobMat }, new int[] { 0 }, null, hist, 1, new int[] { 100 }, ranges, uniform: true, accumulate: true); float[] histAcumulado = new float[hist.Rows]; float[] histAcumuladoPorcentaje = new float[11]; histAcumulado[0] = hist.At <float>(0, 0); for (int i = 1; i < hist.Rows; i++) { histAcumulado[i] = hist.At <float>(i, 0) + histAcumulado[i - 1]; } int k = 1; for (int i = 1; i < histAcumuladoPorcentaje.Count(); i++) { for (; k < hist.Rows; k++) { float porcentajeActual = histAcumulado[k] / segmentosBlob.Count() * 100; float porcentajeAnterior = histAcumulado[k - 1] / segmentosBlob.Count() * 100; float porcentajeRequerido = (float)((i < 10) ? i * 10 : 99.3); if (porcentajeRequerido <= porcentajeActual) { float tamañoPorcentajeActual = (float)(k * (float)segmentosBlob.Max(x => x.Size) / 100.0); float tamañoPorcentajeAnterior = (float)((k - 1) * (float)segmentosBlob.Max(x => x.Size) / 100.0); float tasaVariacionTamañoPorcentaje = (tamañoPorcentajeActual - tamañoPorcentajeAnterior) / (porcentajeActual - porcentajeAnterior); histAcumuladoPorcentaje[i] = tamañoPorcentajeAnterior + tasaVariacionTamañoPorcentaje * (i * 10 - porcentajeAnterior); break; } } } for (int i = 0; i < histAcumuladoPorcentaje.Count(); i++) { Console.Write(histAcumuladoPorcentaje[i] + ","); } Console.WriteLine(""); // data1 = []; // for i in range(0, len(keypoints1)): // data1.append(keypoints1[i].size * coefTamano) // #tamano.write(str(i)+'\t'+str(keypoints1[i].size*2*0.3)+'\n') // cv2.line(im_with_keypoints1, (int(float(keypoints1[i].pt[0] - keypoints1[i].size)), int(float(keypoints1[i].pt[1]))), (int(float(keypoints1[i].pt[0] + keypoints1[i].size)), int(float(keypoints1[i].pt[1]))), (255, 0, 0), 1) // cv2.line(im_with_keypoints1, (int(float(keypoints1[i].pt[0])), int(float(keypoints1[i].pt[1] - keypoints1[i].size))), (int(float(keypoints1[i].pt[0])), int(float(keypoints1[i].pt[1] + keypoints1[i].size))), (255, 0, 0), 1) //# print(data1) //n1, bins1, patches1 = hist(data1, 200,[0, max(data1)], normed = 100, cumulative = True, bottom = True, histtype = 'stepfilled', align = 'mid', orientation = 'vertical', rwidth = 1, log = False, color = "r") // tamano = open(temp + "instancia_" + instancia + ".txt", "w") // x = np.array(bins1) // y = np.append([0], n1) // xnew = [x[1], x[21], x[36], x[45], x[53], x[60], x[69], x[78], x[88], x[97], x[200]] //ynew = [y[1], y[21], y[36], y[45], y[53], y[60], y[69], y[78], y[88], y[97], y[200]] //tamano.write('INSERT INTO [dbo].[Granulometria](Cod_Instancia,Fecha,P_10,P_20,P_30,P_40,P_50,P_60,P_70,P_80,P_90,P_100, Filename) values (') //tamano.write(instancia + ",CONVERT(datetime, '" + sys.argv[1][0:4] + "-" + sys.argv[1][4:6] + "-" + sys.argv[1][6:8] + ' ' + sys.argv[1][9:11] + ':' + sys.argv[1][11:13] + ':' + sys.argv[1][13:15] + "', 120)") //for j in range(1, len(xnew)): // #tamano.write (str(j)+'\t'+str(round(xnew[j],1))+'\t'+str(round(ynew[j]*100,2))+'\n') // tamano.write(',' + str(round(xnew[j], 1))) //tamano.write(",'" + sys.argv[1] + " - Resultado.jpg'") //tamano.write(')') //CvXImgProc.Thinning(mascaraInv, mascaraInv, ThinningTypes.ZHANGSUEN); Mat imWithKeypoints1 = new Mat(); Cv2.DrawKeypoints(imagen, segmentosBlob, imWithKeypoints1, new Scalar(0, 0, 255), DrawMatchesFlags.DrawRichKeypoints); var dataTamaños = segmentosBlob.Select(s => s.Size).ToArray(); Cv2.ImWrite("D:\\Dictuc\\output0" + numImg + ".png", imagen); Cv2.ImWrite("D:\\Dictuc\\output1" + numImg++ + ".png", imWithKeypoints1); Cv2.ImShow("Segmentado", imagen); Cv2.ImShow("GrisContraste", imagenGrisContraste); Cv2.ImShow("bordes90", imagenBordes); Cv2.ImShow("bordes50", imagenBordes2); salida.Write(imagen); //System.Threading.Thread.Sleep(10); Cv2.WaitKey(10); imagenRuidoFiltrado.Release(); imagenGrisContraste.Release(); imagenGrisFrecAltasProc.Release(); imagenBordes.Release(); imagenBinaria.Release(); imagenAberturaRelleno.Release(); } }
/// <summary> /// Create a shred object given a filepath to a bitmap image /// </summary> /// <param name="filepath"> destination path of the shred image </param> /// <param name="ignoreTopBottom"> Default is true, set to false to scan top and bottom aswell </param> public Shred(string filepath, bool ignoreTopBottom = true) { InitializeINode(); Filepath = filepath; Id = _count++; Logger.Trace("Starting Chamfer From Left"); int directions = ignoreTopBottom ? 4 : 8; Convolution = new List <double[]>(directions); Luminousity = new List <double[]>(directions); Chamfer = new List <int[]>(directions); Thresholded = new List <double[]>(directions); Sparsity = new List <long>(directions); Offsets = new List <int[]>(directions); using (Bitmap source = new Bitmap(filepath)) { var image = new Image <Bgra, Byte>(source); // Initialize List for Random Access for (int ii = 0; ii < directions; ii++) { Convolution.Add(new double[0]); Luminousity.Add(new double[0]); Thresholded.Add(new double[0]); Chamfer.Add(new int[0]); Sparsity.Add((long)-1.0); Offsets.Add(new int[0]); } foreach (int side in Enum.GetValues(typeof(Direction))) { // 2 per side if (side * 2 >= directions) { continue; } int regularIndex = Index((Direction)side, Orientation.Regular); int reverseIndex = regularIndex + 1; //Index((Direction) side, Orientation.Reversed); Logger.Trace("Measuring Side no:" + side); int[] offset = EdgeDetector.EdgePoints(source, (Direction)side); Offsets[regularIndex] = offset; Offsets[reverseIndex] = Utility.Reverse(offset); double[] luminousity = Forensics.Luminousity.RepresentativeLuminousity(image, BUFFER, SAMPLE_SIZE, (Direction)side); Luminousity[regularIndex] = luminousity; Luminousity[reverseIndex] = Utility.Reverse(luminousity); int[] indicies = Utility.GetKernelIndicies(ConvolutionKernel, -1); double[] convolutions = Utility.Convolute(Luminousity[regularIndex], ConvolutionKernel, indicies); Convolution[regularIndex] = convolutions; Convolution[reverseIndex] = Utility.Reverse(convolutions); double[] thresholded = Utility.Threshold(Utility.Absolute(Convolution[regularIndex]), THRESHOLD); Thresholded[regularIndex] = thresholded; Thresholded[reverseIndex] = Utility.Reverse(thresholded); int[] chamfer = Forensics.Chamfer.Measure(Thresholded[regularIndex]); Chamfer[regularIndex] = chamfer; Chamfer[reverseIndex] = Utility.Reverse(chamfer); long sparsity = Forensics.Chamfer.Sparsity(Chamfer[regularIndex]); Sparsity[regularIndex] = sparsity; Sparsity[reverseIndex] = sparsity; } } }