Пример #1
0
 public static Color GetContrast(this Color Source, bool PreserveOpacity)
 {
     var inputColor = Source;
       //if RGB values are close to each other by a diff less than 10%, then if RGB values are lighter side, decrease the blue by 50% (eventually it will increase in conversion below), if RBB values are on darker side, decrease yellow by about 50% (it will increase in conversion)
       var avgColorValue = (byte) ((Source.R + Source.G + Source.B)/3);
       var diff_r = Math.Abs(Source.R - avgColorValue);
       var diff_g = Math.Abs(Source.G - avgColorValue);
       var diff_b = Math.Abs(Source.B - avgColorValue);
       if (diff_r < 20 && diff_g < 20 && diff_b < 20) //The color is a shade of gray
       {
     if (avgColorValue < 123) //color is dark
     {
       inputColor = Color.FromArgb(Source.A, 220, 230, 50);
     }
     else
     {
       inputColor = Color.FromArgb(Source.A, 255, 255, 50);
     }
       }
       var sourceAlphaValue = Source.A;
       if (!PreserveOpacity)
       {
     sourceAlphaValue = Math.Max(Source.A, (byte) 127); //We don't want contrast color to be more than 50% transparent ever.
       }
       var rgb = new RGB {R = inputColor.R, G = inputColor.G, B = inputColor.B};
       var hsb = ConvertToHSB(rgb);
       hsb.H = hsb.H < 180 ? hsb.H + 180 : hsb.H - 180;
       //_hsb.B = _isColorDark ? 240 : 50; //Added to create dark on light, and light on dark
       rgb = ConvertToRGB(hsb);
       return Color.FromArgb(sourceAlphaValue, (int) rgb.R, (int) rgb.G, (int) rgb.B);
 }
Пример #2
0
        public Renderer(VariableSet variables, Drawable drawable)
            : base(variables)
        {
            _drawable = drawable;

              const double lensAngle = 70.0;
              const double earthRadius = 6375.0;
              var amplitudes = new double[]{1.0, 0.5, 0.25, 0.125, 0.0625,
                    0.03125, 0.05, 0.05, 0.04, 0.0300};

              _width = drawable.Width;
              _height = drawable.Height;

              _clouds = new Perlin3D(10, 16.0, amplitudes,
                 (int) GetValue<UInt32>("seed"));
              _cameraDistance = _width * 0.5 / Math.Tan(lensAngle * Math.PI / 180.0);

              _intSunX = (int) Math.Round((_width - 1) * GetValue<double>("sun_x"));
              _intSunY = (int) Math.Round((_height - 1) * GetValue<double>("sun_y"));

              _horizonColor2 = FromScreen("horizon_color");
              _skyColor2 = FromScreen("sky_color");
              _sunColor2 = FromScreen("sun_color");
              _cloudColor2 = FromScreen("cloud_color");
              _shadowColor2 = FromScreen("shadow_color");

              var tilt = new TMatrix(GetValue<double>("tilt"), 1);
              var rotation = new TMatrix(GetValue<double>("rotation"), 2);
              _transform = TMatrix.Combine(tilt, rotation);
              _cameraLocation = new Vector3(0.0, earthRadius + 0.2, 0.0);
        }
Пример #3
0
 /*
  * Check whether the color of the object this script is attached to is
  * compatible with the passed in color. Compatible colors are those that
  * either match or match one of the component colors in the color wheel.
  */
 public bool isCompatible(RGB theirRGB)
 {
     if (theirRGB.color == color) {
         return true;
     }
     return false;
 }
Пример #4
0
 public static RGB GetRGB(this Color self)
 {
     RGB rgb = new RGB();
     rgb.r = self.r;
     rgb.g = self.g;
     rgb.b = self.b;
     return rgb;
 }
Пример #5
0
        public static Color HSVtoColor(HSV hsv)
        {
            if (hsv == null)
                return Color.Blue;

            DRColor.RGB RGB = new RGB(hsv);
            return Color.FromArgb(RGB.Red, RGB.Green, RGB.Blue);
        }
Пример #6
0
        public void GetBufferFrames()
        {
            FileBuffer.Seek(0, SeekOrigin.Begin);
            BinaryFormatter mFormatter = new BinaryFormatter(FileBuffer);
            FlcHeader.ReadData(mFormatter);
            Civ3Header.ReadData(mFormatter);

            SFliFrameHeader frameHeader = new SFliFrameHeader();
            SFliChunkHeader chunkHeader = new SFliChunkHeader();

            mBufferFrames = new byte[FlcHeader.frames + 8][];
            mColourMap = new RGB[FlcHeader.frames + 8][];

            for (short frame = 0; frame < FlcHeader.frames + 8; frame++) {

                mBufferFrames[frame] = new byte[FlcHeader.width * FlcHeader.height];
                mColourMap[frame] = new RGB[256];

                if (frame > 0) {
                    Array.Copy(mBufferFrames[frame - 1], mBufferFrames[frame], sizeof(byte) * (FlcHeader.width * FlcHeader.height));
                    Array.Copy(mColourMap[frame - 1], mColourMap[frame], 256);
                }

                frameHeader.ReadData(mFormatter);

                if (frameHeader.magic != 0xf1fa) {
                    //fseek(fp, frameHeader.Size - sizeof(frameHeader), SEEK_CUR);

                    ulong size = (ulong)System.Runtime.InteropServices.Marshal.SizeOf(typeof(SFliFrameHeader));
                    mFormatter.ReadBytes((int)(frameHeader.size - size));

                    FlcHeader.frames--;
                    frame--;
                    continue;
                }

                for (int chunk = 0; chunk < frameHeader.chunks; chunk++) {
                    chunkHeader.ReadData(mFormatter);

                    switch (chunkHeader.type) {
                        case 4:
                            FlcColour256(mFormatter, frame);
                            break;
                        case 7:
                            long read = FlcDeltaFlc(mFormatter, frame);
                            mFormatter.ReadBytes((int)((long)chunkHeader.size - read));
                            break;
                        case 15:
                            FlcBitwiseRun(mFormatter, frame);
                            break;
                        default:
                            throw new NotImplementedException();

                    }
                }

            }
        }
Пример #7
0
        /// <summary>
        /// transformation HSV -> RGB
        /// source: http://en.wikipedia.org/wiki/HSL_and_HSV (consistent with anything found on the web)
        /// </summary>
        /// <author>Birthe Anne Wiegand</author>
        /// <returns>the RGB value</returns>
        public RGB asRGB()
        {
            RGB temp = new RGB();

            float f = this.H / 60f - (float)Math.Floor(this.H / 60f);
            float p = this.V * (1f - this.S);
            float q = this.V * (1f - this.S * f);
            float t = this.V * (1f - this.S * (1 - f));

            if (0f <= this.H && this.H < 60f)
            {
                temp.R = this.V;
                temp.G = t;
                temp.B = p;
            }
            else if (60f <= this.H && this.H < 120f)
            {
                temp.R = q;
                temp.G = this.V;
                temp.B = p;
            }
            else if (120f <= this.H && this.H < 180f)
            {
                temp.R = p;
                temp.G = this.V;
                temp.B = t;
            }
            else if (180f <= this.H && this.H < 240f)
            {
                temp.R = p;
                temp.G = q;
                temp.B = this.V;
            }
            else if (240f <= this.H && this.H < 300f)
            {
                temp.R = t;
                temp.G = p;
                temp.B = this.V;
            }
            else if (300f <= this.H && this.H < 360f)
            {
                temp.R = this.V;
                temp.G = p;
                temp.B = q;
            }
            else
            {
                System.Diagnostics.Debug.Write("HSV to RGB out of range");
            }

            return temp;
        }
Пример #8
0
        public void setPalette(int colorCount, bool save = false)
        {
            unsafe
            {
                Clear();

                for (int y = 0; y < Buffer.heightInPixels; y++)
                {
                    byte* currentLine = Buffer.ptrFirstPixel + (y * Buffer.stride);
                    for (int x = 0; x < Buffer.widthInBytes; x = x + Buffer.bytesPerPixel)
                    {
                        colorList.Add(new RGB(Buffer.memoryStream[y, x + 2], Buffer.memoryStream[y, x + 1], Buffer.memoryStream[y, x]));
                    }
                }

                List<RGB> palette = GetPalette(colorCount);
                int k = 0;
                for (int y = 0; y < Buffer.heightInPixels; y++)
                {
                    byte* currentLine = Buffer.ptrFirstPixel + (y * Buffer.stride);
                    for (int x = 0; x < Buffer.widthInBytes; x = x + Buffer.bytesPerPixel)
                    {

                        RGB color = new RGB(Buffer.memoryStream[y,x + 2], Buffer.memoryStream[y,x + 1], Buffer.memoryStream[y,x]);
                        
                        Int32 b;
                        if (!cache.TryGetValue(color, out b))
                        {
                            for (int i = 0; i < cubeList.Count; i++)
                            {
                                if (cubeList[i].IsColorIn(color))
                                {
                                    b = cubeList[i].PaletteIndex;
                                    break;
                                }
                            }
                        }

                        currentLine[x + 2] = palette[b].R;
                        currentLine[x + 1] = palette[b].G;
                        currentLine[x] = palette[b].B;
                    }
                }
                if (save)
                    Buffer.addData();
                Buffer.Refrash();

            }
        }
Пример #9
0
        Pixel DoSwirlies(int x, int y)
        {
            var rgb = new RGB(0.0, 0.0, 0.0);

              const double zoom = 0.5;
              const int terms = 5;

              _swirlies.ForEach(swirly =>
            swirly.CalculateOnePoint(terms, _width, _height, zoom,
                         x, y, rgb));

              return new Pixel(FloatToIntPixel(RemapColorRange(rgb.R)),
               FloatToIntPixel(RemapColorRange(rgb.G)),
               FloatToIntPixel(RemapColorRange(rgb.B)));
        }
Пример #10
0
        public void UnionTest()
        {
            // Byte is a value type, and will default to 0,
            // so the default colour will be black!
            var black = new RGB();
            Assert.AreEqual(black.AsHex(), "000000");

            var coral = new RGB(255, 125, 125);
            Assert.AreEqual(coral.AsHex(), "FF7D7D");

            var coralConverted = new RGB().FromHex("FF7D7D");
            Assert.AreEqual(coralConverted.R, 255);
            Assert.AreEqual(coralConverted.G, 125);
            Assert.AreEqual(coralConverted.B, 125);
        }
Пример #11
0
        public static byte[] CombineColorChannels(RGB[] rgb)
        {
            byte[] data = new byte[rgb.Length * 3];

            int counter = 0;
            for (int i = 0; i < data.Length; i += 3)
            {
                data[i] = rgb[counter].r;
                data[i + 1] = rgb[counter].g;
                data[i + 2] = rgb[counter].b;

                ++counter;
            }

            return data;
        }
Пример #12
0
        protected override Image Load()
        {
            if (ReadHeader())
            {
              var colormap = new RGB[] {
            new RGB(255,255,255),
            new RGB(255,0,0),
            new RGB(0,255,0),
            new RGB(255,255,0),
            new RGB(0,0,255),
            new RGB(255,0,255),
            new RGB(0,255,255),
            new RGB(181,181,181),
            new RGB(84,84,84),
            new RGB(127,0,0),
            new RGB(0,127,0),
            new RGB(127,127,0),
            new RGB(0,0,127),
            new RGB(127,0,127),
            new RGB(0,127,127),
            new RGB(0,0,0)
              };

              var image = NewImage(_imageWidth, _imageHeight,
                   ImageBaseType.Indexed,
                   ImageType.Indexed, Filename);
              image.Colormap = colormap;
              var rgn = new PixelRgn(image.Layers[0], true, false);

              int bparrow = (_imageWidth + 7) / 8;

              for (int y = 0; y < _imageHeight; )
            {
              // byte[] line = new byte[bparrow * 8];
              var line = new byte[_imageWidth];
              int count = ReadLine(line);
              do
            {
              rgn.SetRow(line, 0, y++);
            }
              while (--count > 0);
            }

              return image;
            }
              return null;
        }
