//HoughLineTransformation lineTransform = new HoughLineTransformation(); //// apply Hough line transofrm //lineTransform.ProcessImage(edge); //var fertig = UnmanagedImage(lineTransform, imageBm, edge); //Bitmap WithLines = fertig.ToManagedImage(); //uint j = 199; //TODO Wie hier an die 199 kommen??? // achtung, warum schwankt der count????????? // count . Nummer ist die ANZHAL!!!!!!!!!!! //for (uint i = (uint)bbb.Count() - 1; i > bbb.Count()-20; i--, j--) //{ //// locating objects //BlobCounter blobCounter = new BlobCounter(); //blobCounter.FilterBlobs = true; //blobCounter.MinHeight = 5; //blobCounter.MinWidth = 5; //blobCounter.ProcessImage(edge); //Blob[] blobs = blobCounter.GetObjectsInformation(); //// check for rectangles //SimpleShapeChecker shapeChecker = new SimpleShapeChecker(); //// create convex hull searching algorithm //GrahamConvexHull hullFinder = new GrahamConvexHull(); //// Bitmap tempBitmap = new Bitmap(imageBm.Width, imageBm.Height); //// lock image to draw on it //BitmapData data = imageBm.LockBits( // new Rectangle(0, 0, imageBm.Width, imageBm.Height), // ImageLockMode.ReadWrite, imageBm.PixelFormat); //List<IntPoint> edgePoints = new List<IntPoint>(); //List<System.Drawing.Point> Points = new List<Point>(); //foreach (var blob in blobs) //{ // List<IntPoint> leftPoints, rightPoints;//, edgePoints; // // get blob's edge points // blobCounter.GetBlobsLeftAndRightEdges(blob,//blobs[i] // out leftPoints, out rightPoints); // edgePoints.AddRange(leftPoints); // edgePoints.AddRange(rightPoints); // // blob's convex hull // List<IntPoint> hull = hullFinder.FindHull(edgePoints); // AForge.Imaging.Drawing.Polygon( data, hull, System.Drawing.Color.Red ); // // } // //} //} //imageBm.UnlockBits(data); ////Graphics g = Graphics.FromImage(/*imageSrc.myImg*/tempBitmap); ////g.DrawPolygon(new System.Drawing.Pen(System.Drawing.Color.Red, 5.0f), Points.ToArray()); //this.imageGray.Source = imageSrc.BitmapToImageSource(imageBm); ////imageSrc.myImg.Save("result.png"); //pen.Color = Color.Blue; //foreach (IntPoint corner in corners) //{ // graphics.DrawRectangle(pen, corner.X - 1, corner.Y - 1, 10, 10); //} //// use the shape checker to extract the corner points //if (shapeChecker.IsQuadrilateral(edgePoints, out cornerPoints)) //{ // // only do things if the corners form a rectangle // if (shapeChecker.CheckPolygonSubType(cornerPoints) == PolygonSubType.Rectangle) // { // here i use the graphics class to draw an overlay, but you // could also just use the cornerPoints list to calculate your //// x, y, width, height values. //Points = new List<System.Drawing.Point>(); //foreach (var point in edgePoints)//cornerPoints) //{ // Points.Add(new System.Drawing.Point(point.X, point.Y)); private static UnmanagedImage UnmanagedImage(HoughLineTransformation lineTransform, Bitmap imageBm, Bitmap edge) { // get lines using relative intensity HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(0.5); UnmanagedImage fertig = AForge.Imaging.UnmanagedImage.FromManagedImage(imageBm); Debug.WriteLine("Found lines: " + lines.Length); var count = 0; foreach (HoughLine line in lines) { // get line's radius and theta values int r = line.Radius; double t = line.Theta; // check if line is in lower part of the image if (r < 0) { t += 180; r = -r; } // convert degrees to radians t = (t / 180) * Math.PI; // get image centers (all coordinate are measured relative // to center) int w2 = edge.Width / 2; int h2 = edge.Height / 2; double x0 = 0, x1 = 0, y0 = 0, y1 = 0; if (line.Theta != 0) { // none-vertical line x0 = -w2; // most left point x1 = w2; // most right point // calculate corresponding y values y0 = (-Math.Cos(t) * x0 + r) / Math.Sin(t); y1 = (-Math.Cos(t) * x1 + r) / Math.Sin(t); } else { // vertical line x0 = line.Radius; x1 = line.Radius; y0 = h2; y1 = -h2; } if (line.Theta > 70 && line.Theta < 110) { if (line.RelativeIntensity > 0.7) { count++; AForge.Imaging.Drawing.Line(fertig, new IntPoint((int)x0 + w2, h2 - (int)y0), new IntPoint((int)x1 + w2, h2 - (int)y1), System.Drawing.Color.Red); } } } Debug.WriteLine("Found intensive: " + count); return(fertig); }
private void FindImageSlope() { string con = null; int count = 0; HoughLineTransformation hlinetransform = new HoughLineTransformation(); hlinetransform.ProcessImage(_medgeimg); Bitmap bmap = hlinetransform.ToBitmap(); HoughLine[] lines = hlinetransform.GetLinesByRelativeIntensity(0.5); double theta = 0; int length = 0; length = hlinetransform.LinesCount; foreach (HoughLine hline in lines) { int radius = hline.Radius; double th = hline.Theta; float intent = hline.Intensity; con = con + "Slope:" + th + ":" + intent + "\n"; theta += th; count++; } if (con != null) { Imgslope = con.ToString(); } Imgslope = (theta / count).ToString(); OnPropertyChanged("Imgslope"); }
private void FindImageSlope() { string con = null; _mintent = 0; int count = 0; HoughLineTransformation hlinetransform = new HoughLineTransformation(); hlinetransform.ProcessImage(_mgrayImg); Bitmap bmap = hlinetransform.ToBitmap(); HoughLine[] lines = hlinetransform.GetLinesByRelativeIntensity(1); foreach (HoughLine hline in lines) { int radius = hline.Radius; double th = hline.Theta; float intensities = hline.Intensity; con = con + "Slope:" + th + ":" + intensities + "\n"; _mintent += intensities; count++; } if (_mintent != 0) { AverageIntensityOfCImg = _mintent / count; } if (con != null) { OriginalImgslope = con.ToString(); } OnPropertyChanged("Imgslope"); }
public static double[,] DoHoughTransform(Bitmap sourceImage, int directionsCount, bool saveTransformImage) { int rowCount = sourceImage.Height; int colCount = sourceImage.Width; HoughLineTransformation lineTransform = new HoughLineTransformation(); //lineTransform.MinLineIntensity = (short)(colCount * 1.0); //min intensity in hough map to recognise a line //lineTransform.LocalPeakRadius = 4; //lineTransform.StepsPerDegree = 1; // this is default // apply Hough line transofrm lineTransform.ProcessImage(sourceImage); double maxIntensity = lineTransform.MaxIntensity; // max intensity in hough map if (saveTransformImage) { Bitmap houghLineImage = lineTransform.ToBitmap(); string path = @"C:\SensorNetworks\Output\Sonograms\hough.png"; houghLineImage.Save(path, ImageFormat.Png); } // get lines using relative intensity HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(1.0); //HoughLine[] lines = lineTransform.GetMostIntensiveLines(2); //this number of highest intensity lines Console.WriteLine("Number of lines returned from Hough transform = {0}", lines.Length); double angleResolution = 360 / (double)directionsCount; // transfer lines to r,t space //rows = radius; cols = angleCategory int maxRadius = rowCount / 2; double[,] rtSpace = new double[maxRadius + 1, directionsCount]; foreach (HoughLine line in lines) { // get line's radius and theta values int radius = line.Radius; double t = line.Theta; // check if line is in lower part of the image if (radius < 0) { t += 180; radius = -radius; } Console.WriteLine("Theta={1:f2} Radius={0}", radius, t); int angleCategory = (int)Math.Round(t / angleResolution); if (angleCategory >= directionsCount) { angleCategory = 0; } rtSpace[radius, angleCategory] += line.Intensity / (double)rowCount; } return(rtSpace); }
public Bitmap renderSunoPreview(TrajectorySet ts, int susanCornerPixelRadius, int houghLineWidth, Boolean susanRender, Boolean houghRender, Boolean blackRender, Boolean trajectoryPointsRender) { HoughLineTransformation lineTransform = ts.lineTransform; HoughLine[] lines = ts.lines; List <IntPoint> corners = ts.corners; Bitmap image = AForge.Imaging.Image.Clone(ts.image, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(image); if (susanRender) { foreach (IntPoint corner in corners) { g.FillEllipse(new SolidBrush(Color.Red), corner.X, corner.Y, susanCornerPixelRadius, susanCornerPixelRadius); } } if (blackRender) { foreach (System.Drawing.Point current_point in ts.black_points) { g.FillEllipse(new SolidBrush(Color.Yellow), current_point.X, current_point.Y, susanCornerPixelRadius, susanCornerPixelRadius); } } if (trajectoryPointsRender) { foreach (System.Drawing.Point current_point in ts.trajectory_points) { g.FillEllipse(new SolidBrush(Color.Coral), current_point.X, current_point.Y, susanCornerPixelRadius, susanCornerPixelRadius); } } BitmapData sourceData = image.LockBits( new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat); if (houghRender) { foreach (HoughLine line in lines) { drawHoughLine(line, image, sourceData, houghLineWidth); } } image.UnlockBits(sourceData); return(image); }
/// <summary> /// Called when videoPlayer receives a new frame. /// </summary> /// <param name="sender"></param> /// <param name="image"></param> private void videoPlayer_NewFrame(object sender, ref Bitmap image) { // convert image to grayscale var gray = new GrayscaleBT709(); var frame = gray.Apply(image); // threshold image to only keep light pixels var threshold = new Threshold(125); threshold.ApplyInPlace(frame); // blank out everything but the road var horizonY = (int)(image.Height * 0.65); var fill = new CanvasFill(new Rectangle(0, 0, image.Width, horizonY), Color.Red); fill.ApplyInPlace(frame); // detect edges var edgeDetector = new CannyEdgeDetector(); edgeDetector.ApplyInPlace(frame); // do a hough line transformation, which will search for straight lines in the frame var transform = new HoughLineTransformation(); transform.ProcessImage(frame); var rawLines = transform.GetMostIntensiveLines(50); // only keep non-horizontal lines that cross the horizon at the vanishing point var lines = from l in rawLines let range = new Range(-75, -65) where range.IsInside(l.Radius) && (l.Theta <= 85 || l.Theta >= 95) select l; // show the edge detection view in the bottom left box edgeBox.Image = frame; // show the lane detection view in the bottom right box var laneImg = new Bitmap(image.Width, image.Height); Utility.DrawHoughLines(lines, laneImg, Color.White, 1); laneBox.Image = laneImg; // draw the lanes on the main camera image too Utility.DrawHoughLines(lines, image, Color.LightGreen, 2); }
public static void Lines(Bitmap binarySource) { HoughLineTransformation lineTransform = new HoughLineTransformation(); //lineTransform. = 10; // apply Hough line transofrm lineTransform.ProcessImage(binarySource); HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(0.5); if (lines.Count() > 0) { //Result += "NW: Yes!\n"; } else { //Result += "NW: No!\n"; } }
private void houghTranformLine666(Bitmap sausBasic) { Bitmap saus = ConvertToFormat(sausBasic); HoughLineTransformation lineTransform = new HoughLineTransformation(); // apply Hough line transofrm lineTransform.ProcessImage(saus); Bitmap houghLineImage = lineTransform.ToBitmap(); // get lines using relative intensity HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(0.5); foreach (HoughLine line in lines) { Console.WriteLine(JsonConvert.SerializeObject(line, Formatting.Indented)); } pictureBox2.Image = houghLineImage; }
/// <summary> /// Detect the highway lane boundaries. /// </summary> /// <param name="image">The camera frame to process</param> /// <returns>The detected lane lines in the frame</returns> private HoughLine[] DetectLaneLines(Bitmap image) { // convert image to grayscale var frame = Grayscale.CommonAlgorithms.BT709.Apply(image); // threshold image to only keep light pixels var threshold = new Threshold(125); threshold.ApplyInPlace(frame); // blank out everything but the road var horizonY = (int)(image.Height * 0.65); var fill = new CanvasFill(new Rectangle(0, 0, image.Width, horizonY), Color.Red); fill.ApplyInPlace(frame); // detect edges var edgeDetector = new CannyEdgeDetector(); edgeDetector.ApplyInPlace(frame); // do a hough line transformation, which will search for straight lines in the frame var transform = new HoughLineTransformation(); transform.ProcessImage(frame); var rawLines = transform.GetMostIntensiveLines(50); // only keep non-horizontal lines that cross the horizon at the vanishing point var lines = from l in rawLines let range = new Range(-75, -65) where range.IsInside(l.Radius) && (l.Theta <= 85 || l.Theta >= 95) select l; // show the edge detection view in the bottom left box edgeBox.Image = (Bitmap)frame.Clone(); // return lines return(lines.ToArray()); }
public TrajectorySet CalculateTrajectorySet(Bitmap image, Double HoughRelativeIntensity, Int32 SusanCornerDifferenceTreshold, Int32 SusanCornerGeometricalTreshold, Int32 lineScanThreshold, Int32 lineScanRadius, Int32 radialThreshold, Boolean geometrical) { TrajectorySet ts = new TrajectorySet(); ts.elaboration_start_time = DateTime.Now; Bitmap hough_image = AForge.Imaging.Image.Clone(image, PixelFormat.Format24bppRgb); Bitmap susan_image = AForge.Imaging.Image.Clone(image, PixelFormat.Format24bppRgb); // AForge.Imaging.Image.FormatImage(ref hough_image); // AForge.Imaging.Image.FormatImage(ref susan_image); //FILTERS AND SOURCE INIT hough_image = Grayscale.CommonAlgorithms.RMY.Apply(hough_image); susan_image = Grayscale.CommonAlgorithms.RMY.Apply(susan_image); hough_image = ApplyFilter(hough_image, new Threshold()); susan_image = ApplyFilter(susan_image, new Threshold()); //INIT OBJECTS HoughLineTransformation lineTransform = new HoughLineTransformation(); SusanCornersDetector susanTransform = new SusanCornersDetector(SusanCornerDifferenceTreshold, SusanCornerGeometricalTreshold); FiltersSequence filter = new FiltersSequence( Grayscale.CommonAlgorithms.BT709, new Threshold(64) ); //APPLY ALGOS AND GET ENTITIES BitmapData houghSourceData = hough_image.LockBits( new Rectangle(0, 0, hough_image.Width, hough_image.Height), ImageLockMode.ReadOnly, hough_image.PixelFormat); lineTransform.ProcessImage(houghSourceData); hough_image.UnlockBits(houghSourceData); ts.elaborated_image = AForge.Imaging.Image.Clone(hough_image, PixelFormat.Format24bppRgb);; hough_image.Dispose(); HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(HoughRelativeIntensity); BitmapData sousanSourceData = susan_image.LockBits( new Rectangle(0, 0, susan_image.Width, susan_image.Height), ImageLockMode.ReadOnly, susan_image.PixelFormat); List <IntPoint> corners = susanTransform.ProcessImage(sousanSourceData); susan_image.UnlockBits(sousanSourceData); susan_image.Dispose(); //populat trajectoryset ts.image = image; ts.lineTransform = lineTransform; ts.lines = lines; ts.susanTransform = susanTransform; ts.corners = corners; //get discontinuity points this.CalculateDiscontinuityPoints(ts, lineScanThreshold, lineScanRadius, radialThreshold, geometrical); //get trajectory lines (W=3) //get trajectory lines (W=2) //get trajectory lines (W=1) //get quadrant foreach lines W=3, W=2, W=1 ts.elaboration_end_time = DateTime.Now; return(ts); }
public void findLines(object o) { DateTime tick = DateTime.Now; const int lineCount = 10; Bitmap bitmap = (Bitmap)o; HoughLine[] hls = new HoughLine[lineCount]; for (int i = 0; i < hls.Length; i++) hls[i] = null; for (int i = 0; i < heightRes.Length - 1; i++) { int y = heightRes[i]; int yDelta = heightRes[i + 1] - heightRes[i]; int xDelta = widthRes[i + 1] - widthRes[i]; for (int x = 0; x < bitmap.Width; x += xDelta) { Rectangle sub = new Rectangle(x, y, xDelta, yDelta); Bitmap subImg = (Bitmap)bitmap.Clone(sub, bitmap.PixelFormat); HoughLineTransformation hlt = new HoughLineTransformation(); hlt.ProcessImage(subImg); hls = hlt.GetMostIntensiveLines(lineCount); for (int j = 0; j < lineCount; j++) { if (hls.Length > j && hls[j] != null) { float xOffset = subImg.Width / 2f + x; float yOffset = subImg.Height / 2f + y; hls[j] = moveHL(hls[j], xOffset, yOffset, bitmap.Width / 2f, bitmap.Height); } } } } short[] bestThreeRadius = new short[] { 0, 0, 0 }; double[] bestThreeIntensity = new double[] { 0, 0, 0 }; double[] bestThreeTheta = new double[] { double.MinValue, double.MinValue, double.MinValue }; foreach (HoughLine hl in hls) { if (hl == null) continue; short rNew = (short)(hl.Radius); double tNew = hl.Theta; double sNew = hl.RelativeIntensity; bool isNew = true; for (int i = 0; i < 3; i++) { short r = bestThreeRadius[i]; double t = bestThreeTheta[i]; double s = bestThreeIntensity[i]; if (t != double.MinValue && (Math.Abs(t - tNew) < 30 || 180 - Math.Abs(t - tNew) < 30) && Math.Abs(r - rNew) < 30) { bestThreeRadius[i] = (short)(((r * s) + (rNew * sNew)) / (s + sNew)); bestThreeTheta[i] = (short)(((t * s) + (tNew * sNew)) / (s + sNew)); bestThreeIntensity[i] += sNew; isNew = false; break; } } if (isNew) { double minS = double.MaxValue; int minSidx = 0; for (int i = 0; i < 3; i++) { if (bestThreeIntensity[i] < minS) { minS = bestThreeIntensity[i]; minSidx = i; } } if (sNew > bestThreeIntensity[minSidx]) { bestThreeRadius[minSidx] = rNew; bestThreeIntensity[minSidx] = sNew; bestThreeTheta[minSidx] = tNew; } } } for (int i = 0; i < 3; i++) { currentStateProbs[i] = double.MinValue; if (bestThreeTheta[i] == double.MinValue || bestThreeIntensity[i] < 1) { bestThreeTheta[i] = double.MinValue; continue; } currentThetaStates[i] = (int)bestThreeTheta[i]; currentRStates[i] = bestThreeRadius[i]; currentStateProbs[i] = bestThreeIntensity[i]; } threadRunning = false; DateTime tack = DateTime.Now; //Console.WriteLine(tack.Subtract(tick).Milliseconds); }
// Process image private void ProcessImage(Bitmap bitmap) { QuantizeImage(bitmap); Grayscale grayscaleFilter = new Grayscale(0.33, 0.33, 0.34); // apply the filter Bitmap grayImage = grayscaleFilter.Apply(bitmap); //Get Histogram /*int[] histogram = new int[256]; * for (int i = 0; i < 256; i++) { * histogram[i] = 0; * } * for (int i = 0; i < grayImage.Width; i++ ) * { * for (int j = 0; j < grayImage.Height; j++) { * histogram[(Convert.ToInt32(grayImage.GetPixel(i, j).R.ToString()) + Convert.ToInt32(grayImage.GetPixel(i, j).G.ToString()) + * Convert.ToInt32(grayImage.GetPixel(i, j).B.ToString()))/3] +=1; * } * }*/ // create filter SobelEdgeDetector sobelFilter = new SobelEdgeDetector(); // apply the filter sobelFilter.ApplyInPlace(grayImage); Threshold filter = new Threshold(243); // apply the filter filter.ApplyInPlace(grayImage); HoughLineTransformation lineTransform = new HoughLineTransformation(); lineTransform.ProcessImage(grayImage); Bitmap houghLineImage = lineTransform.ToBitmap(); // get lines using relative intensity HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(0.5); BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); BitmapData grayImageData = grayImage.LockBits( new Rectangle(0, 0, grayImage.Width, grayImage.Height), ImageLockMode.ReadWrite, grayImage.PixelFormat); UnmanagedImage unmanagedImage = new UnmanagedImage(bitmapData); int w2 = 0, h2 = 0; Color color = Color.Black; foreach (HoughLine line in lines) { String temp = line.Theta.ToString(); //MessageBox.Show(temp, "ok", MessageBoxButtons.OK); // get line's radius and theta values int r = line.Radius; double t = line.Theta; // check if line is in lower part of the image if (r < 0) { t += 180; r = -r; } // convert degrees to radians t = (t / 180) * Math.PI; // get image centers (all coordinate are measured relative // to center) w2 = grayImage.Width / 2; h2 = grayImage.Height / 2; double x0 = 0, x1 = 0, y0 = 0, y1 = 0; if (line.Theta != 0) { // horizontal // none-vertical line if (line.Theta > 0 && line.Theta < 10 || line.Theta > 170) { x0 = -w2; // most left point x1 = w2; // most right point y0 = (-Math.Cos(t) * x0 + r) / Math.Sin(t); y1 = (-Math.Cos(t) * x1 + r) / Math.Sin(t); color = Color.Red; Drawing.Line(bitmapData, new IntPoint((int)x0 + w2, h2 - (int)y0), new IntPoint((int)x1 + w2, h2 - (int)y1), color); Drawing.Line(grayImageData, new IntPoint((int)x0 + w2, h2 - (int)y0), new IntPoint((int)x1 + w2, h2 - (int)y1), color); } if (line.Theta > 80 && line.Theta < 100) { x0 = -w2; // most left point x1 = w2; // most right point y0 = (-Math.Cos(t) * x0 + r) / Math.Sin(t); y1 = (-Math.Cos(t) * x1 + r) / Math.Sin(t); Drawing.Line(bitmapData, new IntPoint((int)x0 + w2, h2 - (int)y0), new IntPoint((int)x1 + w2, h2 - (int)y1), Color.Blue); Drawing.Line(grayImageData, new IntPoint((int)x0 + w2, h2 - (int)y0), new IntPoint((int)x1 + w2, h2 - (int)y1), Color.Blue); } } else { // vertical line x0 = line.Radius; x1 = line.Radius; y0 = h2; y1 = -h2; color = Color.Red; Drawing.Line(bitmapData, new IntPoint((int)x0 + w2, h2 - (int)y0), new IntPoint((int)x1 + w2, h2 - (int)y1), color); Drawing.Line(grayImageData, new IntPoint((int)x0 + w2, h2 - (int)y0), new IntPoint((int)x1 + w2, h2 - (int)y1), color); } // // draw line on the image } bitmap.UnlockBits(bitmapData); grayImage.UnlockBits(grayImageData); MessageBox.Show(lines.Length + "", "ok", MessageBoxButtons.OK); Clipboard.SetDataObject(bitmap); // and to picture box pictureBox.Image = bitmap; UpdatePictureBoxPosition(); }
private HoughLine processSubImage(Bitmap subImg) { HoughLineTransformation hlt = new HoughLineTransformation(); hlt.ProcessImage(subImg); HoughLine[] hlsin = hlt.GetMostIntensiveLines(1); if (hlsin == null || hlsin.Length == 0 || hlsin[0].Intensity < 0.000001) return null; return hlsin[0]; }
public BahtinovImage GrabBahtinov() { var bahtinovImage = new BahtinovImage(); Bitmap convertedSource; if (originalSource.Format != System.Windows.Media.PixelFormats.Gray8) { if (originalSource.Format != System.Windows.Media.PixelFormats.Gray16) { using (var imgToConvert = ImageUtility.BitmapFromSource(originalSource, System.Drawing.Imaging.PixelFormat.Format48bppRgb)) { convertedSource = new Grayscale(0.2125, 0.7154, 0.0721).Apply(imgToConvert); } convertedSource = ImageUtility.Convert16BppTo8Bpp(ImageUtility.ConvertBitmap(convertedSource, System.Windows.Media.PixelFormats.Gray16)); } else { convertedSource = ImageUtility.Convert16BppTo8Bpp(originalSource); } } else { convertedSource = ImageUtility.BitmapFromSource(originalSource, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); convertedSource.Palette = ImageUtility.GetGrayScalePalette(); } using (var focusEllipsePen = new System.Drawing.Pen(System.Drawing.Brushes.Green, 1)) { using (var intersectEllipsePen = new System.Drawing.Pen(System.Drawing.Brushes.Red, 1)) { var mediaColor = backgroundColor; var drawingColor = System.Drawing.Color.FromArgb(mediaColor.A, mediaColor.R, mediaColor.G, mediaColor.B); using (var linePen = new System.Drawing.Pen(drawingColor, 1)) { using (var bahtinovedBitmap = new Bitmap(convertedSource.Width, convertedSource.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb)) { Graphics graphics = Graphics.FromImage(bahtinovedBitmap); graphics.DrawImage(convertedSource, 0, 0); /* Apply filters and detection*/ CannyEdgeDetector filter = new CannyEdgeDetector(); filter.GaussianSize = 10; filter.ApplyInPlace(convertedSource); HoughLineTransformation lineTransform = new HoughLineTransformation(); lineTransform.ProcessImage(convertedSource); HoughLine[] lines = lineTransform.GetMostIntensiveLines(6); List <Line> bahtinovLines = new List <Line>(); foreach (HoughLine line in lines) { var k = TranslateHughLineToLine(line, bahtinovedBitmap.Width, bahtinovedBitmap.Height); bahtinovLines.Add(k); } float x1, x2, y1, y2; if (bahtinovLines.Count == 6) { var orderedPoints = bahtinovLines.OrderBy(x => 1.0d / x.Slope).ToList(); var threeLines = new List <Line>(); for (var i = 0; i < orderedPoints.Count(); i += 2) { var l1 = orderedPoints[i]; var l2 = orderedPoints[i + 1]; var inter = (l1.Intercept + l2.Intercept) / 2.0f; var slope = (l1.Slope + l2.Slope) / 2.0f; var centerLine = Line.FromSlopeIntercept(slope, inter); threeLines.Add(centerLine); x1 = 0; x2 = convertedSource.Width; y1 = double.IsInfinity(centerLine.Slope) ? centerLine.Intercept : centerLine.Slope + centerLine.Intercept; y2 = double.IsInfinity(centerLine.Slope) ? centerLine.Intercept : (centerLine.Slope * (convertedSource.Width) + centerLine.Intercept); graphics.DrawLine( linePen, new PointF(x1, y1), new PointF(x2, y2)); } /* Intersect outer bahtinov lines */ var intersection = threeLines[0].GetIntersectionWith(threeLines[2]); if (intersection.HasValue) { /* get orthogonale to center line through intersection */ var centerBahtinovLine = threeLines[1]; var orthogonalSlope = -1.0f / centerBahtinovLine.Slope; var orthogonalIntercept = intersection.Value.Y - orthogonalSlope * intersection.Value.X; var orthogonalCenter = Line.FromSlopeIntercept(orthogonalSlope, orthogonalIntercept); var intersection2 = centerBahtinovLine.GetIntersectionWith(orthogonalCenter); if (intersection2.HasValue && !double.IsInfinity(intersection2.Value.X)) { x1 = intersection.Value.X; y1 = intersection.Value.Y; x2 = intersection2.Value.X; y2 = intersection2.Value.Y; bahtinovImage.Distance = intersection.Value.DistanceTo(intersection2.Value); var t = bahtinovImage.Distance * 4 / bahtinovImage.Distance; var x3 = (float)((1 - t) * x1 + t * x2); var y3 = (float)((1 - t) * y1 + t * y2); var r = 10; graphics.DrawEllipse( intersectEllipsePen, new RectangleF(x3 - r, y3 - r, 2 * r, 2 * r)); graphics.DrawEllipse( focusEllipsePen, new RectangleF(x2 - r, y2 - r, 2 * r, 2 * r)); graphics.DrawLine( intersectEllipsePen, new PointF(x3, y3), new PointF(x2, y2)); } } } var img = ImageUtility.ConvertBitmap(bahtinovedBitmap, System.Windows.Media.PixelFormats.Bgr24); convertedSource.Dispose(); img.Freeze(); bahtinovImage.Image = img; return(bahtinovImage); } } } } }
public void hough_line() { string basePath = NUnit.Framework.TestContext.CurrentContext.TestDirectory; #region doc_apply_part1 // Let's use a standard test image to show how to apply // the Hough image transform. For this, we can load an // example image using the TestImages class: var testImages = new Accord.DataSets.TestImages(basePath); // We'll use the sudoku test image from OpenCV: Bitmap image = testImages.GetImage("sudoku.png"); // Convert it to binary and mark the possible lines // in white so it can be processed by the transform var sequence = new FiltersSequence( Grayscale.CommonAlgorithms.BT709, new NiblackThreshold(), new Invert() ); // Apply the sequence of filters above: Bitmap binaryImage = sequence.Apply(image); // Finally, we can create a Line Hough Transform: var lineTransform = new HoughLineTransformation(); // and then apply it to the binary image: lineTransform.ProcessImage(binaryImage); // the output of the transform can be seen using Bitmap houghLineImage = lineTransform.ToBitmap(); // For visualization purposes, we can either display the result of the // transform on the screen or save it to disk to be visualized later: // ImageBox.Show(houghLineImage); // houghLineImage.Save("hough-output.png"); #endregion #region doc_apply_part2 // Now, let's say we would like to retrieve the lines and use them // for further processing. First, the lines can be ordered by their // relative intensity using HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(0.9); // Then, let's plot them on top of the input image. Since we will // apply many operations to a single image, it is better to first // convert it to an UnmanagedImage object to avoid having to lock // the image into memory multiple times. UnmanagedImage unmanagedImage = UnmanagedImage.FromManagedImage(image); // Finally, plot them in order: foreach (HoughLine line in lines) { line.Draw(unmanagedImage, color: Color.Red); } // ImageBox.Show(unmanagedImage); // unmanagedImage.ToManagedImage().Save("hough-lines.png"); #endregion Assert.AreEqual(18, lines.Length); lines = lineTransform.GetLinesByRelativeIntensity(0.95); Assert.AreEqual(6, lines.Length); Assert.AreEqual(89, lines[0].Theta); Assert.AreEqual(-236, lines[0].Radius); Assert.AreEqual(531, lines[0].Intensity); Assert.AreEqual(1, lines[0].RelativeIntensity, 1e-8); Assert.AreEqual(4, lines[1].Theta); Assert.AreEqual(224, lines[1].Radius); Assert.AreEqual(516, lines[1].Intensity); Assert.AreEqual(0.97175141242937857, lines[1].RelativeIntensity, 1e-8); Assert.AreEqual(90, lines[2].Theta); Assert.AreEqual(-129, lines[2].Radius); Assert.AreEqual(508, lines[2].Intensity); Assert.AreEqual(0.95668549905838041, lines[2].RelativeIntensity, 1e-8); Assert.AreEqual(90, lines[3].Theta); Assert.AreEqual(-77, lines[3].Radius); Assert.AreEqual(507, lines[3].Intensity); Assert.AreEqual(0.95480225988700562, lines[3].RelativeIntensity, 1e-8); Assert.AreEqual(2, lines[4].Theta); Assert.AreEqual(123, lines[4].Radius); Assert.AreEqual(505, lines[4].Intensity); Assert.AreEqual(0.95103578154425616, lines[4].RelativeIntensity, 1e-8); Assert.AreEqual(179, lines[5].Theta); Assert.AreEqual(26, lines[5].Radius); Assert.AreEqual(505, lines[5].Intensity); Assert.AreEqual(0.95103578154425616, lines[5].RelativeIntensity, 1e-8); }
private void HoughLines() { var image = Accord.Imaging.Image.Clone(_bitmap, PixelFormat.Format24bppRgb); int imageWidth = image.Width; int imageHeight = image.Height; FiltersSequence filter = new FiltersSequence(Grayscale.CommonAlgorithms.BT709, new Threshold(64)); HoughLineTransformation lineTransform = new HoughLineTransformation(); // lock the source image BitmapData sourceData = image.LockBits( new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat); // binarize the image UnmanagedImage binarySource = filter.Apply(new UnmanagedImage(sourceData)); // apply Hough line transform lineTransform.ProcessImage(binarySource); // get lines using relative intensity HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(0.5); List <ABLine> ablines = new List <ABLine>(); foreach (HoughLine line in lines) { string s = string.Format("Theta = {0}, R = {1}, I = {2} ({3})", line.Theta, line.Radius, line.Intensity, line.RelativeIntensity); System.Diagnostics.Debug.WriteLine(s); // uncomment to highlight detected lines // get line's radius and theta values int r = line.Radius; double t = line.Theta; // check if line is in lower part of the image if (r < 0) { t += 180; r = -r; } // convert degrees to radians t = (t / 180) * Math.PI; // get image centers (all coordinate are measured relative // to center) int w2 = image.Width / 2; int h2 = image.Height / 2; double x0 = 0, x1 = 0, y0 = 0, y1 = 0; if (line.Theta != 0) { // none vertical line x0 = -w2; // most left point x1 = w2; // most right point // calculate corresponding y values y0 = (-Math.Cos(t) * x0 + r) / Math.Sin(t); y1 = (-Math.Cos(t) * x1 + r) / Math.Sin(t); } else { // vertical line x0 = line.Radius; x1 = line.Radius; y0 = h2; y1 = -h2; } ablines.Add(new ABLine() { P1 = new System.Drawing.Point((int)x0 + w2, h2 - (int)y0), P2 = new System.Drawing.Point((int)x1 + w2, h2 - (int)y1) }); } using (var g = Graphics.FromImage(_bitmap)) using (Pen pen = new Pen(Color.Red)) { pen.Width = 2; foreach (var l in ablines) { if (Math.Abs(l.P1.X - l.P2.X) > 200) { continue; } g.DrawLine(pen, l.P1, l.P2); } } }
private void GetIntersect(Bitmap grayImage, Bitmap bitmap, int[,,] intersectPoint) { HoughLineTransformation lineTransform = new HoughLineTransformation(); lineTransform.ProcessImage(grayImage); Bitmap houghLineImage = lineTransform.ToBitmap(); // get lines using relative intensity HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(0.5); BitmapData bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); BitmapData grayImageData = grayImage.LockBits( new Rectangle(0, 0, grayImage.Width, grayImage.Height), ImageLockMode.ReadWrite, grayImage.PixelFormat); UnmanagedImage unmanagedImage = new UnmanagedImage(bitmapData); int w2 = 0, h2 = 0; Color color = Color.Black; int[] mVer = new int[19]; double[] mHor = new double[19]; double[] cVer = new double[19]; double[] cHor = new double[19]; int verCount = 0; int horCount = 0; foreach (HoughLine line in lines) { String temp = line.Theta.ToString(); // get line's radius and theta values int r = line.Radius; double t = line.Theta; // check if line is in lower part of the image if (r < 0) { t += 180; r = -r; } // convert degrees to radians t = (t / 180) * Math.PI; // get image centers (all coordinate are measured relative // to center) w2 = grayImage.Width / 2; h2 = grayImage.Height / 2; double x0 = 0, x1 = 0, y0 = 0, y1 = 0; if (line.Theta != 0) { // vertical line if (line.Theta > 0 && line.Theta < 10 || line.Theta > 170) { y0 = -h2; y1 = h2; x0 = (r - (Math.Sin(t) * y0)) / Math.Cos(t); x1 = (r - (Math.Sin(t) * y1)) / Math.Cos(t); color = Color.Red; x0 = w2 + (int)x0; x1 = w2 + (int)x1; y0 = (h2 - y0); y1 = (h2 - y1); //mVer[verCount] = (int) -(Math.Cos(t)/Math.Sin(t)); //cVer[verCount] = (double)r*(1/Math.Sin(t)); if ((int)x0 == (int)x1) { mVer[verCount] = (int)((y1 - y0) / (x1 - x0 + 1)); cVer[verCount] = y0 - (mVer[verCount] * x0); } else { mVer[verCount] = (int)((y1 - y0) / (x1 - x0)); cVer[verCount] = (y0 - (mVer[verCount] * x0)); } /*Drawing.Line(bitmapData, * new IntPoint((int)x0, (int)y0), * new IntPoint((int)x1 ,(int)y1), * color); * Drawing.Line(grayImageData, * new IntPoint((int)x0 , (int)y0), * new IntPoint((int)x1 , (int)y1), * color);*/ verCount++; } // horizontal if (line.Theta > 80 && line.Theta < 100) { x0 = -w2; // most left point x1 = w2; // most right point6 y0 = (-Math.Cos(t) * x0 + r) / Math.Sin(t); y1 = (-Math.Cos(t) * x1 + r) / Math.Sin(t); x0 = x0 + w2; x1 = x1 + w2; y0 = (int)(h2 - (int)y0); y1 = (int)(h2 - (int)y1); //mHor[horCount] = (int)-(Math.Cos(t) / Math.Sin(t)); //cHor[horCount] = (double)r * (1 / Math.Sin(t)); mHor[horCount] = ((y1 - y0) / (x1 - x0)); cHor[horCount] = y0 - (mHor[horCount] * x0); horCount++; /*Drawing.Line(bitmapData, * new IntPoint((int)x0,(int)y0), * new IntPoint((int)x1, (int)y1), * Color.Blue); * Drawing.Line(grayImageData, * new IntPoint((int)x0, (int)y0), * new IntPoint((int)x1, (int)y1), * Color.Blue);*/ } } else { // vertical line x0 = line.Radius; x1 = line.Radius; y0 = h2; y1 = -h2; color = Color.Yellow; x0 = x0 + w2; x1 = x1 + w2; y0 = (h2 - (int)y0); y1 = (h2 - (int)y1); //mVer[verCount] = (int)-(Math.Cos(t) / Math.Sin(t)); //cVer[verCount] = (double)r * (1 / Math.Sin(t)); mVer[verCount] = (int)((y1 - y0) / (x1 - x0 + 1)); cVer[verCount] = y0 - (mVer[verCount] * x0); /*Drawing.Line(bitmapData, * new IntPoint((int)x0, (int)y0), * new IntPoint((int)x1, (int)y1), * color); * Drawing.Line(grayImageData, * new IntPoint((int)x0, (int)y0), * new IntPoint((int)x1, (int)y1), * color);*/ //MessageBox.Show("y0 = " + y0 + " y1 = " + y1 + " x0 = " + x0 + " x1 = " + x1 + // " m = " + mVer[verCount] + " c = " + cVer[verCount], "ok", MessageBoxButtons.OK); verCount++; } } for (int i = 0; i < 19; i++) { for (int j = 0; j < 19; j++) { intersectPoint[0, i, j] = (int)((cHor[j] - cVer[i]) / (mVer[i] - mHor[j])); intersectPoint[1, i, j] = (int)((mHor[j] * intersectPoint[0, i, j]) + cHor[j]); } } int num = 0; //MessageBox.Show("num = " + num + " mv =" + mVer[num] + "," + " cv = " + cVer[num] + " mh =" + mHor[num] + "," + " ch = " + cHor[num] + "," + "x = " // + intersectPoint[0, num, num] + "y = " + intersectPoint[1, num, num], "ok", MessageBoxButtons.OK); bitmap.UnlockBits(bitmapData); grayImage.UnlockBits(grayImageData); //MessageBox.Show(mVer[18] + "," + cVer[18] + "," + intersectPoint[0, 18, 18], "ok", MessageBoxButtons.OK); //MessageBox.Show(intersectPoint. + "", "ok", MessageBoxButtons.OK); }
public static Tuple <Bitmap, double, Rectangle> smate_rotate(Bitmap src) { Bitmap retB = null; Rectangle retR = Rectangle.Empty; double retAngle = 90.0; double angle = 0.0; RotateBicubic filter = new RotateBicubic(retAngle); Bitmap src1 = filter.Apply(src); //Bitmap src1 = (Bitmap)src.Clone(); Bitmap g = Grayscale.CommonAlgorithms.BT709.Apply(src1); Invert it = new Invert(); it.ApplyInPlace(g); //g.Save("temp_1.jpg"); ImageStatistics stat = new ImageStatistics(g); Threshold t = new Threshold((int)(stat.Gray.Mean - stat.Gray.StdDev)); t.ApplyInPlace(g); //g.Save("temp_2.jpg"); stat = new ImageStatistics(g); DifferenceEdgeDetector edgeDetector = new DifferenceEdgeDetector(); edgeDetector.ApplyInPlace(g); //g.Save("temp_3.jpg"); HoughLineTransformation lineTransform = new HoughLineTransformation(); lineTransform.ProcessImage(g); HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(0.8); foreach (HoughLine l in lines) { Program.logIt(string.Format("Intensity={0}, Radius={1}, Theta={2}", l.Intensity, l.Radius, l.Theta)); if (l.Radius < 0) { if (l.Theta < 90) { angle = -l.Theta; } else { angle = 180.0 - l.Theta; } } else { if (l.Theta < 90) { angle = -l.Theta; } else { angle = 180.0 - l.Theta; } } if (Math.Abs(angle) < 45.0) { break; } } Program.logIt(string.Format("angle={0}", angle)); retAngle += angle; RotateBicubic r_filter = new RotateBicubic(angle); Bitmap rotated = r_filter.Apply(src1); // crop if (rotated != null) { Grayscale g_filter = new Grayscale(0.2125, 0.7154, 0.0721); Bitmap grayImage = g_filter.Apply(rotated); Blur bf = new Blur(); bf.ApplyInPlace(grayImage); OtsuThreshold o_filter = new OtsuThreshold(); o_filter.ApplyInPlace(grayImage); BlobCounter blobCounter = new BlobCounter(); blobCounter.MinHeight = 20; blobCounter.MinWidth = 20; blobCounter.FilterBlobs = false; blobCounter.BlobsFilter = null; blobCounter.ObjectsOrder = ObjectsOrder.YX; blobCounter.ProcessImage(grayImage); Blob[] blobs = blobCounter.GetObjectsInformation(); Program.logIt(string.Format("blobs={0}", blobCounter.ObjectsCount)); Rectangle r = Rectangle.Empty; for (int i = 1; i < blobs.Length; i++) { Blob b = blobs[i]; Program.logIt(string.Format("{0}: {1}", b.ID, b.Rectangle)); if (r == Rectangle.Empty) { r = b.Rectangle; } else { r = Rectangle.Union(r, b.Rectangle); } } Program.logIt(string.Format("rect: {0}", r)); retR = r; Crop c_filter = new Crop(r); retB = c_filter.Apply(rotated); } return(new Tuple <Bitmap, double, Rectangle>(retB, retAngle, retR)); }
private void button3_Click(object sender, EventArgs e) { gbr = (Bitmap)pictureBox1.Image; Rectangle rect = new Rectangle(0, 0, gbr.Width, gbr.Height); HoughLineTransformation hough = new HoughLineTransformation(); hough.ProcessImage(ConvertToFormat(gbr, PixelFormat.Format8bppIndexed)); Bitmap res = hough.ToBitmap(); HoughLine[] lines = hough.GetLinesByRelativeIntensity(0.5); MessageBox.Show("Jumlah Garis: " + lines.Length); foreach (var line in lines) { // get line's radius and theta values int r = line.Radius; double t = line.Theta; // check if line is in lower part of the image if (r < 0) { t += 180; r = -r; } // convert degrees to radians t = (t / 180) * Math.PI; // get image centers (all coordinate are measured relative // to center) int w2 = gbr.Width / 2; int h2 = gbr.Height / 2; double x0 = 0, x1 = 0, y0 = 0, y1 = 0; if (line.Theta != 0) { // none-vertical line x0 = -w2; // most left point x1 = w2; // most right point // calculate corresponding y values y0 = (-Math.Cos(t) * x0 + r) / Math.Sin(t); y1 = (-Math.Cos(t) * x1 + r) / Math.Sin(t); } else { // vertical line x0 = line.Radius; x1 = line.Radius; y0 = h2; y1 = -h2; } Pen pen = new Pen(Brushes.Red, 3); Graphics g = Graphics.FromImage(res); g.DrawLine(pen, (int)x0 + w2, h2 - (int)y0, (int)x1 + w2, h2 - (int)y1); // draw line on the image //Drawing.Line(data, // new IntPoint((int)x0 + w2, h2 - (int)y0), // new IntPoint((int)x1 + w2, h2 - (int)y1), // Color.Red); g.Dispose(); } pictureBox2.Image = res; }