public static byte Run(Bitmap bmp, int centerX, int centerY, int[] mask) { int d = (int)Math.Sqrt(mask.Length); if (centerX - d < 0 || centerY - d < 0) { return(bmp.GetPixel(centerX, centerY).R); } else { int halfd = (int)Math.Floor(d / 2.0); Rectangle rect = new Rectangle(centerX - halfd, centerY - halfd, d, d); Bitmap rectBmp = bmp.Clone(rect, bmp.PixelFormat); Bitmap3 bitmap3 = new Bitmap3(rectBmp); double v = 0; for (int i = 0; i < mask.Length; i++) { v += bitmap3.Bitplane[0].GetPixel(i % d, (int)1 / d); } return(Convert.ToByte(v / mask.Length)); } }
/// <summary> /// slic计算 /// </summary> /// <param name="bmp"></param> /// <param name="numberOfCenters"></param> /// <param name="m"></param> /// <param name="edgeColor"></param> /// <returns></returns> public static SlicPackage Run(Bitmap bmp, double numberOfCenters, double m, Color edgeColor) { Bitmap3 image = new Bitmap3(bmp); Bitmap[] processedImages = new Bitmap[2]; // Convert RGB TO LAB image.RGBtoLAB(); // Create centers double S = Math.Sqrt((image.Width * image.Height) / numberOfCenters); Center[] centers = CreateCenters(image, numberOfCenters, S); Bitplane labels = new Bitplane(image.Width, image.Height); labels.SetAllTo(-1); for (int iteration = 0; iteration < 10; iteration++) { Bitplane lenghts = new Bitplane(image.Width, image.Height); lenghts.Max(); int i = 0; foreach (Center center in centers) { for (int k = (int)Math.Round(center.X - S); k < (int)Math.Round(center.X + S); k++) { for (int l = (int)Math.Round(center.Y - S); l < (int)Math.Round(center.Y + S); l++) { if (k >= 0 && k < image.Width && l >= 0 && l < image.Height) { double L = image.Bitplane[2].GetPixel(k, l); double A = image.Bitplane[1].GetPixel(k, l); double B = image.Bitplane[0].GetPixel(k, l); double Dc = Math.Sqrt(Math.Pow(L - center.L, 2) + Math.Pow(A - center.A, 2) + Math.Pow(B - center.B, 2)); double Ds = Math.Sqrt(Math.Pow(l - center.Y, 2) + Math.Pow(k - center.X, 2)); double lenght = Math.Sqrt(Math.Pow(Dc, 2) + Math.Pow(Ds / 2, 2) * Math.Pow(m, 2)); if (lenght < lenghts.GetPixel(k, l)) { lenghts.SetPixel(k, l, lenght); labels.SetPixel(k, l, i); } } } } i++; } centers = CalculateNewCenters(image, centers, labels); } //image.GetBitmap().Save(@"D:\Workspace\bmp\o.jpg"); //image = drawAverage(image, centers, labels); //image.LABtoRGB(); //processedImages[0] = image.GetBitmap(); // Segmented image = DrawEdges(image, centers, labels, edgeColor); image.LABtoRGB(); processedImages[0] = image.GetBitmap(); // Segmented with Edge image = DrawAverage(image, centers, labels); image.LABtoRGB(); processedImages[1] = image.GetBitmap(); //center string centerText = Newtonsoft.Json.JsonConvert.SerializeObject(centers); //label string labelText = Newtonsoft.Json.JsonConvert.SerializeObject(labels); return(new SlicPackage() { Label = labelText, Edge = processedImages[0], Average = processedImages[1], CENTER = centerText, }); }