Пример #13
0
        public FxImages_32bppArgb(Bitmap Image)
        {
            if (Image.PixelFormat != PixelFormat.Format32bppArgb)
            {
                throw new ArgumentException("The input image must 32bppArgb");
            }

            // set the pilex format
            FXPixelFormat = new RGB[4];
            FXPixelFormat[0] = RGB.B;
            FXPixelFormat[1] = RGB.G;
            FXPixelFormat[2] = RGB.R;
            FXPixelFormat[3] = RGB.A;

            // set the internal image
            localImage = Image;
        }
Пример #14
0
        internal static HSB ConvertToHSB(RGB rgb)
        {
            // Following code is taken as it is from MSDN. See link below.
              // By: <a href="http://blogs.msdn.com/b/codefx/archive/2012/02/09/create-a-color-picker-for-windows-phone.aspx" title="MSDN" target="_blank">Yi-Lun Luo</a>
              var r = rgb.R;
              var g = rgb.G;
              var b = rgb.B;

              var max = Max(r, g, b);
              var min = Min(r, g, b);
              var chroma = max - min;
              var hue2 = 0d;
              if (chroma != 0)
              {
            if (max == r)
            {
              hue2 = (g - b)/chroma;
            }
            else if (max == g)
            {
              hue2 = (b - r)/chroma + 2;
            }
            else
            {
              hue2 = (r - g)/chroma + 4;
            }
              }
              var hue = hue2*60;
              if (hue < 0)
              {
            hue += 360;
              }
              var brightness = max;
              double saturation = 0;
              if (chroma != 0)
              {
            saturation = chroma/brightness;
              }
              return new HSB
              {
            H = hue,
            S = saturation,
            B = brightness
              };
        }
Пример #15
0
 /*
  * Gets the material that is associated with the specified RGB's color
  */
 public static Material GetMaterialForRGB( RGB rgb)
 {
     Material returnMaterial = null;
     switch (rgb.color) {
     case ColorWheel.red:
         returnMaterial = ColorManager.Instance.red;
         break;
     case ColorWheel.green:
         returnMaterial = ColorManager.Instance.green;
         break;
     case ColorWheel.blue:
         returnMaterial = ColorManager.Instance.blue;
         break;
     case ColorWheel.black:
         returnMaterial = ColorManager.Instance.black;
         break;
     }
     return returnMaterial;
 }
Пример #16
0
        /// <summary>
        /// interpolate the input image in the specific position 
        /// and specific color, return byte
        /// </summary>
        /// <param name="image"></param>
        /// <param name="xf"></param>
        /// <param name="yf"></param>
        /// <param name="color"></param>
        /// <returns></returns>
        public static byte Bilinear(FxImages image, float xf, float yf, RGB color)
        {
            if (yf + 1>= image.Image.Height)
                yf = image.Image.Height - 2;

            if (xf + 1 >= image.Image.Width)
                xf = image.Image.Width - 2;

            // get the integer part of the position
            int x = (int)Math.Floor(xf);
            int y = (int)Math.Floor(yf);

            // get the ratio part
            double x_ratio = xf - x;
            double y_ratio = yf - y;

            // the inverse ratio
            double x_opposite = 1 - x_ratio;
            double y_opposite = 1 - y_ratio;

            byte result = 0;

            // interpolate on x
            if (y_opposite > 0)
            {
                if (x_opposite > 0)
                    result += (byte)(image[x, y, color] * x_opposite * y_opposite);

                if (x_ratio > 0)
                    result += (byte)(image[x + 1, y, color] * x_ratio * y_opposite);
            }

            // interpolate on y
            if (y_ratio > 0)
            {
                if (x_opposite > 0)
                    result += (byte)(image[x, y + 1, color] * x_opposite * y_ratio);

                if (x_ratio > 0)
                    result += (byte)(image[x + 1, y + 1, color] * x_ratio * y_ratio);
            }
            return result;
        }
Пример #17
0
        public FxImages_8bpp(Bitmap Image)
        {
            if (Image.PixelFormat != PixelFormat.Format8bppIndexed)
            {
                throw new ArgumentException("The input image must be 8 Bit per pixel");
            }

            // set the pilex format
            FXPixelFormat = new RGB[1];
            FXPixelFormat[0] = RGB.B;

            // set the internal image
            localImage = Image;

            /// make the grayscale palette
            ColorPalette greyPal = Image.Palette;
            for (int i = 0; i < greyPal.Entries.Length; i++)
                greyPal.Entries[i] = Color.FromArgb(i, i, i);
            Image.Palette = greyPal;
        }
Пример #18
0
        public Form1()
        {
            InitializeComponent();

            this.numericUpDown1.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.bindingSource1, "R", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
            this.numericUpDown2.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.bindingSource1, "G", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
            this.numericUpDown3.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.bindingSource1, "B", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));

            this.trackBar1.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.bindingSource1, "R", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
            this.trackBar2.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.bindingSource1, "G", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
            this.trackBar3.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.bindingSource1, "B", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));

            RGB rgb1 = new RGB();
            rgb1.R = 100;
            rgb1.G = 200;
            rgb1.B = 50;
            this.bindingSource1.DataSource = rgb1;

            ((RGB)(this.bindingSource1.DataSource)).R = 5;
            ((RGB)(this.bindingSource1.DataSource)).G = 205;
            ((RGB)(this.bindingSource1.DataSource)).B = 55;
        }
Пример #19
0
        /// <summary>
        /// Render all UI.
        /// </summary>
        private void InitializeUI()
        {
            if (PanelEntity.Attributes.ContainsKey("friendly_name"))
            {
                TextBlock textBlock = FindName("DeviceText") as TextBlock;
                textBlock.Text = PanelEntity.Name().ToUpper();
            }

            // For the group panel, average the color of children entities together
            if (ChildrenEntities != null)
            {
                // Set the color adjustment sliders and color wheel by blending the average
                // color for each. Include entities which are in the On state only.
                IEnumerable <Entity> onEntities = ChildrenEntities.Where(x => string.Equals(x.State, "on", StringComparison.InvariantCultureIgnoreCase));

                if (onEntities.Any())
                {
                    // Average the brightness
                    IEnumerable <Entity> brightnessEntities = onEntities.Where(x => x.Attributes.ContainsKey("brightness"));
                    if (brightnessEntities.Any())
                    {
                        double averageBrightness = onEntities.Select(x => Convert.ToDouble(x.Attributes["brightness"])).Cast <double>().Average();
                        UpdateBrightnessControl(averageBrightness);
                    }
                    else
                    {
                        Ellipse ellipse = this.FindName("BrightnessCircle") as Ellipse;
                        ellipse.Visibility = Visibility.Collapsed;
                    }

                    // Average the color temperature
                    IEnumerable <Entity> colorTempEntities = onEntities.Where(x => x.Attributes.ContainsKey("color_temp"));
                    if (colorTempEntities.Any())
                    {
                        double averageColorTemperature = colorTempEntities.Select(x => Convert.ToDouble(x.Attributes["color_temp"])).Cast <double>().Average();

                        UpdateColorTemperatureControl(Convert.ToInt32(averageColorTemperature));

                        ShowColorTemperatureCircle(Visibility.Visible);
                    }
                    else
                    {
                        ShowColorTemperatureCircle(Visibility.Collapsed);
                    }

                    // Average the color
                    IEnumerable <Entity> rgbEntities = onEntities.Where(x => x.Attributes.ContainsKey("rgb_color"));
                    if (rgbEntities.Any())
                    {
                        RGB averageColor = RGB.Average(rgbEntities.Select(x => new RGB(
                                                                              Convert.ToByte(x.Attributes["rgb_color"][0]),
                                                                              Convert.ToByte(x.Attributes["rgb_color"][1]),
                                                                              Convert.ToByte(x.Attributes["rgb_color"][2]))).Cast <RGB>());

                        SetColorWheelLocation(averageColor);

                        ShowColorWheelCircle(Visibility.Visible);
                    }
                    else
                    {
                        ShowColorWheelCircle(Visibility.Collapsed);
                    }
                }
                else
                {
                    UpdateBrightnessControl(0.0);

                    ShowColorTemperatureCircle(Visibility.Collapsed);
                    ShowColorWheelCircle(Visibility.Collapsed);
                }
            }
            else
            {
                if (string.Equals(PanelEntity.State, "on", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (PanelEntity.Attributes.ContainsKey("brightness"))
                    {
                        UpdateBrightnessControl(Convert.ToDouble(PanelEntity.Attributes["brightness"]));
                    }
                    else
                    {
                        Ellipse ellipse = this.FindName("BrightnessCircle") as Ellipse;
                        ellipse.Visibility = Visibility.Collapsed;
                    }

                    if (PanelEntity.Attributes.ContainsKey("color_temp"))
                    {
                        UpdateColorTemperatureControl(Convert.ToInt32(PanelEntity.Attributes["color_temp"]));

                        ShowColorTemperatureCircle(Visibility.Visible);
                    }
                    else
                    {
                        ShowColorTemperatureCircle(Visibility.Collapsed);
                    }

                    if (PanelEntity.Attributes.ContainsKey("rgb_color"))
                    {
                        Newtonsoft.Json.Linq.JArray rgbColors = PanelEntity.Attributes["rgb_color"];

                        RGB rgb = new RGB()
                        {
                            R = Convert.ToByte(rgbColors[0]),
                            G = Convert.ToByte(rgbColors[1]),
                            B = Convert.ToByte(rgbColors[2]),
                        };

                        SetColorWheelLocation(rgb);

                        ShowColorWheelCircle(Visibility.Visible);
                    }
                    else
                    {
                        ShowColorWheelCircle(Visibility.Collapsed);
                    }
                }
                else
                {
                    UpdateBrightnessControl(0.0);

                    ShowColorTemperatureCircle(Visibility.Collapsed);
                    ShowColorWheelCircle(Visibility.Collapsed);
                }
            }

            // ColorTemperature should be a constant yellowish-hue line for brightness-only lights
            if (!PanelEntity.HasSupportedFeatures((uint)LightPlatformSupportedFeatures.ColorTemperature, ChildrenEntities))
            {
                Rectangle colorTemperature = this.FindName("ColorTemperature") as Rectangle;
                colorTemperature.Fill = new SolidColorBrush(Colors.LightYellow);
            }

            // Update the power button last so as to render with any color updates
            ShowHightlightColor(ButtonState.NotPressed);
        }
Пример #20
0
        /// <summary>
        ///   Image histogram back-projection.
        /// </summary>
        ///
        private unsafe void generateBackprojectionMap(UnmanagedImage frame, float[] ratioHistogram)
        {
            int width     = frame.Width;
            int height    = frame.Height;
            int stride    = frame.Stride;
            int pixelSize = Bitmap.GetPixelFormatSize(frame.PixelFormat) / 8;
            int offset    = stride - width * pixelSize;

            fixed(float *map_ptr = map)
            {
                byte * src = (byte *)frame.ImageData.ToPointer();
                float *dst = map_ptr;

                if (mode == CamshiftMode.HSL)
                {
                    // Process as HSL
                    HSL hsl = new HSL();
                    RGB rgb = new RGB();

                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++, src += pixelSize, dst++)
                        {
                            // RGB
                            rgb.Red   = (*(src + RGB.R));
                            rgb.Green = (*(src + RGB.G));
                            rgb.Blue  = (*(src + RGB.B));

                            // Transform into HSL
                            AForge.Imaging.HSL.FromRGB(rgb, hsl);

                            if ((hsl.Saturation >= hslSaturation.Min) && (hsl.Saturation <= hslSaturation.Max) &&
                                (hsl.Luminance >= hslLuminance.Min) && (hsl.Luminance <= hslLuminance.Max))
                            {
                                *dst = ratioHistogram[hsl.Hue];
                            }
                            else
                            {
                                *dst = 0;
                            }
                        }
                        src += offset;
                    }
                }
                else if (mode == CamshiftMode.Mixed)
                {
                    // Process in mixed mode
                    HSL hsl = new HSL();
                    RGB rgb = new RGB();

                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++, src += pixelSize, dst++)
                        {
                            // RGB
                            rgb.Red   = (*(src + RGB.R));
                            rgb.Green = (*(src + RGB.G));
                            rgb.Blue  = (*(src + RGB.B));

                            // Transform into HSL
                            AForge.Imaging.HSL.FromRGB(rgb, hsl);

                            if ((hsl.Saturation >= hslSaturation.Min) && (hsl.Saturation <= hslSaturation.Max) &&
                                (hsl.Luminance >= hslLuminance.Min) && (hsl.Luminance <= hslLuminance.Max))
                            {
                                *dst = ratioHistogram[(int)(hsl.Hue * 10 + hsl.Saturation * 100 + hsl.Luminance * 10)];
                            }
                            else
                            {
                                *dst = 0;
                            }
                        }
                        src += offset;
                    }
                }
                else
                {
                    // Process as RGB
                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++, src += pixelSize, dst++)
                        {
                            // RGB
                            int r   = (int)(*(src + RGB.R)) >> 4;
                            int g   = (int)(*(src + RGB.G)) >> 4;
                            int b   = (int)(*(src + RGB.B)) >> 4;
                            *   dst = ratioHistogram[256 * r + 16 * g + b];
                        }
                        src += offset;
                    }
                }
            }
        }
