/// <summary> /// Use the Luminosity parameter of the background color to detect light vs dark theme settings. /// </summary> /// <remarks> /// This approach detects both the common High Contrast themes (White vs Black) and custom themes which may have relatively lighter backgrounds. /// </remarks> public void CheckBackgroundBrightness() { SolidColorBrush windowbrush = System.Windows.SystemColors.WindowBrush; System.Drawing.Color dcolor = System.Drawing.Color.FromArgb(windowbrush.Color.A, windowbrush.Color.R, windowbrush.Color.G, windowbrush.Color.B); var brightness = dcolor.GetBrightness(); // Test for 'Lightness' at an arbitrary point, approaching 1.0 (White). if (0.7 < brightness) { this.IsLightBackground = true; } else { this.IsLightBackground = false; } }
public List <DColor> GetHarmony(DColor initial, Harmonies harmony) //TODO: function for returning sectors { List <DColor> l = new List <DColor>(); l.Add(initial); switch (harmony) { case Harmonies.Monochromatic: Random r = new Random(); l.Add(HSV2RGB(initial.GetHue(), r.NextDouble(), r.NextDouble())); break; case Harmonies.Analog: l.Add(HSV2RGB(initial.GetHue() - SECTION, initial.GetSaturation(), initial.GetBrightness())); l.Add(HSV2RGB(initial.GetHue() + SECTION, initial.GetSaturation(), initial.GetBrightness())); break; case Harmonies.Complementary: l.Add(HSV2RGB(initial.GetHue() + 180, initial.GetSaturation(), initial.GetBrightness())); break; case Harmonies.SplitComplementary: l.Add(HSV2RGB(initial.GetHue() + 180 - SECTION, initial.GetSaturation(), initial.GetBrightness())); l.Add(HSV2RGB(initial.GetHue() + 180 + SECTION, initial.GetSaturation(), initial.GetBrightness())); break; case Harmonies.Tetradic: l.Add(HSV2RGB(initial.GetHue() + 90, initial.GetSaturation(), initial.GetBrightness())); l.Add(HSV2RGB(initial.GetHue() + 180, initial.GetSaturation(), initial.GetBrightness())); l.Add(HSV2RGB(initial.GetHue() + 270, initial.GetSaturation(), initial.GetBrightness())); break; case Harmonies.Triad: l.Add(HSV2RGB(initial.GetHue() + 120, initial.GetSaturation(), initial.GetBrightness())); l.Add(HSV2RGB(initial.GetHue() + 240, initial.GetSaturation(), initial.GetBrightness())); break; } return(l); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double threshold = 0.5; if (parameter != null) { double.TryParse(parameter.ToString(), NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out threshold); } if (value is SolidColorBrush brush) { var mediaColor = brush.Color; System.Drawing.Color drawingColor = System.Drawing.Color.FromArgb(mediaColor.R, mediaColor.G, mediaColor.B); var brightness = drawingColor.GetBrightness(); if (brightness > threshold) { return(new SolidColorBrush(Color.FromArgb(255, 0, 0, 0))); } else { return(new SolidColorBrush(Color.FromArgb(255, 255, 255, 255))); } } else if (value is string valueString) { var mediaColor = (Color)ColorConverter.ConvertFromString(valueString); System.Drawing.Color drawingColor = System.Drawing.Color.FromArgb(mediaColor.R, mediaColor.G, mediaColor.B); var brightness = drawingColor.GetBrightness(); if (brightness > threshold) { return("Black"); } else { return("White"); } } else { return(value); } }
private Brush GetNewLayerSelectionColor(Color backgroundColor) { System.Drawing.Color color = System.Drawing.Color.FromArgb(backgroundColor.A, backgroundColor.R, backgroundColor.G, backgroundColor.B); float hue = color.GetHue(); float saturation = color.GetSaturation(); float lightness = color.GetBrightness(); if (backgroundColor.A < 64) //transparent color { return(Brushes.White); } if (lightness < 0.5) //dark color { return(Brushes.White); } //light color return(CustomBrushes.VeryDarkGray); }
public Task <CommandResponse> SetColor(System.Drawing.Color color) { Hsv hsv = new Hsb() { H = color.GetHue(), S = color.GetSaturation(), B = color.GetBrightness() }.To <Hsv>(); Commands commands = new Commands(); commands.AddCommand("work_mode", "colour"); commands.AddCommand("colour_data_v2", new { h = Math.Round(hsv.H), s = Math.Round(hsv.S * 1000), v = Math.Round(hsv.V * 1000) }); return(rumahTuya.SendCommands(deviceId, commands)); }
public static IEnumerable <System.Drawing.Color> Range(this System.Drawing.Color firstColor, System.Drawing.Color lastColor, int count, Direction hueDirection) { var color = firstColor; if (count <= 0) { yield break; } if (count == 1) { yield return(firstColor); } float startingHue = color.GetHue(); float stepHue = GetStepping(firstColor.GetHue(), lastColor.GetHue(), count - 1, hueDirection); var stepSaturation = (lastColor.GetSaturation() - firstColor.GetSaturation()) / (count - 1); var stepBrightness = (lastColor.GetBrightness() - firstColor.GetBrightness()) / (count - 1); var stepAlpha = (lastColor.A - firstColor.A) / (count - 1.0); for (int i = 1; i < count; i++) { yield return(color); var hueValue = startingHue + stepHue * i; if (hueValue > 360) { hueValue -= 360; } if (hueValue < 0) { hueValue = 360 + hueValue; } color = FromAhsb( Clamp((int)(color.A + stepAlpha), 0, 255), hueValue, Clamp(color.GetSaturation() + stepSaturation, 0, 1), Clamp(color.GetBrightness() + stepBrightness, 0, 1)); } yield return(lastColor); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // To be here, we know a high contrast theme is active. So get the color for window backgrounds. var windowBackgroundBrush = SystemColors.WindowBrush; System.Drawing.Color windowBackgroundColor = System.Drawing.Color.FromArgb( 0, windowBackgroundBrush.Color.R, windowBackgroundBrush.Color.G, windowBackgroundBrush.Color.B); string result; // If the background for text with this hgh contrast theme is light, // select the dark-on-light clock face image. Otherwise select the // light-on-dark version. if (windowBackgroundColor.GetBrightness() > 0.5) { result = "/GFClock;component/Assets/ClockFace_DarkOnLight.png"; } else { result = "/GFClock;component/Assets/ClockFace_LightOnDark.png"; } return(result); }
public float GetBrightness() { System.Drawing.Color c = (Color)_color; return(c.GetBrightness()); }
private void DoReloadModel(string fieldDataFile, bool isWindMap) { // Create the plot model PlotModel model = this.Model; model.PlotMargins = new OxyThickness(30, 0, 60, 30); model.Axes.Clear(); model.Series.Clear(); model.Annotations.Clear(); string fileTitle = Path.GetFileNameWithoutExtension(fieldDataFile); this.FileTitle = fileTitle; WeatherDataPalette wdp = WeatherDataPaletteFactory.GetPaletteForDataFile(fieldDataFile); bool contours = wdp.ShowContours; bool heatmap = wdp.ShowHeatmap; bool precipitationMap = false; model.Title = string.Format("{0}: {1} [{2}]{3}", App.ControlPanelModel.SelectedViewport.Name, App.ControlPanelModel.SelectedDataType.Value, fileTitle, App.ControlPanelModel.SelectedDataType.Comments); DenseMatrix m = null; int minLon = App.ControlPanelModel.SelectedViewport.MinLon.Round(); int maxLon = App.ControlPanelModel.SelectedViewport.MaxLon.Round(); int minLat = App.ControlPanelModel.SelectedViewport.MinLat.Round(); int maxLat = App.ControlPanelModel.SelectedViewport.MaxLat.Round(); var fieldMatrix = FileSupport.LoadSubMatrixFromFile(fieldDataFile, minLon, maxLon, minLat, maxLat); bool interpolate = (fieldMatrix.RowCount < 10); if (interpolate) { fieldMatrix = fieldMatrix.Interpolate(); } float[,] data = null; float[,] data2 = null; float actualOffset = 0; if (wdp.ShowHeatmap) { float fOffset = (float)App.ControlPanelModel.Offset / 100; float delta = wdp.MinMax.Delta; if (wdp.GetType() == typeof(C_00_Palette)) { delta = 100; } actualOffset = delta * fOffset; } if (wdp.GetType() == typeof(C_00_Palette)) { // It's a map of the precipitation precipitationMap = true; string t01File = fieldDataFile.Replace("C_00", "T_01"); string teFile = fieldDataFile.Replace("C_00", "T_TE"); string tsFile = fieldDataFile.Replace("C_00", "T_TS"); DenseMatrix T01 = FileSupport.LoadSubMatrixFromFile(t01File, minLon, maxLon, minLat, maxLat); DenseMatrix TE = FileSupport.LoadSubMatrixFromFile(teFile, minLon, maxLon, minLat, maxLat); DenseMatrix TS = FileSupport.LoadSubMatrixFromFile(tsFile, minLon, maxLon, minLat, maxLat); DenseMatrix C00 = fieldMatrix; if (interpolate) { T01 = T01.Interpolate(); TE = TE.Interpolate(); TS = TS.Interpolate(); } float sRain = 0; float sSnow = 300; float sSleet = 600; float sFreezingRain = 900; data2 = C00.Transpose().ToArray(); m = DenseMatrix.Create(C00.RowCount, C00.ColumnCount, (r, c) => { float cl = Math.Abs(C00[r, c]) + actualOffset; if (cl <= 0) { cl = 0; } if (cl >= 100) { cl = 100; } float t01 = T01[r, c]; float te = TE[r, c]; float ts = TS[r, c]; float precipClThreshold = 10f; float actualPrecipRate = (cl - precipClThreshold); if (actualPrecipRate >= 0) { return(PrecipTypeComputer <float> .Compute( // Actual temperatures te, ts, t01, // Boundary temperatures as read from simulation parameters SimulationParameters.Instance, // Computed precip type: snow () => (cl + sSnow), // Computed precip type: rain () => (cl + sRain), // Computed precip type: freezing rain () => (cl + sFreezingRain), // Computed precip type: sleet () => (cl + sSleet) )); } else if (cl > 5) { // Cloudy but without precipitation. return(5); } // Sunny return(0); }); } else { m = DenseMatrix.Create(fieldMatrix.RowCount, fieldMatrix.ColumnCount, (r, c) => fieldMatrix[r, c]); m.ADD(actualOffset); } Range <float> minMax = wdp.MinMax; float lineSpacing = wdp.LineSpacing; m = m.MIN(minMax.Max).MAX(minMax.Min); data = m.Transpose().ToArray(); float step = interpolate ? 0.5f : 1; List <float> cols = new List <float>(); for (float i = minLon; i <= maxLon; i += step) { cols.Add(i); } List <float> rows = new List <float>(); for (float i = maxLat; i >= minLat; i -= step) { rows.Add(i); } List <float> levels = new List <float>(); for (float i = wdp.MinMax.Min; i <= wdp.MinMax.Max; i += wdp.LineSpacing) { levels.Add(i); } var pal = OxyPalette.Interpolate(levels.Count, wdp.ColorSteps.ToArray()); List <OxyColor> lineColors = new List <OxyColor>(); foreach (OxyColor c in wdp.ColorSteps) { if (heatmap) { switch (wdp.LineColor.ColorMode) { case Views.LineColorMode.FixedColor: lineColors.Add(wdp.LineColor.Color); break; case Views.LineColorMode.Best_Contrast: lineColors.Add(c.Complementary()); break; case Views.LineColorMode.Black_And_White: { System.Drawing.Color cw = System.Drawing.Color.FromArgb(c.R, c.G, c.B); float br = cw.GetBrightness(); if (br < 0.5f) { lineColors.Add(OxyColors.White); } else { lineColors.Add(OxyColors.Black); } } break; } } else { lineColors.Add(c); } } if (isWindMap) { this.FileTitle += "_WINDMAP"; var D = (App.ControlPanelModel.SelectedViewport.MaxLon - App.ControlPanelModel.SelectedViewport.MinLon); float hf = 1; if (D > 200) { hf = 0.45f; } else if (D > 20) { hf = 0.55f; } else { hf = 1; } float sf = 0.9f * hf; DenseMatrix[] gr = fieldMatrix.ToWindComponents(); float[,] dataX = gr[Direction.X].ToArray(); float[,] dataY = gr[Direction.Y].ToArray(); int rowCount = dataX.GetLength(0); int colCount = dataX.GetLength(1); for (int r = 0; r < rowCount; r++) { for (int c = 0; c < colCount; c++) { float x = c + App.ControlPanelModel.SelectedViewport.MinLon; float y = App.ControlPanelModel.SelectedViewport.MaxLat - r; float dx = dataX[r, c]; float dy = -dataY[r, c]; int mod = (int)Math.Sqrt(dx * dx + dy * dy); LineSeries line = new LineSeries(); line.Points.Add(new DataPoint(x, y)); line.Points.Add(new DataPoint(x + dx, y + dy)); line.StrokeThickness = 1; if (mod < 2) { line.Color = OxyColors.Green; line.StrokeThickness = 2 * hf; } else if (mod < 5) { line.Color = OxyColors.Red; line.StrokeThickness = 2.5 * hf; } else { line.Color = OxyColors.Magenta; line.StrokeThickness = 3 * hf; } model.Series.Add(line); ArrowAnnotation arrow = new ArrowAnnotation(); var edy = Math.Min(dy, 2); arrow.StartPoint = new DataPoint(x + sf * dx, y + sf * edy); arrow.EndPoint = new DataPoint(x + dx, y + edy); arrow.Color = line.Color; arrow.StrokeThickness = line.StrokeThickness; arrow.HeadWidth = 1.5 * line.StrokeThickness; arrow.HeadLength = 3 * line.StrokeThickness; model.Annotations.Add(arrow); //goto MapFeatures; } } } else { if (heatmap) { if (precipitationMap) { HeatMapSeriesEx cloudMapSeries = new HeatMapSeriesEx { Data = data.ToDoubleArray(), X0 = cols[0], X1 = cols[cols.Count - 1], Y0 = rows[0], Y1 = rows[rows.Count - 1], }; model.Series.Add(cloudMapSeries); } else { OxyPlot.Series.HeatMapSeries heatmapSeries = new OxyPlot.Series.HeatMapSeries { Data = data.ToDoubleArray(), X0 = cols[0], X1 = cols[cols.Count - 1], Y0 = rows[0], Y1 = rows[rows.Count - 1], }; model.Series.Add(heatmapSeries); } } if (contours) { OxyPlot.Series.ContourSeries contour = new OxyPlot.Series.ContourSeries { ColumnCoordinates = cols.ToArray().ToDoubleArray(), RowCoordinates = rows.ToArray().ToDoubleArray(), ContourLevels = levels.ToArray().ToDoubleArray(), ContourColors = lineColors.ToArray(), // Same # elements as the levels' array Data = (data2 == null) ? data.ToDoubleArray() : data2.ToDoubleArray(), LabelBackground = OxyColors.Transparent, ContourLevelStep = wdp.LineSpacing, StrokeThickness = wdp.LineWidth, FontSize = 15, FontWeight = 500, }; model.Series.Add(contour); } } MapFeatures: // Always do this last. AddMapFeatures(model, wdp, pal, isWindMap); }
// POST api/stream public async Task <IHttpActionResult> Post() { Trace.TraceWarning("Received"); Trace.TraceError("Received: " + Request.Content); if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); var results = new List <FaceData>(); foreach (var file in provider.Contents) { var filename = file.Headers.ContentDisposition.FileName.Trim('\"'); var buffer = await file.ReadAsByteArrayAsync(); using (var fileStream = new MemoryStream(buffer)) { try { Trace.TraceError(FaceKey); await PersonManager.CreateGroupIfNotExists(); var TargetFaces = new List <Guid>(); var faceServiceClient = new FaceServiceClient(FaceKey); Trace.TraceError(EmotionKey); var emotionServiceClient = new EmotionServiceClient(EmotionKey); var faces = await faceServiceClient.DetectAsync(fileStream, true, false, new FaceAttributeType[] { FaceAttributeType.Smile }); var Rectangles = new Rectangle[faces.Length]; for (int idx = 0; idx < faces.Length; idx++) { TargetFaces.Add(faces[idx].FaceId); var fr = faces[idx].FaceRectangle; Rectangles[idx] = new Rectangle(); Rectangles[idx].Height = fr.Height; Rectangles[idx].Top = fr.Top; Rectangles[idx].Width = fr.Width; Rectangles[idx].Left = fr.Left; } Trace.TraceError(faces.ToString()); // Get all persons var Persons = await faceServiceClient.GetPersonsAsync(GroupName); Trace.TraceError(Persons.ToString()); // Identify each face // Call identify REST API, the result contains identified person information var identifyResult = await faceServiceClient.IdentifyAsync(GroupName, TargetFaces.ToArray(), 0.3f, 4); var emotion = await emotionServiceClient.RecognizeAsync(fileStream, Rectangles); Trace.TraceError(emotion.ToString()); for (int idx = 0; idx < faces.Length; idx++) { // Update identification result for rendering var f = faces[idx]; var face = TargetFaces[idx]; var res = identifyResult[idx]; var emot = emotion[idx]; var name = "Unknown"; var id = ""; var em = ""; var highest = 0f; if (res.Candidates.Length > 0) { foreach (var person in Persons) { if (person.PersonId.ToString() == res.Candidates[0].PersonId.ToString()) { name = person.Name; id = person.UserData; } } } if (emot.Scores.Neutral > highest) { highest = emot.Scores.Neutral; em = "Neutral"; } if (emot.Scores.Happiness > highest) { highest = emot.Scores.Happiness; em = "Happiness"; } if (emot.Scores.Sadness > highest) { highest = emot.Scores.Sadness; em = "Sadness"; } if (emot.Scores.Surprise + emot.Scores.Fear > highest) { highest = emot.Scores.Surprise + emot.Scores.Fear; em = "Surprise"; } if (emot.Scores.Anger > highest) { highest = emot.Scores.Anger; em = "Anger"; } var dat = new FaceData(); dat.Emotion = em; dat.Id = id; dat.Name = name; dat.FaceId = f.FaceId; dat.FaceRectangle = f.FaceRectangle; dat.FaceAttributes = f.FaceAttributes; // Calculate color int red = (int)(255 * (emot.Scores.Anger + emot.Scores.Surprise + emot.Scores.Fear)); int green = (int)(255 * emot.Scores.Happiness); int blue = (int)(255 * emot.Scores.Sadness); System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue); ColorConversion.HSVToRGB(color.GetHue(), color.GetSaturation(), color.GetBrightness(), out red, out green, out blue); dat.Color = "#" + red.ToString("X2") + green.ToString("X2") + blue.ToString("X2"); results.Add(dat); } } catch (FaceAPIException ex) { Trace.TraceError(ex.ErrorCode + ", " + ex.ErrorMessage); } GC.Collect(); } } Trace.TraceError(results.ToString()); return(Json(results)); }
void CreateSliderList(XElement root, List <SliderItem> sliderList) { SliderTypeEnum sliderType = SliderTypeEnum.RGB; int ix = 0; if (root != null) { foreach (XElement basePoint in root.Elements("BasePoint")) { int Pos = int.Parse(basePoint.Attribute("Pos").Value); PatternPoint pp = Pattern[Pos - 1]; switch (root.Name.ToString()) { case "RGB": System.Drawing.Color color = System.Drawing.Color.FromArgb (0, int.Parse(basePoint.Attribute("R").Value), int.Parse(basePoint.Attribute("G").Value), int.Parse(basePoint.Attribute("B").Value) ); pp = Pattern[Pos - 1]; pp.H = color.GetHue(); pp.S = color.GetSaturation(); pp.L = color.GetBrightness(); pp.SaveLightness(); pp.PointColor = Color.FromRgb(color.R, color.G, color.B); pp.Lightness = Convert.ToInt32(pp.L * 255.0); sliderType = SliderTypeEnum.RGB; break; case "White": pp.WhiteD = double.Parse(basePoint.Attribute("W").Value); pp.InitialWhiteD = pp.WhiteD; sliderType = SliderTypeEnum.W; break; case "WhiteTemp": pp.WhiteD = double.Parse(basePoint.Attribute("W").Value); pp.InitialWhiteD = pp.WhiteD; pp.Temp = double.Parse(basePoint.Attribute("T").Value); sliderType = SliderTypeEnum.WT; break; case "Warm": pp.WarmD = double.Parse(basePoint.Attribute("W").Value); pp.InitialWarmD = pp.WarmD; sliderType = SliderTypeEnum.Warm; break; case "Cold": pp.ColdD = double.Parse(basePoint.Attribute("W").Value); pp.InitialColdD = pp.ColdD; sliderType = SliderTypeEnum.Cold; break; } sliderList.Add(CreateSlider(sliderList, ix, Pos, (PointVariant)int.Parse(basePoint.Attribute("Variant").Value), sliderType)); ix++; } } }
public static Hsl From(System.Drawing.Color color) => new Hsl(color.GetHue() / 360, color.GetSaturation(), color.GetBrightness());
private string ScanColor() { WaitForSensorReady(); RGBColor rgbColor = colorSensor.ReadRGB(); int max = Math.Max(Math.Max(rgbColor.Red, rgbColor.Green), rgbColor.Blue); if (max > 255) // Normalize to max 255 { rgbColor = new RGBColor( (UInt16)((int)rgbColor.Red * 255 / max), (UInt16)((int)rgbColor.Green * 255 / max), (UInt16)((int)rgbColor.Blue * 255 / max)); } Color color = Color.FromArgb(rgbColor.Red, rgbColor.Green, rgbColor.Blue); var hue = (int)color.GetHue(); var bright = (int)(color.GetBrightness() * 100); if ((bright < 15 && hue < 50) || (bright <= 22 && hue < 30) || bright < 15) { LcdConsole.WriteLine("Color scan error"); return("ERR"); } //int sat = (int) (color.GetSaturation()*100); string colorStr = string.Format("R:{0} G:{1} B:{2} H:{3} B:{4} ", rgbColor.Red, rgbColor.Green, rgbColor.Blue, hue, bright); string c = " "; if ((bright > 56) || (hue > 42 && hue < 90 && (float)rgbColor.Red / rgbColor.Blue < 1.97) || (hue >= 90 && hue < 105 && bright > 40)) { c = "U - WHITE"; } else if (hue > 80 && hue < 135) { c = "B - GREEN"; } else if (hue > 135 && hue < 260) { c = "F - BLUE"; if (((float)rgbColor.Blue) / rgbColor.Red < 1.2f) { c = "U - WHITE"; } } else if (hue > 33 && hue < 70) { c = "D - YELLOW"; } else if (hue > 15 && hue < 30) { /*if (rgbColor.Blue >= 15 && hue > 15) * { * if (((float) rgbColor.Red)/rgbColor.Blue > 6.10f) * c = "R - ORANGE"; * else * c = "L - RED"; * } * else * c = "R - ORANGE";*/ c = "R - ORANGE"; } else if (hue <= 15) { c = "L - RED"; } c += " - " + colorStr; return(c); }
public static double ColorToBrightness(System.Drawing.Color c) { return(c.GetBrightness()); }
public static Color FromRGB(Vector3 rgb) { System.Drawing.Color systemColor = System.Drawing.Color.FromArgb((int)rgb.X, (int)rgb.Y, (int)rgb.Z); return(new Color(systemColor.GetHue(), systemColor.GetSaturation(), systemColor.GetBrightness() * 240)); }
public int Compare(object firstItem, object secondItem) { if (firstItem == null || secondItem == null) { return(-1); } ColorItem colorItem1 = ( ColorItem )firstItem; ColorItem colorItem2 = ( ColorItem )secondItem; if ((colorItem1.Color == null) || !colorItem1.Color.HasValue || (colorItem2.Color == null) || !colorItem2.Color.HasValue) { return(-1); } System.Drawing.Color drawingColor1 = System.Drawing.Color.FromArgb(colorItem1.Color.Value.A, colorItem1.Color.Value.R, colorItem1.Color.Value.G, colorItem1.Color.Value.B); System.Drawing.Color drawingColor2 = System.Drawing.Color.FromArgb(colorItem2.Color.Value.A, colorItem2.Color.Value.R, colorItem2.Color.Value.G, colorItem2.Color.Value.B); // Compare Hue double hueColor1 = Math.Round(( double )drawingColor1.GetHue(), 3); double hueColor2 = Math.Round(( double )drawingColor2.GetHue(), 3); if (hueColor1 > hueColor2) { return(1); } else if (hueColor1 < hueColor2) { return(-1); } else { // Hue is equal, compare Saturation double satColor1 = Math.Round(( double )drawingColor1.GetSaturation(), 3); double satColor2 = Math.Round(( double )drawingColor2.GetSaturation(), 3); if (satColor1 > satColor2) { return(1); } else if (satColor1 < satColor2) { return(-1); } else { // Saturation is equal, compare Brightness double brightColor1 = Math.Round(( double )drawingColor1.GetBrightness(), 3); double brightColor2 = Math.Round(( double )drawingColor2.GetBrightness(), 3); if (brightColor1 > brightColor2) { return(1); } else if (brightColor1 < brightColor2) { return(-1); } } } return(0); }
public static float GetBrightness(this Color color) { System.Drawing.Color c = System.Drawing.Color.FromArgb(color.R, color.G, color.B); return(c.GetBrightness()); }
/// <summary> /// 检查验证码图片是否能分成4个部分,如果可以就检查4个字符在特征库中是否已经存在,如果不存在, /// 就添加到特征库中,并暂时将对应的字符置为空格以待人工识别 /// </summary> public void writetodata() { bool[,] picpixel = new bool[bp.Width, bp.Height]; for (int ii = 0; ii < bp.Width; ii++) { for (int jj = 0; jj < bp.Height; jj++) { System.Drawing.Color asd = System.Drawing.Color.FromArgb(200, 200, 200); System.Drawing.Color asd1 = System.Drawing.Color.FromArgb(211, 60, 7); // bp.GetPixel(ii, jj); float asd2, asd3; asd2 = asd.GetBrightness(); asd3 = asd1.GetBrightness(); //float asd1 = asd.GetBrightness(); float asd4 = bp.GetPixel(ii, jj).GetBrightness(); if (asd4 < asd2)//bp.GetPixel(ii, jj).GetBrightness() < System.Drawing.Color.FromArgb(207, 255, 255).GetBrightness()) { bp.SetPixel(ii, jj, System.Drawing.Color.FromArgb(0, 0, 0)); //if(asd4<asd2) picpixel[ii, jj] = true; } else { bp.SetPixel(ii, jj, System.Drawing.Color.FromArgb(255, 255, 255)); picpixel[ii, jj] = false; } } } return; int[] index = new int[8]; int indexnum = 0; bool black = false; for (int ii = 0; ii < bp.Width; ii++) { bool haveblack = false; for (int jj = 0; jj < bp.Height; jj++) { if (picpixel[ii, jj]) { haveblack = true; break; } } if (haveblack && black == false) { index[indexnum] = ii; indexnum++; black = true; } if (!haveblack && black) { index[indexnum] = ii; indexnum++; black = false; } } if (indexnum < 7) { return; } if (indexnum == 7) { index[7] = 49; } //**** for (int ii = 0; ii < 4; ii++) { int x1 = index[ii * 2]; int x2 = index[ii * 2 + 1]; int y1 = 0, y2 = 19; bool mb = false; for (int jj = 0; jj < 20; jj++) { for (int kk = x1; kk < x2; kk++) { if (picpixel[kk, jj]) { mb = true; break; } } if (mb) { y1 = jj; break; } } mb = false; for (int jj = 19; jj >= 0; jj--) { for (int kk = x1; kk < x2; kk++) { if (picpixel[kk, jj]) { mb = true; break; } } if (mb) { y2 = jj; break; } } //**以上是获取有效区域的范围 for (int jj = 0; jj < 20; jj++) { this.datapic[jj] = 0; this.datapic[jj] = 0; } this.xlpic = (byte)(x2 - x1); //如果字符宽度超过16个像素就不予处理 if (xlpic > 16) { continue; } this.ylpic = (byte)(y2 - y1 + 1); int ys = -1; ushort[] addin = new ushort[] { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 }; for (int jj = y1; jj <= y2; jj++) { ys++; int xs = -1; for (int kk = x1; kk < x2; kk++) { xs++; if (picpixel[kk, jj]) { this.datapic[ys] = (ushort)(this.datapic[ys] + addin[xs]); } } } this.adddatawithnullchar(); } //**** }
public static void BgrToHsv(Image <Bgr, byte> img, Image <Bgr, byte> imgCopy) { unsafe { int x, y; MIplImage m = img.MIplImage; byte * dataPtr = (byte *)m.imageData.ToPointer(); // Pointer to the image MIplImage m2 = imgCopy.MIplImage; byte * dataPtr2 = (byte *)m2.imageData.ToPointer(); // Pointer to the image int width = img.Width; int height = img.Height; int nChan = m.nChannels; // number of channels - 3 int padding = m.widthStep - m.nChannels * m.width; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { var x0 = x; var y0 = y; int blue = (dataPtr + y * m.widthStep + x * nChan)[0]; int green = (dataPtr + y * m.widthStep + x * nChan)[1]; int red = (dataPtr + y * m.widthStep + x * nChan)[2]; System.Drawing.Color intermediate = System.Drawing.Color.FromArgb(red, green, blue); Hsv hsvPixel = new Hsv(intermediate.GetHue(), intermediate.GetSaturation(), intermediate.GetBrightness()); double r = red / 255.0; double g = green / 255.0; double b = blue / 255.0; double hue, sat, val; double cmax = Math.Max(r, b); cmax = Math.Max(cmax, g); double cmin = Math.Min(r, b); cmin = Math.Min(cmin, g); double delta = cmax - cmin; //Hue hue = hsvPixel.Hue; //Saturation if (cmax == 0) { sat = 0; } else { sat = delta / cmax; } //Value val = cmax; (dataPtr2 + y * m.widthStep + x * nChan)[0] = (byte)(Math.Round(val * 255)); (dataPtr2 + y * m.widthStep + x * nChan)[1] = (byte)(Math.Round(sat * 255)); (dataPtr2 + y * m.widthStep + x * nChan)[2] = (byte)(Math.Round(hue * 255 / 360)); } } } }
private HSLColor GetAreaColor(Area a) { HSLColor retVal = new HSLColor(0, 0, 0); ModuleView source = theNeuronArray.FindModuleByLabel("ImageZoom"); if (source == null) { return(retVal); } if (a.areaCorners.Count == 2) { if (source.GetNeuronAt((int)a.areaCorners[0].loc.X, (int)a.areaCorners[0].loc.Y) is Neuron n0) { System.Drawing.Color c2 = Utils.IntToDrawingColor(n0.LastChargeInt); retVal = new HSLColor(c2.GetHue(), c2.GetSaturation(), c2.GetBrightness()); } } else { if (source.GetNeuronAt((int)a.centroid.X, (int)a.centroid.Y) is Neuron n1) { System.Drawing.Color c2 = Utils.IntToDrawingColor(n1.LastChargeInt); retVal = new HSLColor(c2.GetHue(), c2.GetSaturation(), c2.GetBrightness()); } } return(retVal); #pragma warning disable 162 //this code works but is too slow to be useful...replace it with some OPENCV code //Get the bounds of the area List <Point> pts = new List <Point>(); foreach (var x in a.areaCorners) { if (!double.IsNaN(x.loc.X) && !double.IsNaN(x.loc.Y)) { pts.Add(x.loc); } } int minx = (int)pts.Min(x => x.X); int miny = (int)pts.Min(x => x.Y); int maxx = (int)pts.Max(x => x.X); int maxy = (int)pts.Max(x => x.Y); //get the average color within the bounds float hueTot = 0; float brightTot = 0; float satTot = 0; int pointCount = 0; for (int i = minx; i < maxx; i++) { for (int j = miny; j < maxy; j++) { if (Utils.IsPointInPolygon(pts.ToArray(), new Point(i, j))) { if (source.GetNeuronAt(i, j) is Neuron n) { System.Drawing.Color c1 = Utils.IntToDrawingColor(n.LastChargeInt); pointCount++; hueTot += c1.GetHue(); brightTot += c1.GetBrightness(); satTot += c1.GetSaturation(); } } } } hueTot /= pointCount; brightTot /= pointCount; satTot /= pointCount; retVal = new HSLColor(hueTot, satTot, brightTot); return(retVal); #pragma warning restore 162 }
public void ChangeHue(double hue) { double H, S, L; System.Drawing.Color c = System.Drawing.Color.FromArgb(ToInt32()); S = c.GetSaturation(); L = c.GetBrightness(); H = c.GetHue(); H = hue; S = 0.9; L = ((L - 0.5) * 0.5) + 0.5; if (L == 0) { R = G = B = 0; } else { if (S == 0) { R = G = B = L; } else { double temp2 = ((L <= 0.5) ? L * (1.0 + S) : L + S - (L * S)); double temp1 = 2.0 * L - temp2; double[] t3 = new double[] { H + 1.0 / 3.0, H, H - 1.0 / 3.0 }; double[] clr = new double[] { 0, 0, 0 }; for (int i = 0; i < 3; i++) { if (t3[i] < 0) { t3[i] += 1.0; } if (t3[i] > 1) { t3[i] -= 1.0; } if (6.0 * t3[i] < 1.0) { clr[i] = temp1 + (temp2 - temp1) * t3[i] * 6.0; } else if (2.0 * t3[i] < 1.0) { clr[i] = temp2; } else if (3.0 * t3[i] < 2.0) { clr[i] = (temp1 + (temp2 - temp1) * ((2.0 / 3.0) - t3[i]) * 6.0); } else { clr[i] = temp1; } } R = clr[0]; G = clr[1]; B = clr[2]; } } }
public static Vector3 ToHSV(Vector3 color) { Vector3 result; // the resultant color converted to HSV space float hue; // degrees [0, 360] float saturation; // [0, 1] float value; // [0, 1] float min, max, delta; Vector3 c; c = color * 255; System.Drawing.Color _color = System.Drawing.Color.FromArgb(255, (int)c.X, (int)c.Y, (int)c.Z); hue = _color.GetHue(); saturation = _color.GetSaturation(); value = _color.GetBrightness() * 255; return(new Vector3(hue, saturation, value)); //if (c.X == 255 && c.Y == 255 && c.Z == 255) //{ // hue = 0; // saturation = 0; // value = 100; // return new Vector3(hue, saturation, value); //} min = Min(c); max = Max(c); value = max; delta = max - min; if (max != 0) { if (delta == 0) { if (min == 255) { saturation = 0; } else { saturation = min / 255; } } else { saturation = delta / max; } } else { saturation = 0; hue = 0; value = 0; return(new Vector3(hue, saturation, value)); } if (c.X == max) // red is dominant { hue = (c.Y - c.Z) / delta; // between yellow & magenta } else if (c.Y == max) // green is dominant { hue = 2 + (c.Z - c.X) / delta; // between cyan & yellow } else // blue is dominant { hue = 4 + (c.X - c.Y) / delta; // between magenta & cyan } hue *= 60; if (hue < 0) { hue += 360; } if (float.IsNaN(hue)) { hue = 0; } result = new Vector3(hue, saturation, value); return(result); }
internal DotHsvColor(System.Drawing.Color color) { H = color.GetHue(); S = color.GetSaturation(); V = color.GetBrightness(); }