Пример #21
0
 public FillStyle(RGB SolidFillColor)
 {
     this._SolidColor = SolidFillColor;
     this._Type       = FillStyleType.Solid;
 }
Пример #22
0
 public SetLevelData()
 {
     level = 1;
     color = Color.White;
 }
Пример #23
0
    public static UInt32[,] matrix_filtration(int W, int H, UInt32[,] pixel, int N, double[,] matryx)
    {
        int i, j, k, m, gap = (int)(N / 2);
        int tmpH = H + 2 * gap, tmpW = W + 2 * gap;

        UInt32[,] tmppixel = new UInt32[tmpH, tmpW];
        UInt32[,] newpixel = new UInt32[H, W];
        //заполнение временного расширенного изображения
        //углы
        for (i = 0; i < gap; i++)
        {
            for (j = 0; j < gap; j++)
            {
                tmppixel[i, j]                       = pixel[0, 0];
                tmppixel[i, tmpW - 1 - j]            = pixel[0, W - 1];
                tmppixel[tmpH - 1 - i, j]            = pixel[H - 1, 0];
                tmppixel[tmpH - 1 - i, tmpW - 1 - j] = pixel[H - 1, W - 1];
            }
        }
        //крайние левая и правая стороны
        for (i = gap; i < tmpH - gap; i++)
        {
            for (j = 0; j < gap; j++)
            {
                tmppixel[i, j]            = pixel[i - gap, j];
                tmppixel[i, tmpW - 1 - j] = pixel[i - gap, W - 1 - j];
            }
        }
        //крайние верхняя и нижняя стороны
        for (i = 0; i < gap; i++)
        {
            for (j = gap; j < tmpW - gap; j++)
            {
                tmppixel[i, j]            = pixel[i, j - gap];
                tmppixel[tmpH - 1 - i, j] = pixel[H - 1 - i, j - gap];
            }
        }
        //центр
        for (i = 0; i < H; i++)
        {
            for (j = 0; j < W; j++)
            {
                tmppixel[i + gap, j + gap] = pixel[i, j];
            }
        }
        //применение ядра свертки
        RGB ColorOfPixel = new RGB();
        RGB ColorOfCell  = new RGB();

        for (i = gap; i < tmpH - gap; i++)
        {
            for (j = gap; j < tmpW - gap; j++)
            {
                ColorOfPixel.R = 0;
                ColorOfPixel.G = 0;
                ColorOfPixel.B = 0;
                for (k = 0; k < N; k++)
                {
                    for (m = 0; m < N; m++)
                    {
                        ColorOfCell     = calculationOfColor(tmppixel[i - gap + k, j - gap + m], matryx[k, m]);
                        ColorOfPixel.R += ColorOfCell.R;
                        ColorOfPixel.G += ColorOfCell.G;
                        ColorOfPixel.B += ColorOfCell.B;
                    }
                }
                //контролируем переполнение переменных
                if (ColorOfPixel.R < 0)
                {
                    ColorOfPixel.R = 0;
                }
                if (ColorOfPixel.R > 255)
                {
                    ColorOfPixel.R = 255;
                }
                if (ColorOfPixel.G < 0)
                {
                    ColorOfPixel.G = 0;
                }
                if (ColorOfPixel.G > 255)
                {
                    ColorOfPixel.G = 255;
                }
                if (ColorOfPixel.B < 0)
                {
                    ColorOfPixel.B = 0;
                }
                if (ColorOfPixel.B > 255)
                {
                    ColorOfPixel.B = 255;
                }

                newpixel[i - gap, j - gap] = build(ColorOfPixel);
            }
        }

        return(newpixel);
    }
Пример #24
0
 public void UpdateRGB()
 {
     RGB.FromCMYK(CMYK);
     OnPropertyChanged("RGB");
 }
Пример #25
0
 void set_color(int index, RGB entry)
 {
     palette[index] = new Color(entry.r, entry.g, entry.b).PackedValue;
 }
Пример #26
0
 public RGB(int APIversion, EventHandler handler, RGB basis) : base(APIversion, handler, basis.X, basis.Y, basis.Z)
 {
 }
Пример #27
0
 public CustomData(float _editorOffset, float _editorOldOffset, string _difficultyLabel, RGB _colorLeft, RGB _colorRight, RGB _envColorLeft, RGB _envColorRight
                   , RGB _envColorLeftBoost, RGB _envColorRightBoost, RGB _obstacleColor)
 {
     this._editorOffset    = _editorOffset;
     this._editorOldOffset = _editorOldOffset;
     if (_difficultyLabel == null)
     {
         _difficultyLabel = "ExpertPlus";
     }
     this._difficultyLabel = _difficultyLabel;
     if (_colorLeft == null)
     {
         _colorLeft = new(0.7529412f, 0.1882353f, 0.1882353f);
     }
     this._colorLeft = _colorLeft;
     if (_colorRight == null)
     {
         _colorRight = new(0.1254902f, 0.3921569f, 0.6588235f);
     }
     this._colorRight = _colorRight;
     if (_envColorLeft == null)
     {
         _envColorLeft = new(0.7529412f, 0.1882353f, 0.1882353f);
     }
     this._envColorLeft = _envColorLeft;
     if (_envColorRight == null)
     {
         _envColorRight = new(0.1254902f, 0.3921569f, 0.6588235f);
     }
     this._envColorRight = _envColorRight;
     if (_envColorLeftBoost == null)
     {
         _envColorLeftBoost = new(0.8f, 0.9098f, 0.8f);
     }
     this._envColorLeftBoost = _envColorLeftBoost;
     if (_envColorRightBoost == null)
     {
         _envColorRightBoost = new(0.89019f, 0.396078f, 0.756862f);
     }
     this._envColorRightBoost = _envColorRightBoost;
     if (_obstacleColor == null)
     {
         _obstacleColor = new(1, 0, 0);
     }
     this._obstacleColor = _obstacleColor;
 }
Пример #28
0
 /// <summary>
 /// Sets the color (attribute value) of a RGB LED endpoint using a RGBW value.
 /// </summary>
 /// <param name="uuid">The attribute uuid.</param>
 /// <param name="color">The color value.</param>
 /// <returns>True if successful.</returns>
 public async Task <bool> SetColorAsync(Guid uuid, RGB color) =>
 await SetColorAsync(uuid, ColorData.Rgb2Hex(color));
Пример #29
0
        protected unsafe override void ProcessFilter(UnmanagedImage image, Rectangle rect)
        {
            int   num   = System.Drawing.Image.GetPixelFormatSize(image.PixelFormat) / 8;
            int   left  = rect.Left;
            int   top   = rect.Top;
            int   num2  = left + rect.Width;
            int   num3  = top + rect.Height;
            int   num4  = image.Stride - rect.Width * num;
            RGB   rGB   = new RGB();
            YCbCr yCbCr = new YCbCr();
            float num5  = 0f;
            float num6  = 0f;
            float num7  = 0f;
            float num8  = 0f;
            float num9  = 0f;
            float num10 = 0f;

            if (inY.Max != inY.Min)
            {
                num5 = (outY.Max - outY.Min) / (inY.Max - inY.Min);
                num6 = outY.Min - num5 * inY.Min;
            }
            if (inCb.Max != inCb.Min)
            {
                num7 = (outCb.Max - outCb.Min) / (inCb.Max - inCb.Min);
                num8 = outCb.Min - num7 * inCb.Min;
            }
            if (inCr.Max != inCr.Min)
            {
                num9  = (outCr.Max - outCr.Min) / (inCr.Max - inCr.Min);
                num10 = outCr.Min - num9 * inCr.Min;
            }
            byte *ptr = (byte *)image.ImageData.ToPointer();

            ptr += top * image.Stride + left * num;
            for (int i = top; i < num3; i++)
            {
                int num11 = left;
                while (num11 < num2)
                {
                    rGB.Red   = ptr[2];
                    rGB.Green = ptr[1];
                    rGB.Blue  = *ptr;
                    YCbCr.FromRGB(rGB, yCbCr);
                    if (yCbCr.Y >= inY.Max)
                    {
                        yCbCr.Y = outY.Max;
                    }
                    else if (yCbCr.Y <= inY.Min)
                    {
                        yCbCr.Y = outY.Min;
                    }
                    else
                    {
                        yCbCr.Y = num5 * yCbCr.Y + num6;
                    }
                    if (yCbCr.Cb >= inCb.Max)
                    {
                        yCbCr.Cb = outCb.Max;
                    }
                    else if (yCbCr.Cb <= inCb.Min)
                    {
                        yCbCr.Cb = outCb.Min;
                    }
                    else
                    {
                        yCbCr.Cb = num7 * yCbCr.Cb + num8;
                    }
                    if (yCbCr.Cr >= inCr.Max)
                    {
                        yCbCr.Cr = outCr.Max;
                    }
                    else if (yCbCr.Cr <= inCr.Min)
                    {
                        yCbCr.Cr = outCr.Min;
                    }
                    else
                    {
                        yCbCr.Cr = num9 * yCbCr.Cr + num10;
                    }
                    YCbCr.ToRGB(yCbCr, rGB);
                    ptr[2] = rGB.Red;
                    ptr[1] = rGB.Green;
                    *ptr = rGB.Blue;
                    num11++;
                    ptr += num;
                }
                ptr += num4;
            }
        }
Пример #30
0
        private void tbValue_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (!(sender is TextBox))
            {
                return;
            }
            if (e.KeyCode == Keys.Return)
            {
                UpdatetbValue(null);
                e.Handled = true;
                return;
            }
            double value;

            if (!double.TryParse(((TextBox)sender).Text,
                                 System.Globalization.NumberStyles.Integer,
                                 null, out value))
            {
                return;
            }
            #region hsv  textboxes
            if (sender == tbHSV_H)
            {
                HSV chsv = HSV.FromRGB(_color.ToRGB());
                chsv.H = value / 360.0;
                _color = XYZ.FromRGB(chsv.ToRGB());
            }
            else if (sender == tbHSV_S)
            {
                HSV chsv = HSV.FromRGB(_color.ToRGB());
                chsv.S = value / 100.0;
                _color = XYZ.FromRGB(chsv.ToRGB());
            }
            else if (sender == tbHSV_V)
            {
                HSV chsv = HSV.FromRGB(_color.ToRGB());
                chsv.V = value / 100.0;
                _color = XYZ.FromRGB(chsv.ToRGB());
            }
            #endregion
            #region secondary textboxes
            else if (_mode == Mode.HSV_RGB)
            {
                RGB crgb = _color.ToRGB();
                if (sender == tbSecond_1)
                {
                    crgb.R = value / 255.0;
                }
                else if (sender == tbSecond_2)
                {
                    crgb.G = value / 255.0;
                }
                else                 //sender==tbSecond_3
                {
                    crgb.B = value / 255.0;
                }
                _color = XYZ.FromRGB(crgb);
            }
            else if (_mode == Mode.HSV_LAB)
            {
                LAB clab = LAB.FromXYZ(_color);
                if (sender == tbSecond_1)
                {
                    clab.L = value;
                }
                else if (sender == tbSecond_2)
                {
                    clab.a = value;
                }
                else                 //sender==tbSecond_3
                {
                    clab.b = value;
                }
                _color = clab.ToXYZ();
            }
            #endregion
            //update ui
            _module.XYZ       = _color;
            lblColorOut.Color = _color.ToRGB();
            UpdatetbValue((TextBox)sender);
        }
Пример #31
0
        // Paint control
        protected override void OnPaint(PaintEventArgs pe)
        {
            Graphics  g  = pe.Graphics;
            Rectangle rc = this.ClientRectangle;
            Rectangle rcPie;
            Brush     brush;
            RGB       rgb = new RGB( );
            HSL       hsl = new HSL( );

            // get pie rectangle
            rcPie = new Rectangle(4, 4, Math.Min(rc.Right, rc.Bottom) - 8, Math.Min(rc.Right, rc.Bottom) - 8);

            // init HSL value
            hsl.Luminance  = 0.5;
            hsl.Saturation = 1.0;

            if (type == HuePickerType.Value)
            {
                // draw HSL pie
                for (int i = 0; i < 360; i++)
                {
                    hsl.Hue = i;
                    // convert from HSL to RGB
                    AForge.Imaging.HSL.ToRGB(hsl, rgb);
                    // create brush
                    brush = new SolidBrush(rgb.Color);
                    // draw one hue value
                    g.FillPie(brush, rcPie, -i, -1);

                    brush.Dispose( );
                }
            }
            else
            {
                // draw HSL pie
                for (int i = 0; i < 360; i++)
                {
                    if (
                        ((min < max) && (i >= min) && (i <= max)) ||
                        ((min > max) && ((i >= min) || (i <= max))))
                    {
                        hsl.Hue = i;
                        // convert from HSL to RGB
                        AForge.Imaging.HSL.ToRGB(hsl, rgb);
                        // create brush
                        brush = new SolidBrush(rgb.Color);
                    }
                    else
                    {
                        brush = new SolidBrush(Color.FromArgb(128, 128, 128));
                    }

                    // draw one hue value
                    g.FillPie(brush, rcPie, -i, -1);

                    brush.Dispose( );
                }
            }

            //
            double halfWidth = (double)rcPie.Width / 2;
            double angleRad  = -min * Math.PI / 180;
            double angleCos  = Math.Cos(angleRad);
            double angleSin  = Math.Sin(angleRad);

            double x = halfWidth * angleCos;
            double y = halfWidth * angleSin;

            ptCenter.X = rcPie.Left + (int)(halfWidth);
            ptCenter.Y = rcPie.Top + (int)(halfWidth);
            ptMin.X    = rcPie.Left + (int)(halfWidth + x);
            ptMin.Y    = rcPie.Top + (int)(halfWidth + y);

            // draw MIN pointer
            g.FillEllipse(blackBrush,
                          rcPie.Left + (int)(halfWidth + x) - 4,
                          rcPie.Top + (int)(halfWidth + y) - 4,
                          8, 8);
            g.DrawLine(blackPen, ptCenter, ptMin);

            // check picker type
            if (type == HuePickerType.Region)
            {
                angleRad = -max * Math.PI / 180;
                angleCos = Math.Cos(angleRad);
                angleSin = Math.Sin(angleRad);

                x = halfWidth * angleCos;
                y = halfWidth * angleSin;

                ptMax.X = rcPie.Left + (int)(halfWidth + x);
                ptMax.Y = rcPie.Top + (int)(halfWidth + y);

                // draw MAX pointer
                g.FillEllipse(whiteBrush,
                              rcPie.Left + (int)(halfWidth + x) - 4,
                              rcPie.Top + (int)(halfWidth + y) - 4,
                              8, 8);
                g.DrawLine(whitePen, ptCenter, ptMax);
            }

            base.OnPaint(pe);
        }
Пример #32
0
 public SolidLightSource(RGB rgb)
 {
     this.rgb = rgb;
 }
Пример #33
0
 /*
  * Map our player's power bars to the color passed in by returning
  * the power associated with the provided color.
  */
 Power GetPowerForColor(RGB rgb)
 {
     ColorWheel color = rgb.color;
     Power returnPower = null;
     switch (color) {
     case ColorWheel.blue:
         returnPower = bluePower;
         break;
     case ColorWheel.red:
         returnPower = redPower;
         break;
     case ColorWheel.green:
         returnPower = greenPower;
         break;
     }
     return returnPower;
 }
 public MapColorEntryWithOsmGuid([NotNull] string osmGuid, [NotNull] RGB desiredColor, [CanBeNull] string text)
 {
     OsmGuid      = osmGuid;
     DesiredColor = desiredColor;
     Text         = text;
 }
Пример #35
0
        public unsafe Bitmap Apply(Bitmap srcImg)
        {
            if (srcImg.PixelFormat != PixelFormat.Format24bppRgb)
            {
                throw new ArgumentException();
            }
            int        width      = srcImg.Width;
            int        height     = srcImg.Height;
            BitmapData bitmapdata = srcImg.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            Bitmap     bitmap     = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            BitmapData data2      = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            RGB        rgb        = new RGB();
            HSL        hsl        = new HSL();
            int        num3       = bitmapdata.Stride - (width * 3);
            double     num4       = 0.0;
            double     num5       = 0.0;
            double     num6       = 0.0;
            double     num7       = 0.0;

            if (this.inLuminance.Max != this.inLuminance.Min)
            {
                num4 = (this.outLuminance.Max - this.outLuminance.Min) / (this.inLuminance.Max - this.inLuminance.Min);
                num5 = this.outLuminance.Min - (num4 * this.inLuminance.Min);
            }
            if (this.inSaturation.Max != this.inSaturation.Min)
            {
                num6 = (this.outSaturation.Max - this.outSaturation.Min) / (this.inSaturation.Max - this.inSaturation.Min);
                num7 = this.outSaturation.Min - (num6 * this.inSaturation.Min);
            }
            byte *numPtr  = (byte *)bitmapdata.Scan0.ToPointer();
            byte *numPtr2 = (byte *)data2.Scan0.ToPointer();

            for (int i = 0; i < height; i++)
            {
                int num9 = 0;
                while (num9 < width)
                {
                    rgb.Red   = numPtr[2];
                    rgb.Green = numPtr[1];
                    rgb.Blue  = numPtr[0];
                    GodLesZ.Library.Imaging.ColorConverter.RGB2HSL(rgb, hsl);
                    if (hsl.Luminance >= this.inLuminance.Max)
                    {
                        hsl.Luminance = this.outLuminance.Max;
                    }
                    else if (hsl.Luminance <= this.inLuminance.Min)
                    {
                        hsl.Luminance = this.outLuminance.Min;
                    }
                    else
                    {
                        hsl.Luminance = (num4 * hsl.Luminance) + num5;
                    }
                    if (hsl.Saturation >= this.inSaturation.Max)
                    {
                        hsl.Saturation = this.outSaturation.Max;
                    }
                    else if (hsl.Saturation <= this.inSaturation.Min)
                    {
                        hsl.Saturation = this.outSaturation.Min;
                    }
                    else
                    {
                        hsl.Saturation = (num6 * hsl.Saturation) + num7;
                    }
                    GodLesZ.Library.Imaging.ColorConverter.HSL2RGB(hsl, rgb);
                    numPtr2[2] = rgb.Red;
                    numPtr2[1] = rgb.Green;
                    numPtr2[0] = rgb.Blue;
                    num9++;
                    numPtr  += 3;
                    numPtr2 += 3;
                }
                numPtr  += num3;
                numPtr2 += num3;
            }
            bitmap.UnlockBits(data2);
            srcImg.UnlockBits(bitmapdata);
            return(bitmap);
        }
 public MapColorEntryWithOsmGuid([NotNull] string osmGuid, [NotNull] RGB desiredColor)
 {
     OsmGuid      = osmGuid;
     DesiredColor = desiredColor;
 }
Пример #37
0
 public RGBFilter(RGB minRGB, RGB maxRGB)
 {
     this.minRGB = minRGB;
     this.maxRGB = maxRGB;
 }
 public bool Equals(RGB rgb)
 {
     return((this.R == rgb.R) && (this.G == rgb.G) && (this.B == rgb.B));
 }
Пример #39
0
        /// <summary>
        ///   Creates a color histogram discarding low intensity colors
        /// </summary>
        ///
        private unsafe float[] createHistogram(UnmanagedImage frame, Rectangle area)
        {
            int width     = frame.Width;
            int height    = frame.Height;
            int stride    = frame.Stride;
            int pixelSize = Bitmap.GetPixelFormatSize(frame.PixelFormat) / 8;
            int offset    = stride - area.Width * pixelSize;

            float[] histogram = new float[histogramSize];

            // stay inside the image
            int areaX      = Math.Max(area.X, 0);
            int areaY      = Math.Max(area.Y, 0);
            int areaWidth  = Math.Min(area.Width, width - areaX);
            int areaHeight = Math.Min(area.Height, height - areaY);


            if (mode == CamshiftMode.HSL)
            {
                // Process as HSL
                HSL hsl = new HSL();
                RGB rgb = new RGB();

                byte *src = (byte *)frame.ImageData.ToPointer() + areaX * pixelSize + areaY * stride;
                for (int y = 0; y < areaHeight; y++)
                {
                    for (int x = 0; x < areaWidth; x++, src += 3)
                    {
                        rgb.Red   = (*(src + RGB.R));
                        rgb.Green = (*(src + RGB.G));
                        rgb.Blue  = (*(src + RGB.B));

                        AForge.Imaging.HSL.FromRGB(rgb, hsl);

                        if ((hsl.Saturation >= hslSaturation.Min) && (hsl.Saturation <= hslSaturation.Max) &&
                            (hsl.Luminance >= hslLuminance.Min) && (hsl.Luminance <= hslLuminance.Max))
                        {
                            histogram[hsl.Hue] += 1;
                        }
                    }
                    src += offset;
                }
            }
            else if (mode == CamshiftMode.Mixed)
            {
                // Process in mixed mode
                HSL hsl = new HSL();
                RGB rgb = new RGB();

                byte *src = (byte *)frame.ImageData.ToPointer() + areaX * pixelSize + areaY * stride;
                for (int y = 0; y < areaHeight; y++)
                {
                    for (int x = 0; x < areaWidth; x++, src += 3)
                    {
                        rgb.Red   = (*(src + RGB.R));
                        rgb.Green = (*(src + RGB.G));
                        rgb.Blue  = (*(src + RGB.B));

                        AForge.Imaging.HSL.FromRGB(rgb, hsl);

                        if ((hsl.Saturation >= hslSaturation.Min) && (hsl.Saturation <= hslSaturation.Max) &&
                            (hsl.Luminance >= hslLuminance.Min) && (hsl.Luminance <= hslLuminance.Max))
                        {
                            histogram[(int)(hsl.Hue * 10 + hsl.Saturation * 100 + hsl.Luminance * 10)] += 1;
                        }
                    }
                    src += offset;
                }
            }
            else
            {
                // Process as RGB
                byte *src = (byte *)frame.ImageData.ToPointer() + areaX * pixelSize + areaY * stride;
                for (int y = 0; y < areaHeight; y++)
                {
                    for (int x = 0; x < areaWidth; x++, src += 3)
                    {
                        // (small values are discarded)
                        int r = (int)(*(src + RGB.R)) >> 4;
                        int g = (int)(*(src + RGB.G)) >> 4;
                        int b = (int)(*(src + RGB.B)) >> 4;
                        histogram[256 * r + 16 * g + b] += 1;
                    }
                    src += offset;
                }
            }

            return(histogram);
        }
Пример #40
0
        // Process the filter
        private unsafe void ProcessFilter(BitmapData data)
        {
            int width  = data.Width;
            int height = data.Height;

            RGB    rgb = new RGB( );
            YCbCr  ycbcr = new YCbCr( );
            int    offset = data.Stride - width * 3;
            double ky = 0, by = 0;
            double kcb = 0, bcb = 0;
            double kcr = 0, bcr = 0;

            // Y line params
            if (inY.Max != inY.Min)
            {
                ky = (outY.Max - outY.Min) / (inY.Max - inY.Min);
                by = outY.Min - ky * inY.Min;
            }
            // Cb line params
            if (inCb.Max != inCb.Min)
            {
                kcb = (outCb.Max - outCb.Min) / (inCb.Max - inCb.Min);
                bcb = outCb.Min - kcb * inCb.Min;
            }
            // Cr line params
            if (inCr.Max != inCr.Min)
            {
                kcr = (outCr.Max - outCr.Min) / (inCr.Max - inCr.Min);
                bcr = outCr.Min - kcr * inCr.Min;
            }

            // do the job
            byte *ptr = (byte *)data.Scan0.ToPointer( );

            // for each row
            for (int y = 0; y < height; y++)
            {
                // for each pixel
                for (int x = 0; x < width; x++, ptr += 3)
                {
                    rgb.Red   = ptr[RGB.R];
                    rgb.Green = ptr[RGB.G];
                    rgb.Blue  = ptr[RGB.B];

                    // convert to YCbCr
                    AForge.Imaging.ColorConverter.RGB2YCbCr(rgb, ycbcr);

                    // correct Y
                    if (ycbcr.Y >= inY.Max)
                    {
                        ycbcr.Y = outY.Max;
                    }
                    else if (ycbcr.Y <= inY.Min)
                    {
                        ycbcr.Y = outY.Min;
                    }
                    else
                    {
                        ycbcr.Y = ky * ycbcr.Y + by;
                    }

                    // correct Cb
                    if (ycbcr.Cb >= inCb.Max)
                    {
                        ycbcr.Cb = outCb.Max;
                    }
                    else if (ycbcr.Cb <= inCb.Min)
                    {
                        ycbcr.Cb = outCb.Min;
                    }
                    else
                    {
                        ycbcr.Cb = kcb * ycbcr.Cb + bcb;
                    }

                    // correct Cr
                    if (ycbcr.Cr >= inCr.Max)
                    {
                        ycbcr.Cr = outCr.Max;
                    }
                    else if (ycbcr.Cr <= inCr.Min)
                    {
                        ycbcr.Cr = outCr.Min;
                    }
                    else
                    {
                        ycbcr.Cr = kcr * ycbcr.Cr + bcr;
                    }

                    // convert back to RGB
                    AForge.Imaging.ColorConverter.YCbCr2RGB(ycbcr, rgb);

                    ptr[RGB.R] = rgb.Red;
                    ptr[RGB.G] = rgb.Green;
                    ptr[RGB.B] = rgb.Blue;
                }
                ptr += offset;
            }
        }
Пример #41
0
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        /// 
        /// <param name="image">Source image data.</param>
        /// <param name="rect">Image rectangle for processing by the filter.</param>
        /// 
        /// <exception cref="NullReferenceException">Channel image was not specified.</exception>
        /// <exception cref="InvalidImagePropertiesException">Channel image size does not match source
        /// image size.</exception>
        ///
        protected override unsafe void ProcessFilter( UnmanagedImage image, Rectangle rect )
        {
            if ( ( channelImage == null ) && ( unmanagedChannelImage == null ) )
            {
                throw new NullReferenceException( "Channel image was not specified." );
            }

            int pixelSize = Image.GetPixelFormatSize( image.PixelFormat ) / 8;

            int width   = image.Width;
            int height  = image.Height;
            int startX  = rect.Left;
            int startY  = rect.Top;
            int stopX   = startX + rect.Width;
            int stopY   = startY + rect.Height;
            int offset  = image.Stride - rect.Width * pixelSize;

            BitmapData chData = null;
            // pointer to channel's data
            byte* ch;
            // channel's image stride
            int chStride = 0;

            // check channel's image type
            if ( channelImage != null )
            {
                // check channel's image dimension
                if ( ( width != channelImage.Width ) || ( height != channelImage.Height ) )
                    throw new InvalidImagePropertiesException( "Channel image size does not match source image size." );

                // lock channel image
                chData = channelImage.LockBits(
                    new Rectangle( 0, 0, width, height ),
                    ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed );

                ch = (byte*) chData.Scan0.ToPointer( );
                chStride = chData.Stride;
            }
            else
            {
                // check channel's image dimension
                if ( ( width != unmanagedChannelImage.Width ) || ( height != unmanagedChannelImage.Height ) )
                    throw new InvalidImagePropertiesException( "Channel image size does not match source image size." );

                ch = (byte*) unmanagedChannelImage.ImageData;
                chStride = unmanagedChannelImage.Stride;
            }

            int     offsetCh = chStride - rect.Width;
            RGB     rgb = new RGB( );
            YCbCr   ycbcr = new YCbCr( );

            // do the job
            byte* dst = (byte*) image.ImageData.ToPointer( );

            // allign pointer to the first pixel to process
            dst += ( startY * image.Stride + startX * pixelSize );
            ch += ( startY * chStride + startX );

            // for each line
            for ( int y = startY; y < stopY; y++ )
            {
                // for each pixel
                for ( int x = startX; x < stopX; x++, dst += pixelSize, ch++ )
                {
                    rgb.Red     = dst[RGB.R];
                    rgb.Green   = dst[RGB.G];
                    rgb.Blue    = dst[RGB.B];

                    // convert to YCbCr
                    AForge.Imaging.YCbCr.FromRGB( rgb, ycbcr );

                    switch ( channel )
                    {
                        case YCbCr.YIndex:
                            ycbcr.Y = (float) *ch / 255;
                            break;

                        case YCbCr.CbIndex:
                            ycbcr.Cb = (float) *ch / 255 - 0.5f;
                            break;

                        case YCbCr.CrIndex:
                            ycbcr.Cr = (float) *ch / 255 - 0.5f;
                            break;
                    }

                    // convert back to RGB
                    AForge.Imaging.YCbCr.ToRGB( ycbcr, rgb );

                    dst[RGB.R] = rgb.Red;
                    dst[RGB.G] = rgb.Green;
                    dst[RGB.B] = rgb.Blue;
                }
                dst += offset;
                ch  += offsetCh;
            }

            if ( chData != null )
            {
                // unlock
                channelImage.UnlockBits( chData );
            }
        }
Пример #42
0
        RGB[] CreateColormap(byte[] pal)
        {
            // convert pal: 0..7 -> 0..255
              var tab = new byte[]{0, 36, 73, 109, 146, 182, 219, 255};
              var cmap = new RGB[16];

              for (int i = 0; i < 16; i++)
            {
              uint col = GetInteger(pal, 2 * i);
              cmap[i].R = tab[(col >> 8) & 7];
              cmap[i].G = tab[(col >> 4) & 7];
              cmap[i].B = tab[(col >> 0) & 7];
            }
              return cmap;
        }
Пример #43
0
 /// <summary>
 /// Returns a string representation of the RGB color value.
 /// </summary>
 /// <param name="color">The RGB color value.</param>
 /// <returns>The hex string representation.</returns>
 public static string Rgb2Hex(RGB color)
 {
     return(color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2"));
 }
Пример #44
0
        /// <summary>
        /// Processes the filter on the passed <paramref name="srcData"/>
        /// resulting into <paramref name="dstData"/>.
        /// </summary>
        /// <param name="srcData">The source bitmap data.</param>
        /// <param name="dstData">The destination bitmap data.</param>
        protected override void Process(BitmapData srcData, BitmapData dstData)
        {
            int pixelSize = Image.GetPixelFormatSize(srcData.PixelFormat) / 8;
            int w = srcData.Width;
            int h = srcData.Height;
            int offsetSrc = srcData.Stride - w * pixelSize;
            int offsetDst = dstData.Stride - w;

            // process image
            unsafe
            {
                byte* src = (byte*)srcData.Scan0.ToPointer();
                byte* dst = (byte*)dstData.Scan0.ToPointer();
                // for each line
                for (int y = 0; y < h; y++)
                {
                    // for each pixel in line
                    for (int x = 0; x < w; x++, src += pixelSize, dst++)
                    {
                        RGB rgb = new RGB(src[RGBA.R], src[RGBA.G], src[RGBA.B]);

                        switch (ColorSpace)
                        {
                            case ColorSpaceEnum.HSB:
                                SetGrayscaleValue(dst, rgb.To<HSB>().Color, 359.764706, 1, 1);
                                break;
                            case ColorSpaceEnum.HSL:
                                SetGrayscaleValue(dst, rgb.To<HSL>().Color, 359.764706, 1, 1);
                                break;
                            case ColorSpaceEnum.LAB:
                                SetGrayscaleValue(dst, rgb.To<LAB>().Color, 100, 184.417028, 202.338137);
                                break;
                            case ColorSpaceEnum.LCH:
                                SetGrayscaleValue(dst, rgb.To<LCH>().Color, 100, 133.807615, 3.14159259);
                                break;
                            case ColorSpaceEnum.LUV:
                                SetGrayscaleValue(dst, rgb.To<LUV>().Color, 100, 258.092592, 241.501545);
                                break;
                            case ColorSpaceEnum.RGB:
                                SetGrayscaleValue(dst, rgb.Color, 255, 255, 255);
                                break;
                            case ColorSpaceEnum.SRGB:
                                SetGrayscaleValue(dst, rgb.To<SRGB>().Color, 1, 1, 1);
                                break;
                            case ColorSpaceEnum.XYZ:
                                SetGrayscaleValue(dst, rgb.To<XYZ>().Color, 0.95047, 1, 1.08883);
                                break;
                        }
                    }
                    src += offsetSrc;
                    dst += offsetDst;
                }
            }
        }
Пример #45
0
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        ///
        /// <param name="image">Source image data.</param>
        /// <param name="rect">Image rectangle for processing by the filter.</param>
        ///
        protected override unsafe void ProcessFilter(UnmanagedImage image, Rectangle rect)
        {
            // get pixel size
            int pixelSize = (image.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;

            int startX = rect.Left;
            int startY = rect.Top;
            int stopX  = startX + rect.Width;
            int stopY  = startY + rect.Height;
            int offset = image.Stride - rect.Width * pixelSize;

            RGB rgb = new RGB( );
            HSL hsl = new HSL( );

            bool updated;

            // do the job
            byte *ptr = (byte *)image.ImageData.ToPointer( );

            // allign pointer to the first pixel to process
            ptr += (startY * image.Stride + startX * pixelSize);

            // for each row
            for (int y = startY; y < stopY; y++)
            {
                // for each pixel
                for (int x = startX; x < stopX; x++, ptr += pixelSize)
                {
                    updated   = false;
                    rgb.Red   = ptr[RGB.R];
                    rgb.Green = ptr[RGB.G];
                    rgb.Blue  = ptr[RGB.B];

                    // convert to HSL
                    BestCS.Imaging.HSL.FromRGB(rgb, hsl);

                    // check HSL values
                    if (
                        (hsl.Saturation >= saturation.Min) && (hsl.Saturation <= saturation.Max) &&
                        (hsl.Luminance >= luminance.Min) && (hsl.Luminance <= luminance.Max) &&
                        (
                            ((hue.Min < hue.Max) && (hsl.Hue >= hue.Min) && (hsl.Hue <= hue.Max)) ||
                            ((hue.Min > hue.Max) && ((hsl.Hue >= hue.Min) || (hsl.Hue <= hue.Max)))
                        )
                        )
                    {
                        if (!fillOutsideRange)
                        {
                            if (updateH)
                            {
                                hsl.Hue = fillH;
                            }
                            if (updateS)
                            {
                                hsl.Saturation = fillS;
                            }
                            if (updateL)
                            {
                                hsl.Luminance = fillL;
                            }

                            updated = true;
                        }
                    }
                    else
                    {
                        if (fillOutsideRange)
                        {
                            if (updateH)
                            {
                                hsl.Hue = fillH;
                            }
                            if (updateS)
                            {
                                hsl.Saturation = fillS;
                            }
                            if (updateL)
                            {
                                hsl.Luminance = fillL;
                            }

                            updated = true;
                        }
                    }

                    if (updated)
                    {
                        // convert back to RGB
                        BestCS.Imaging.HSL.ToRGB(hsl, rgb);

                        ptr[RGB.R] = rgb.Red;
                        ptr[RGB.G] = rgb.Green;
                        ptr[RGB.B] = rgb.Blue;
                    }
                }
                ptr += offset;
            }
        }
Пример #46
0
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        /// 
        /// <param name="image">Source image data.</param>
        /// <param name="rect">Image rectangle for processing by the filter.</param>
        ///
        protected override unsafe void ProcessFilter( UnmanagedImage image, Rectangle rect )
        {
            int pixelSize = Image.GetPixelFormatSize( image.PixelFormat ) / 8;

            int startX  = rect.Left;
            int startY  = rect.Top;
            int stopX   = startX + rect.Width;
            int stopY   = startY + rect.Height;
            int offset  = image.Stride - rect.Width * pixelSize;

            RGB     rgb = new RGB( );
            YCbCr   ycbcr = new YCbCr( );

            float ky  = 0, by  = 0;
            float kcb = 0, bcb = 0;
            float kcr = 0, bcr = 0;

            // Y line parameters
            if ( inY.Max != inY.Min )
            {
                ky = ( outY.Max - outY.Min ) / ( inY.Max - inY.Min );
                by = outY.Min - ky * inY.Min;
            }
            // Cb line parameters
            if ( inCb.Max != inCb.Min )
            {
                kcb = ( outCb.Max - outCb.Min ) / ( inCb.Max - inCb.Min );
                bcb = outCb.Min - kcb * inCb.Min;
            }
            // Cr line parameters
            if ( inCr.Max != inCr.Min )
            {
                kcr = ( outCr.Max - outCr.Min ) / ( inCr.Max - inCr.Min );
                bcr = outCr.Min - kcr * inCr.Min;
            }

            // do the job
            byte* ptr = (byte*) image.ImageData.ToPointer( );

            // allign pointer to the first pixel to process
            ptr += ( startY * image.Stride + startX * pixelSize );

            // for each row
            for ( int y = startY; y < stopY; y++ )
            {
                // for each pixel
                for ( int x = startX; x < stopX; x++, ptr += pixelSize )
                {
                    rgb.Red     = ptr[RGB.R];
                    rgb.Green   = ptr[RGB.G];
                    rgb.Blue    = ptr[RGB.B];

                    // convert to YCbCr
                     BestCS.Imaging.YCbCr.FromRGB( rgb, ycbcr );

                    // correct Y
                    if ( ycbcr.Y >= inY.Max )
                        ycbcr.Y = outY.Max;
                    else if ( ycbcr.Y <= inY.Min )
                        ycbcr.Y = outY.Min;
                    else
                        ycbcr.Y = ky * ycbcr.Y + by;

                    // correct Cb
                    if ( ycbcr.Cb >= inCb.Max )
                        ycbcr.Cb = outCb.Max;
                    else if ( ycbcr.Cb <= inCb.Min )
                        ycbcr.Cb = outCb.Min;
                    else
                        ycbcr.Cb = kcb * ycbcr.Cb + bcb;

                    // correct Cr
                    if ( ycbcr.Cr >= inCr.Max )
                        ycbcr.Cr = outCr.Max;
                    else if ( ycbcr.Cr <= inCr.Min )
                        ycbcr.Cr = outCr.Min;
                    else
                        ycbcr.Cr = kcr * ycbcr.Cr + bcr;

                    // convert back to RGB
                     BestCS.Imaging.YCbCr.ToRGB( ycbcr, rgb );

                    ptr[RGB.R] = rgb.Red;
                    ptr[RGB.G] = rgb.Green;
                    ptr[RGB.B] = rgb.Blue;
                }
                ptr += offset;
            }
        }
Пример #47
0
        static void Main()
        {
            if (mutex.WaitOne(TimeSpan.Zero, true) == false)
            {
                MessageBox.Show("Only one instance of Vistrol application allowed.");
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            formLicense = new FormLicense();

            LicenseChecker.LicenseChecker licenceChecker = null;
            DriveInfo[] allDrives = DriveInfo.GetDrives();
            foreach (DriveInfo drive in allDrives)
            {
                string filePath = drive.RootDirectory + LicenseChecker.LicenseChecker.LICENSE_FILE_NAME;
                if (Utils.Files.IsFileExists(filePath))
                {
                    licenceChecker = new LicenseChecker.LicenseChecker(filePath);
                    licenceChecker.EvtLicenseCheckStatus += licenceChecker_EvtLicenseCheckStatus;
                    break;
                }
            }

            if (licenceChecker == null)
            {
                MessageBox.Show("No license found. Please plug in dongle and retry.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                return;
            }

            // initialize database
            ConnectionManager connMgr = new ConnectionManager();

            formServer = new FormServer(connMgr);

            wcfCallback = new WcfCallbackHandler(connMgr, formServer);
            Server.ServerDbHelper.GetInstance().Initialize(wcfCallback);

            RGBERROR error   = 0;
            IntPtr   hRGBDLL = IntPtr.Zero;

            try
            {
                error = RGB.Load(out hRGBDLL);
                if (error == RGBERROR.NO_ERROR)
                {
                    ServerVisionHelper.getInstance().InitializeVisionDB();
                }
            }
            catch (Exception)
            {
            }

            licenceChecker.StartCheck();
            Application.Run(formServer);

            // clean up
            if (hRGBDLL != IntPtr.Zero)
            {
                RGB.Free(hRGBDLL);
            }

            licenceChecker.StopCheck();
        }
Пример #48
0
        private void InitMenu()
        {
            var menuStack = layout.Add(new StackPanel()
            {
                Orientation = Orientation.Vertical
            }, 0, 0);

            menuStack.Add(new Label()
            {
                Text = "Samples Menu".ToYellow(underlined: true)
            });
            menuStack.Add(new Label()
            {
                Text = ConsoleString.Empty
            });
            var overviewButton = menuStack.Add(new Button()
            {
                Tag = MenuTag, Shortcut = new KeyboardShortcut(ConsoleKey.O, null), Text = "Overview".ToWhite()
            });

            SetupMenuItem(overviewButton, () =>
            {
                var panel = new ConsolePanel();
                var label = panel.Add(new Label()
                {
                    Text = "Welcome to the PowerArgs sample app.".ToGreen()
                }).CenterBoth();
                return(panel);
            });

            var calculatorButton = menuStack.Add(new Button()
            {
                Tag = MenuTag, Shortcut = new KeyboardShortcut(ConsoleKey.C, null), Text = "Calculator program".ToWhite()
            });

            SetupMenuItem(calculatorButton, () =>
            {
                var panel   = new ConsolePanel();
                var console = panel.Add(new SampleConsole(() => new CommandLineArgumentsDefinition(typeof(CalculatorProgram)))).Fill();
                return(panel);
            });

            var args = new PerfTestArgs()
            {
                Test = TestCase.FallingChars
            };
            var perfButton = menuStack.Add(new Button()
            {
                Tag = MenuTag, Shortcut = new KeyboardShortcut(ConsoleKey.P, null), Text = "Perf Test".ToWhite()
            });

            SetupMenuItem(perfButton, () =>
            {
                var panel = new StackPanel()
                {
                    Height = 3, Orientation = Orientation.Vertical
                };
                panel.Add(new Form(FormOptions.FromObject(args))
                {
                    Height = 2
                }).FillHorizontally();
                var runButton = panel.Add(new Button()
                {
                    Text = "Run".ToWhite(), Shortcut = new KeyboardShortcut(ConsoleKey.R)
                });

                runButton.Pressed.SubscribeOnce(() =>
                {
                    panel.Controls.Clear();
                    var console = panel.Add(new PerfTest(args)).Fill();
                });

                InvokeNextCycle(() => panel.Descendents.Where(d => d.CanFocus).FirstOrDefault()?.TryFocus());

                return(panel);
            });

            var colorArgs = new ColorTestArgs {
                From = ConsoleColor.Black, To = ConsoleColor.Green, Mode = ConsoleMode.VirtualTerminal
            };
            var colorButton = menuStack.Add(new Button()
            {
                Tag = MenuTag, Shortcut = new KeyboardShortcut(ConsoleKey.R, null), Text = "RGB Test".ToWhite()
            });

            SetupMenuItem(colorButton, () =>
            {
                var panel = new ConsolePanel()
                {
                    Height = 4
                };
                panel.Add(new Form(FormOptions.FromObject(colorArgs))
                {
                    Height = 3
                }).FillHorizontally();
                var runButton = panel.Add(new Button()
                {
                    Y = 3, Text = "Run".ToWhite(), Shortcut = new KeyboardShortcut(ConsoleKey.R)
                });

                runButton.Pressed.SubscribeOnce(() =>
                {
                    panel.Controls.Clear();

                    if (colorArgs.Mode == ConsoleMode.VirtualTerminal)
                    {
                        ConsoleProvider.Fancy = true;
                    }

                    if (colorArgs.Mode == ConsoleMode.Console)
                    {
                        ConsoleProvider.Fancy = false;
                    }

                    var toColor = panel.Add(new ConsolePanel()
                    {
                        Width = 20, Height = 3, Background = colorArgs.From
                    }).CenterBoth();
                    var label = toColor.Add(new Label()
                    {
                        Text = toColor.Background.ToRGBString().ToWhite(toColor.Background, underlined: true)
                    }).CenterBoth();
                    RGB.AnimateAsync(new RGBAnimationOptions()
                    {
                        Transitions = new System.Collections.Generic.List <System.Collections.Generic.KeyValuePair <RGB, RGB> >()
                        {
                            new System.Collections.Generic.KeyValuePair <RGB, RGB>(colorArgs.From, colorArgs.To),
                        }
                        ,
                        Duration         = 1500,
                        EasingFunction   = Animator.EaseInOut,
                        AutoReverse      = true,
                        Loop             = this,
                        AutoReverseDelay = 500,
                        OnColorsChanged  = (c) =>
                        {
                            toColor.Background = c[0];
                            label.Text         = toColor.Background.ToRGBString().ToWhite(toColor.Background, underlined: true);
                        }
                    });
                });

                InvokeNextCycle(() => panel.Descendents.Where(d => d.CanFocus).FirstOrDefault()?.TryFocus());

                return(panel);
            });

            overviewButton.Pressed.Fire();
        }
Пример #49
0
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        /// 
        /// <param name="image">Source image data.</param>
        /// <param name="rect">Image rectangle for processing by the filter.</param>
        ///
        protected override unsafe void ProcessFilter( UnmanagedImage image, Rectangle rect )
        {
            int pixelSize = Bitmap.GetPixelFormatSize( image.PixelFormat ) / 8;

            int startX  = rect.Left;
            int startY  = rect.Top;
            int stopX   = startX + rect.Width;
            int stopY   = startY + rect.Height;
            int offset  = image.Stride - rect.Width * pixelSize;

            RGB rgb = new RGB( );
            HSL hsl = new HSL( );

            // do the job
            byte* ptr = (byte*) image.ImageData.ToPointer( );

            // allign pointer to the first pixel to process
            ptr += ( startY * image.Stride + startX * pixelSize );

            // for each row
            for ( int y = startY; y < stopY; y++ )
            {
                // for each pixel
                for ( int x = startX; x < stopX; x++, ptr += pixelSize )
                {
                    rgb.Red     = ptr[RGB.R];
                    rgb.Green   = ptr[RGB.G];
                    rgb.Blue    = ptr[RGB.B];

                    // convert to HSL
                     BestCS.Imaging.HSL.FromRGB( rgb, hsl );

                    // modify hue value
                    hsl.Hue = hue;

                    // convert back to RGB
                     BestCS.Imaging.HSL.ToRGB( hsl, rgb );

                    ptr[RGB.R] = rgb.Red;
                    ptr[RGB.G] = rgb.Green;
                    ptr[RGB.B] = rgb.Blue;
                }
                ptr += offset;
            }
        }
Пример #50
0
 private void Set_and_Send_AM0(OC_Mode mode, int band, RGB New_AM0)
 {
     ocparam.Set_OC_Mode_AM0(New_AM0, mode, band);
     Send_Gamma_AM1_AM0(mode, band);
     api.WriteLine("[Set_and_Send_AM0]OCMode/band AM0_R/G/B : " + mode + "/" + band + " " + New_AM0.int_R + "/" + New_AM0.int_G + "/" + New_AM0.int_B);
 }
Пример #51
0
 public void SetRightColor(RGB color, double opacity)
 {
     _gradient.SegmentSetRightColor(_segment, color, opacity);
 }
 public NodeColorRGB(int nodeNumber, RGB color)
 {
     _nodeNumber = nodeNumber;
     _color      = color;
 }
Пример #53
0
        // Process the filter
        private unsafe void ProcessFilter( BitmapData data )
        {
            int width	= data.Width;
            int height	= data.Height;

            RGB		rgb = new RGB( );
            HSL		hsl = new HSL( );
            int		offset = data.Stride - width * 3;
            bool	updated;

            // do the job
            byte * ptr = (byte *) data.Scan0.ToPointer( );

            // for each row
            for ( int y = 0; y < height; y++ )
            {
                // for each pixel
                for ( int x = 0; x < width; x++, ptr += 3 )
                {
                    updated		= false;
                    rgb.Red		= ptr[RGB.R];
                    rgb.Green	= ptr[RGB.G];
                    rgb.Blue	= ptr[RGB.B];

                    // convert to HSL
                    AForge.Imaging.ColorConverter.RGB2HSL( rgb, hsl );

                    // check HSL values
                    if (
                        ( hsl.Saturation >= saturation.Min ) && ( hsl.Saturation <= saturation.Max ) &&
                        ( hsl.Luminance >= luminance.Min ) && ( hsl.Luminance <= luminance.Max ) &&
                        (
                        ( ( hue.Min < hue.Max ) && ( hsl.Hue >= hue.Min ) && ( hsl.Hue <= hue.Max ) ) ||
                        ( ( hue.Min > hue.Max ) && ( ( hsl.Hue >= hue.Min ) || ( hsl.Hue <= hue.Max ) ) )
                        )
                        )
                    {
                        if ( !fillOutsideRange )
                        {
                            if ( updateH ) hsl.Hue			= fillH;
                            if ( updateS ) hsl.Saturation	= fillS;
                            if ( updateL ) hsl.Luminance	= fillL;

                            updated = true;
                        }
                    }
                    else
                    {
                        if ( fillOutsideRange )
                        {
                            if ( updateH ) hsl.Hue			= fillH;
                            if ( updateS ) hsl.Saturation	= fillS;
                            if ( updateL ) hsl.Luminance	= fillL;

                            updated = true;
                        }
                    }

                    if ( updated )
                    {
                        // convert back to RGB
                        AForge.Imaging.ColorConverter.HSL2RGB( hsl, rgb );

                        ptr[RGB.R] = rgb.Red;
                        ptr[RGB.G] = rgb.Green;
                        ptr[RGB.B] = rgb.Blue;
                    }
                }
                ptr += offset;
            }
        }
        public RGB to_RGB(HSI hsi)
        {
            RGB    rgb = new RGB();
            double r, g, b;

            double h = hsi.Hue;
            double s = hsi.Saturation;
            double i = hsi.Intensity;

            h = h * 2 * Math.PI;

            if (h >= 0 && h < 2 * Math.PI / 3)
            {
                b = i * (1 - s);
                r = i * (1 + s * Math.Cos(h) / Math.Cos(Math.PI / 3 - h));
                g = 3 * i - (r + b);
            }
            else if (h >= 2 * Math.PI / 3 && h < 4 * Math.PI / 3)
            {
                r = i * (1 - s);
                g = i * (1 + s * Math.Cos(h - 2 * Math.PI / 3) / Math.Cos(Math.PI - h));
                b = 3 * i - (r + g);
            }
            else //if (h >= 4 * Math.PI / 3 && h <= 2 * Math.PI)
            {
                g = i * (1 - s);
                b = i * (1 + s * Math.Cos(h - 4 * Math.PI / 3) / Math.Cos(5 * Math.PI / 3 - h));
                r = 3 * i - (g + b);
            }

            r *= 255;
            g *= 255;
            b *= 255;

            if (r > 255)
            {
                r = 255;
            }
            else if (r < 0)
            {
                r = 0;
            }

            if (g > 255)
            {
                g = 255;
            }
            else if (g < 0)
            {
                g = 0;
            }

            if (b > 255)
            {
                b = 255;
            }
            else if (b < 0)
            {
                b = 0;
            }
            rgb.Red   = Convert.ToInt32(r);
            rgb.Blue  = Convert.ToInt32(b);
            rgb.Green = Convert.ToInt32(g);
            return(rgb);
        }
Пример #55
0
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        /// 
        /// <param name="image">Source image data.</param>
        /// <param name="rect">Image rectangle for processing by the filter.</param>
        ///
        protected override unsafe void ProcessFilter( UnmanagedImage image, Rectangle rect )
        {
            // get pixel size
            int pixelSize = ( image.PixelFormat == PixelFormat.Format24bppRgb ) ? 3 : 4;

            int startX  = rect.Left;
            int startY  = rect.Top;
            int stopX   = startX + rect.Width;
            int stopY   = startY + rect.Height;
            int offset  = image.Stride - rect.Width * pixelSize;

            RGB rgb = new RGB( );
            YCbCr ycbcr = new YCbCr( );

            bool updated;

            // do the job
            byte* ptr = (byte*) image.ImageData.ToPointer( );

            // allign pointer to the first pixel to process
            ptr += ( startY * image.Stride + startX * pixelSize );

            // for each row
            for ( int y = startY; y < stopY; y++ )
            {
                // for each pixel
                for ( int x = startX; x < stopX; x++, ptr += pixelSize )
                {
                    updated   = false;
                    rgb.Red   = ptr[RGB.R];
                    rgb.Green = ptr[RGB.G];
                    rgb.Blue  = ptr[RGB.B];

                    // convert to YCbCr
                    AForge.Imaging.YCbCr.FromRGB( rgb, ycbcr );

                    // check YCbCr values
                    if (
                        ( ycbcr.Y >= yRange.Min )   && ( ycbcr.Y <= yRange.Max ) &&
                        ( ycbcr.Cb >= cbRange.Min ) && ( ycbcr.Cb <= cbRange.Max ) &&
                        ( ycbcr.Cr >= crRange.Min ) && ( ycbcr.Cr <= crRange.Max )
                        )
                    {
                        if ( !fillOutsideRange )
                        {
                            if ( updateY ) ycbcr.Y   = fillY;
                            if ( updateCb ) ycbcr.Cb = fillCb;
                            if ( updateCr ) ycbcr.Cr = fillCr;

                            updated = true;
                        }
                    }
                    else
                    {
                        if ( fillOutsideRange )
                        {
                            if ( updateY ) ycbcr.Y   = fillY;
                            if ( updateCb ) ycbcr.Cb = fillCb;
                            if ( updateCr ) ycbcr.Cr = fillCr;

                            updated = true;
                        }
                    }

                    if ( updated )
                    {
                        // convert back to RGB
                        AForge.Imaging.YCbCr.ToRGB( ycbcr, rgb );

                        ptr[RGB.R] = rgb.Red;
                        ptr[RGB.G] = rgb.Green;
                        ptr[RGB.B] = rgb.Blue;
                    }
                }
                ptr += offset;
            }
        }
        private void histogramEqualizationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Bitmap source = (Bitmap)pictureBox1.Image;

            int[] graylevel = new int[256];

            HSI[,] hsi = new HSI[source.Height, source.Width];


            progressBar1.Minimum = 0;
            progressBar1.Maximum = (source.Width * source.Height * 4);
            progressBar1.Value   = 0;

            for (int i = 0; i < source.Height; i++)
            {
                for (int j = 0; j < source.Width; j++)
                {
                    RGB rgb = new RGB(source.GetPixel(j, i).R, source.GetPixel(j, i).G, source.GetPixel(j, i).B);
                    hsi[i, j] = to_HSI(rgb);
                    progressBar1.Increment(1);
                }
            }


            ////
            for (int i = 0; i < source.Height; i++)
            {
                for (int j = 0; j < source.Width; j++)
                {
                    int inx = Convert.ToInt32(hsi[i, j].Intensity * 255);
                    graylevel[inx]++;
                    progressBar1.Increment(1);
                }
            }
            double[] Transform = new double[256];
            for (int i = 0; i < 256; i++)
            {
                Transform[i] = (double)graylevel[i] / (double)(source.Height * source.Width);
            }
            for (int i = 1; i < 256; i++)
            {
                Transform[i] = Transform[i] + Transform[i - 1];
            }
            for (int i = 0; i < source.Height; i++)
            {
                for (int j = 0; j < source.Width; j++)
                {
                    int inx = Convert.ToInt32(hsi[i, j].Intensity * 255);
                    hsi[i, j].Intensity = Transform[inx];
                    progressBar1.Increment(1);
                }
            }

            ////
            Bitmap result = new Bitmap(source.Width, source.Height);

            for (int i = 0; i < source.Height; i++)
            {
                for (int j = 0; j < source.Width; j++)
                {
                    RGB rgb = new RGB();
                    rgb = to_RGB(hsi[i, j]);
                    result.SetPixel(j, i, Color.FromArgb(rgb.Red, rgb.Green, rgb.Blue));
                    progressBar1.Increment(1);
                }
            }
            progressBar1.Value = 0;
            pictureBox2.Image  = result;
        }
Пример #57
0
 /*
  * Sets references to components on this Player game object or one of its children
  */
 void LinkComponents()
 {
     bluePower = (BluePower)GetComponent<BluePower> ();
     redPower = (RedPower)GetComponent<RedPower> ();
     greenPower = (GreenPower)GetComponent<GreenPower> ();
     playerRGB = (RGB)playerGeo.GetComponent<RGB> ();
     inventory = (Inventory)GetComponent<Inventory> ();
 }
Пример #58
0
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        ///
        /// <param name="image">Source image data.</param>
        /// <param name="rect">Image rectangle for processing by the filter.</param>
        ///
        protected override unsafe void ProcessFilter(UnmanagedImage image, Rectangle rect)
        {
            int pixelSize = Image.GetPixelFormatSize(image.PixelFormat) / 8;

            int startX = rect.Left;
            int startY = rect.Top;
            int stopX  = startX + rect.Width;
            int stopY  = startY + rect.Height;
            int offset = image.Stride - rect.Width * pixelSize;

            RGB rgb = new RGB( );
            HSL hsl = new HSL( );

            float kl = 0, bl = 0;
            float ks = 0, bs = 0;

            // luminance line parameters
            if (inLuminance.Max != inLuminance.Min)
            {
                kl = (outLuminance.Max - outLuminance.Min) / (inLuminance.Max - inLuminance.Min);
                bl = outLuminance.Min - kl * inLuminance.Min;
            }
            // saturation line parameters
            if (inSaturation.Max != inSaturation.Min)
            {
                ks = (outSaturation.Max - outSaturation.Min) / (inSaturation.Max - inSaturation.Min);
                bs = outSaturation.Min - ks * inSaturation.Min;
            }

            // do the job
            byte *ptr = (byte *)image.ImageData.ToPointer( );

            // allign pointer to the first pixel to process
            ptr += (startY * image.Stride + startX * pixelSize);

            // for each row
            for (int y = startY; y < stopY; y++)
            {
                // for each pixel
                for (int x = startX; x < stopX; x++, ptr += pixelSize)
                {
                    rgb.Red   = ptr[RGB.R];
                    rgb.Green = ptr[RGB.G];
                    rgb.Blue  = ptr[RGB.B];

                    // convert to HSL
                    AForge.Imaging.HSL.FromRGB(rgb, hsl);

                    // do luminance correction
                    if (hsl.Luminance >= inLuminance.Max)
                    {
                        hsl.Luminance = outLuminance.Max;
                    }
                    else if (hsl.Luminance <= inLuminance.Min)
                    {
                        hsl.Luminance = outLuminance.Min;
                    }
                    else
                    {
                        hsl.Luminance = kl * hsl.Luminance + bl;
                    }

                    // do saturation correct correction
                    if (hsl.Saturation >= inSaturation.Max)
                    {
                        hsl.Saturation = outSaturation.Max;
                    }
                    else if (hsl.Saturation <= inSaturation.Min)
                    {
                        hsl.Saturation = outSaturation.Min;
                    }
                    else
                    {
                        hsl.Saturation = ks * hsl.Saturation + bs;
                    }

                    // convert back to RGB
                    AForge.Imaging.HSL.ToRGB(hsl, rgb);

                    ptr[RGB.R] = rgb.Red;
                    ptr[RGB.G] = rgb.Green;
                    ptr[RGB.B] = rgb.Blue;
                }
                ptr += offset;
            }
        }
Пример #59
0
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        /// 
        /// <param name="image">Source image data.</param>
        /// <param name="rect">Image rectangle for processing by the filter.</param>
        ///
        protected override unsafe void ProcessFilter( UnmanagedImage image, Rectangle rect )
        {
            // get pixel size
            int pixelSize = ( image.PixelFormat == PixelFormat.Format24bppRgb ) ? 3 : 4;

            int startX  = rect.Left;
            int startY  = rect.Top;
            int stopX   = startX + rect.Width;
            int stopY   = startY + rect.Height;
            int offset  = image.Stride - rect.Width * pixelSize;

            RGB rgb = new RGB( );
            HSL hsl = new HSL( );

            bool updated;

            // do the job
            byte* ptr = (byte*) image.ImageData.ToPointer( );

            // allign pointer to the first pixel to process
            ptr += ( startY * image.Stride + startX * pixelSize );

            // for each row
            for ( int y = startY; y < stopY; y++ )
            {
                // for each pixel
                for ( int x = startX; x < stopX; x++, ptr += pixelSize )
                {
                    updated   = false;
                    rgb.Red   = ptr[RGB.R];
                    rgb.Green = ptr[RGB.G];
                    rgb.Blue  = ptr[RGB.B];

                    // convert to HSL
                    AForge.Imaging.HSL.FromRGB( rgb, hsl );

                    // check HSL values
                    if (
                        ( hsl.Saturation >= saturation.Min ) && ( hsl.Saturation <= saturation.Max ) &&
                        ( hsl.Luminance >= luminance.Min ) && ( hsl.Luminance <= luminance.Max ) &&
                        (
                        ( ( hue.Min < hue.Max ) && ( hsl.Hue >= hue.Min ) && ( hsl.Hue <= hue.Max ) ) ||
                        ( ( hue.Min > hue.Max ) && ( ( hsl.Hue >= hue.Min ) || ( hsl.Hue <= hue.Max ) ) )
                        )
                        )
                    {
                        if ( !fillOutsideRange )
                        {
                            if ( updateH ) hsl.Hue = fillH;
                            if ( updateS ) hsl.Saturation = fillS;
                            if ( updateL ) hsl.Luminance = fillL;

                            updated = true;
                        }
                    }
                    else
                    {
                        if ( fillOutsideRange )
                        {
                            if ( updateH ) hsl.Hue = fillH;
                            if ( updateS ) hsl.Saturation = fillS;
                            if ( updateL ) hsl.Luminance = fillL;

                            updated = true;
                        }
                    }

                    if ( updated )
                    {
                        // convert back to RGB
                        AForge.Imaging.HSL.ToRGB( hsl, rgb );

                        ptr[RGB.R] = rgb.Red;
                        ptr[RGB.G] = rgb.Green;
                        ptr[RGB.B] = rgb.Blue;
                    }
                }
                ptr += offset;
            }
        }
Пример #60
0
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        ///
        /// <param name="image">Source image data.</param>
        /// <param name="rect">Image rectangle for processing by the filter.</param>
        ///
        protected override unsafe void ProcessFilter(UnmanagedImage image, Rectangle rect)
        {
            int pixelSize = Image.GetPixelFormatSize(image.PixelFormat) / 8;

            int startX = rect.Left;
            int startY = rect.Top;
            int stopX  = startX + rect.Width;
            int stopY  = startY + rect.Height;
            int offset = image.Stride - rect.Width * pixelSize;

            RGB   rgb   = new RGB( );
            YCbCr ycbcr = new YCbCr( );

            float ky = 0, by = 0;
            float kcb = 0, bcb = 0;
            float kcr = 0, bcr = 0;

            // Y line parameters
            if (inY.Max != inY.Min)
            {
                ky = (outY.Max - outY.Min) / (inY.Max - inY.Min);
                by = outY.Min - ky * inY.Min;
            }
            // Cb line parameters
            if (inCb.Max != inCb.Min)
            {
                kcb = (outCb.Max - outCb.Min) / (inCb.Max - inCb.Min);
                bcb = outCb.Min - kcb * inCb.Min;
            }
            // Cr line parameters
            if (inCr.Max != inCr.Min)
            {
                kcr = (outCr.Max - outCr.Min) / (inCr.Max - inCr.Min);
                bcr = outCr.Min - kcr * inCr.Min;
            }

            // do the job
            byte *ptr = (byte *)image.ImageData.ToPointer( );

            // allign pointer to the first pixel to process
            ptr += (startY * image.Stride + startX * pixelSize);

            // for each row
            for (int y = startY; y < stopY; y++)
            {
                // for each pixel
                for (int x = startX; x < stopX; x++, ptr += pixelSize)
                {
                    rgb.Red   = ptr[RGB.R];
                    rgb.Green = ptr[RGB.G];
                    rgb.Blue  = ptr[RGB.B];

                    // convert to YCbCr
                    AForge.Imaging.YCbCr.FromRGB(rgb, ycbcr);

                    // correct Y
                    if (ycbcr.Y >= inY.Max)
                    {
                        ycbcr.Y = outY.Max;
                    }
                    else if (ycbcr.Y <= inY.Min)
                    {
                        ycbcr.Y = outY.Min;
                    }
                    else
                    {
                        ycbcr.Y = ky * ycbcr.Y + by;
                    }

                    // correct Cb
                    if (ycbcr.Cb >= inCb.Max)
                    {
                        ycbcr.Cb = outCb.Max;
                    }
                    else if (ycbcr.Cb <= inCb.Min)
                    {
                        ycbcr.Cb = outCb.Min;
                    }
                    else
                    {
                        ycbcr.Cb = kcb * ycbcr.Cb + bcb;
                    }

                    // correct Cr
                    if (ycbcr.Cr >= inCr.Max)
                    {
                        ycbcr.Cr = outCr.Max;
                    }
                    else if (ycbcr.Cr <= inCr.Min)
                    {
                        ycbcr.Cr = outCr.Min;
                    }
                    else
                    {
                        ycbcr.Cr = kcr * ycbcr.Cr + bcr;
                    }

                    // convert back to RGB
                    AForge.Imaging.YCbCr.ToRGB(ycbcr, rgb);

                    ptr[RGB.R] = rgb.Red;
                    ptr[RGB.G] = rgb.Green;
                    ptr[RGB.B] = rgb.Blue;
                }
                ptr += offset;
            }
        }