private Color GetColorFromImage()
 {
     var color = Colors.Transparent;
     try
     {
         BitmapSource bitmapSource = ImageColors.Source as BitmapSource;
         if (bitmapSource != null)
         {
             double x = Mouse.GetPosition(ImageColors).X;
             x *= bitmapSource.PixelWidth / ImageColors.ActualWidth;
             if ((int)x > bitmapSource.PixelWidth - 1)
                 x = bitmapSource.PixelWidth - 1;
             else if (x < 0) x = 0;
             double y = Mouse.GetPosition(ImageColors).Y;
             y *= bitmapSource.PixelHeight / ImageColors.ActualHeight;
             if ((int)y > bitmapSource.PixelHeight - 1)
                 y = bitmapSource.PixelHeight - 1;
             else if (y < 0) y = 0;
             CroppedBitmap cb = new CroppedBitmap(bitmapSource, new Int32Rect((int)x, (int)y, 1, 1));
             byte[] pixels = new byte[4];
             cb.CopyPixels(pixels, 4, 0);
             if (pixels[3] == byte.MaxValue)
             {
                 color = Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]);
             }
         }
     }
     catch (Exception ex)
     {
         Log.Add(ex);
     }
     return color;
 }
Ejemplo n.º 2
0
        private void Image_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            var AssociatedObject = this;
            // Retrieve the coordinate of the mouse position in relation to the supplied image.
            Point point = e.GetPosition(AssociatedObject);

            // Use RenderTargetBitmap to get the visual, in case the image has been transformed.
            var renderTargetBitmap = new RenderTargetBitmap((int) AssociatedObject.ActualWidth,
                (int) AssociatedObject.ActualHeight,
                96, 96, PixelFormats.Default);
            renderTargetBitmap.Render(AssociatedObject);

            // Make sure that the point is within the dimensions of the image.
            if ((point.X <= renderTargetBitmap.PixelWidth) && (point.Y <= renderTargetBitmap.PixelHeight))
            {
                // Create a cropped image at the supplied point coordinates.
                var croppedBitmap = new CroppedBitmap(renderTargetBitmap,
                    new Int32Rect((int) point.X, (int) point.Y, 1, 1));

                // Copy the sampled pixel to a byte array.
                var pixels = new byte[4];
                croppedBitmap.CopyPixels(pixels, 4, 0);

                // Assign the sampled color to a SolidColorBrush and return as conversion.
                var SelectedColor = Color.FromArgb(255, pixels[2], pixels[1], pixels[0]);
                TextBox.Text = "#" + SelectedColor.ToString().Substring(3);
                Label.Background = new SolidColorBrush(SelectedColor);
            }
        }
Ejemplo n.º 3
0
        private Color GetColorFromImage(Point p)
        {
            try
            {
                var bounds = VisualTreeHelper.GetDescendantBounds(this);
                var rtb = new RenderTargetBitmap((int) bounds.Width, (int) bounds.Height, 96, 96, PixelFormats.Default);
                rtb.Render(this);

                byte[] arr;
                var png = new PngBitmapEncoder();
                png.Frames.Add(BitmapFrame.Create(rtb));
                using (var stream = new MemoryStream())
                {
                    png.Save(stream);
                    arr = stream.ToArray();
                }

                BitmapSource bitmap = BitmapFrame.Create(new MemoryStream(arr));

                var pixels = new byte[4];
                var cb = new CroppedBitmap(bitmap, new Int32Rect((int) p.X, (int) p.Y, 1, 1));
                cb.CopyPixels(pixels, 4, 0);
                return Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]);
            }
            catch (Exception)
            {
                return ColorBox.Color;
            }
        }
Ejemplo n.º 4
0
        private void Image_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                var cb = new CroppedBitmap((BitmapSource) (((Image) e.Source).Source),
                                           new Int32Rect((int) Mouse.GetPosition(e.Source as Image).X,
                                                         (int) Mouse.GetPosition(e.Source as Image).Y, 1, 1));
                _pixels = new byte[4];
                try
                {
                    cb.CopyPixels(_pixels, 4, 0);
                    SetColor(Color.FromRgb(_pixels[2], _pixels[1], _pixels[0]));
                    UpdateMarkerPosition();

                    if (OnColorSelected != null)
                        OnColorSelected(SelectedColor);
                }
                catch
                {
                    // not logged
                }
                UpdateSlider();
            }
            catch (Exception)
            {
                // not logged
            }
        }
Ejemplo n.º 5
0
 void wheel_MouseMove(object sender, MouseEventArgs e)
 {
     try
     {
         CroppedBitmap cb = new CroppedBitmap(wheel.Source as BitmapSource, new Int32Rect((int)Mouse.GetPosition(this).X, (int)Mouse.GetPosition(this).Y, 1, 1));
         pixels = new byte[4];
         try
         {
             cb.CopyPixels(pixels, 4, 0);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
         Console.WriteLine(pixels[0] + ":" + pixels[1] + ":" + pixels[2] + ":" + pixels[3]);
         rec.Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(pixels[2], pixels[1], pixels[0]));
     }
     catch (Exception exc)
     {
     }
 }
 private void Image_MouseDown(object sender, MouseButtonEventArgs e)
 {
     try
     {
         var cb = new CroppedBitmap((BitmapSource)(((Image)e.Source).Source), new Int32Rect((int)Mouse.GetPosition(e.Source as Image).X, (int)Mouse.GetPosition(e.Source as Image).Y, 1, 1));
         _pixels = new byte[4];
         try
         {
             cb.CopyPixels(_pixels, 4, 0);
             UpdateCurrentColor();
             UpdateMarkerPosition();
         }
         catch
         {
         }
         UpdateSlider();
     }
     catch (Exception)
     {
     }
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Update the mouse cursor ellipse position.
 /// </summary>
 private void UpdateCursorEllipse(Color searchColor)
 {
     // Scan the canvas image for a color which matches the search color
     CroppedBitmap cb;
     Color tempColor = new Color();
     byte[] pixels = new byte[4];
     int searchY = 0;
     int searchX = 0;
     for (searchY = 0; searchY <= this.canvasImage.Width - 1; searchY++)
     {
         for (searchX = 0; searchX <= this.canvasImage.Height - 1; searchX++)
         {
             cb = new CroppedBitmap(this.ColorImage.Source as BitmapSource, new Int32Rect(searchX, searchY, 1, 1));
             cb.CopyPixels(pixels, 4, 0);
             tempColor = new Color(pixels[2], pixels[1], pixels[0]);
             if (tempColor == searchColor) break;
         }
         if (tempColor == searchColor) break;
     }
     // Default to the top left if no match is found
     if (tempColor != searchColor)
     {
         searchX = 0;
         searchY = 0;
     }
     // Update the mouse cursor ellipse position
     this.ellipsePixel.SetValue(Canvas.LeftProperty, ((double)searchX - (this.ellipsePixel.Width / 2.0)));
     this.ellipsePixel.SetValue(Canvas.TopProperty, ((double)searchY - (this.ellipsePixel.Width / 2.0)));
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Retrieves the color from the ColorRectangle at the point where the mouse is in the rectangle
        /// </summary>
        /// <returns>Returns the color in an Argb format</returns>
        private Color GetColorFromColorRectangle()
        {
            PresentationSource source = PresentationSource.FromVisual(this);

            //Gets the mouses current position relative to the color rectangle
            Point point = Mouse.GetPosition(ColorRectangle);

            //Creates a bitmap of the color rectangle and renders it
            RenderTargetBitmap bmp = new RenderTargetBitmap((int)ColorRectangle.Width, (int)ColorRectangle.Height, 96 * source.CompositionTarget.TransformToDevice.M11, 96 * source.CompositionTarget.TransformToDevice.M22, PixelFormats.Default);
            bmp.Render(ColorRectangle);

            //If the mouse position is within the color rectangle
            if ((point.X < bmp.PixelWidth) && (point.Y < bmp.PixelHeight))
            {
                //Create a cropped bitmap with the dimensions of height, width = 1, at the mouses position
                CroppedBitmap croppedBitmap = new CroppedBitmap(bmp, new Int32Rect((int)point.X, (int)point.Y, 1, 1));

                //Copies the pixel stored in the cropped bitmap to a byte array
                byte[] pixels = new byte[4];
                croppedBitmap.CopyPixels(pixels, 4, 0);

                //Returns the color generated from the byte array to the calling function
                return Color.FromArgb(255, pixels[2], pixels[1], pixels[0]);
            }
            //IF the mouse is out of bounds of the ColorRectangle, returns a default color
            else
                return Color.FromArgb(0, 0, 0, 0);
        }
Ejemplo n.º 9
0
		internal Present Render(MapRectangle mapRect, System.Drawing.Size size, bool useDocumentTransparency, bool exactColors)
		{
			Monitor.Enter(this);
			Present result;
			try
			{
				RectangleD rectangleD = new RectangleD(mapRect.lon0 * (double)this.boundingBox.Width - 0.5, -mapRect.lat1 * (double)this.boundingBox.Height + (double)this.actualBoundingBox.Height - 0.5, (mapRect.lon1 - mapRect.lon0) * (double)this.boundingBox.Width + (double)this.hackRectangleAdjust, (mapRect.lat1 - mapRect.lat0) * (double)this.boundingBox.Height + (double)this.hackRectangleAdjust);
				RectangleD rectangleD2 = rectangleD.Grow(2.0);
				RectangleD r = new RectangleD((double)this.actualBoundingBox.X, (double)this.actualBoundingBox.Y, (double)this.actualBoundingBox.Width, (double)this.actualBoundingBox.Height);
				RectangleD dest = new RectangleD(0.0, 0.0, (double)size.Width, (double)size.Height);
				ScaleAndTranslate scaleAndTranslate = new ScaleAndTranslate(rectangleD, dest);
				RectangleD rectangleD3 = rectangleD2.Intersect(r).Round();
				RectangleD rectangleD4 = scaleAndTranslate.Apply(rectangleD.Intersect(r));
				RectangleD rectangleD5 = scaleAndTranslate.Apply(rectangleD3);
				ScaleAndTranslate scaleAndTranslate2 = new ScaleAndTranslate(-rectangleD5.X, -rectangleD5.Y);
				RectangleD rectangleD6 = scaleAndTranslate2.Apply(rectangleD4);
				GDIBigLockedImage gDIBigLockedImage = new GDIBigLockedImage(size, "WPFVerb");
				GDIBigLockedImage image = gDIBigLockedImage;
				if (!rectangleD3.IntIsEmpty() && !rectangleD6.IntIsEmpty())
				{
					try
					{
						GDIBigLockedImage obj;
						Monitor.Enter(obj = gDIBigLockedImage);
						try
						{
							Bitmap bitmap = (Bitmap)gDIBigLockedImage.IPromiseIAmHoldingGDISLockSoPleaseGiveMeTheImage();
							BitmapSource source = new CroppedBitmap(this.primarySource, rectangleD3.ToInt32Rect());
							BitmapSource source2 = new TransformedBitmap(source, scaleAndTranslate.ToScaleTransform());
							BitmapSource bitmapSource = new CroppedBitmap(source2, rectangleD6.ToInt32Rect());
							Int32Rect int32Rect = rectangleD4.ToInt32Rect();
							BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, size.Width, size.Height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
							try
							{
								IntPtr buffer = new IntPtr(bitmapData.Scan0.ToInt32() + int32Rect.Y * bitmapData.Stride + int32Rect.X * 4);
								bitmapSource.CopyPixels(new Int32Rect(0, 0, bitmapSource.PixelWidth, bitmapSource.PixelHeight), buffer, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
							}
							finally
							{
								bitmap.UnlockBits(bitmapData);
							}
						}
						finally
						{
							Monitor.Exit(obj);
						}
					}
					catch (Exception ex)
					{
						if (BigDebugKnob.theKnob.debugFeaturesEnabled)
						{
							this.LabelThisImage(gDIBigLockedImage, ex.ToString());
						}
					}
					if (useDocumentTransparency)
					{
						image = gDIBigLockedImage;
					}
					else
					{
						GDIBigLockedImage gDIBigLockedImage2 = new GDIBigLockedImage(size, "WPFVerb-untransparent");
						GDIBigLockedImage obj2;
						Monitor.Enter(obj2 = gDIBigLockedImage2);
						try
						{
							Graphics graphics = gDIBigLockedImage2.IPromiseIAmHoldingGDISLockSoPleaseGiveMeTheGraphics();
							graphics.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, size.Width, size.Height);
							graphics.DrawImage(gDIBigLockedImage.IPromiseIAmHoldingGDISLockSoPleaseGiveMeTheImage(), 0, 0);
							graphics.Dispose();
							image = gDIBigLockedImage2;
							gDIBigLockedImage.Dispose();
						}
						finally
						{
							Monitor.Exit(obj2);
						}
					}
				}
				result = new ImageRef(new ImageRefCounted(image));
			}
			finally
			{
				Monitor.Exit(this);
			}
			return result;
		}
Ejemplo n.º 10
0
 /// <summary>
 /// 获取某点鼠标点击颜色值
 /// </summary>
 /// <param name="bitmapsource">当前点击图片</param>
 /// <param name="x">鼠标点击坐标</param>
 /// <param name="y">鼠标点击坐标</param>
 /// <returns>是否有效点击</returns>
 public static bool IsEffectiveHitOnPngImage(BitmapSource bitmapsource, double x, double y)
 {
     bool isEffective = false;
     CroppedBitmap crop = new CroppedBitmap(bitmapsource as BitmapSource, new Int32Rect((int)x, (int)y, 1, 1));
     byte[] pixels = new byte[4];
     try
     {
         crop.CopyPixels(pixels, 4, 0);
         crop = null;
     }
     catch (Exception e)
     {
         //MessageBox.Show(ee.ToString());
     }
     Color tempColor = Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]);
     if (tempColor.ToString() == "#00000000")
     {
         isEffective = false;//点击到非有效部分
     }
     else
     {
         isEffective = true;//点击到有效部分
     }
     return isEffective;
 }
Ejemplo n.º 11
0
        public int calcMacbethStats(byte[] pixels, int width, int height)
        {
            // //create array of rectangles
            System.Windows.Int32Rect[] macbethRects = new System.Windows.Int32Rect[24];

            for (int i = 0; i < 24; i++) {
                macbethRects[i].Width = (int)(width * 0.06);
                macbethRects[i].Height = (int)(height * 0.09);

                if (i % 6 == 0)
                    macbethRects[i].X = (int)(width * 0.04);
                else if (i % 6 == 1)
                    macbethRects[i].X = (int)(width * 0.21);
                else if (i % 6 == 2)
                    macbethRects[i].X = (int)(width * 0.38);
                else if (i % 6 == 3)
                    macbethRects[i].X = (int)(width * 0.56);
                else if (i % 6 == 4)
                    macbethRects[i].X = (int)(width * 0.72);
                else if (i % 6 == 5)
                    macbethRects[i].X = (int)(width * 0.89);
            }

            for (int i = 0; i < 24; i++) {
                if (i < 6)
                    macbethRects[i].Y = (int)(height * 0.06);
                else if (i < 12)
                    macbethRects[i].Y = (int)(height * 0.33);
                else if (i < 18)
                    macbethRects[i].Y = (int)(height * 0.58);
                else if (i < 24)
                    macbethRects[i].Y = (int)(height * 0.84);
            }

            // get patch stats for each rectangle
            for (int i = 0; i < 24; i++){
                byte[] patch = new byte[macbethRects[0].Width * macbethRects[0].Height*2];
                BitmapSource bmpSource = BitmapSource.Create(width, height, 96, 96, PixelFormats.Gray16, null, pixels, width * 2);
                //image1.Source = bmpSource;
                CroppedBitmap chunk = new CroppedBitmap(bmpSource, macbethRects[i]);

                try
                {
                    chunk.CopyPixels(patch, macbethRects[i].Width * 2, 0); // stuff data into 4 pixel (8 byte) array
                    calculateStats(patch, macbethRects[i].Width, macbethRects[i].Height);
                    MacbethMean[i] = getMeanValues();
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message);
                }
            }

            // calculate average colors
            /*int patchrow = 0, patchcol, row;
            for (row = 0; row < height; row++) {

                if ((row > (0.06 * height)) && (row < (0.15 * height)))
                    patchrow = 0;
                else if ((row > (0.33 * height)) && (row < (0.42 * height)))
                    patchrow = 1;
                else if ((row > (0.58 * height)) && (row < (0.67 * height)))
                    patchrow = 2;
                else if ((row > (0.84 * height)) && (row < (0.93 * height)))
                    patchrow = 3;
                else
                    patchrow = 4;

                for (int col = 0; col < width; col++) {

                    if ((col > (0.04 * width)) && (col < (0.1 * width)))
                        patchcol = 0;
                    else if ((col > (0.21 * width)) && (col < (0.27 * width)))
                        patchcol = 1;
                    else if ((col > (0.38 * width)) && (col < (0.44 * width)))
                        patchcol = 2;
                    else if ((col > (0.56 * width)) && (col < (0.62 * width)))
                        patchcol = 3;
                    else if ((col > (0.72 * width)) && (col < (0.78 * width)))
                        patchcol = 4;
                    else if ((col > (0.89 * width)) && (col < (0.95 * width)))
                        patchcol = 5;
                    else
                        patchcol = 6;

                    if ((patchcol < 6) && (patchrow < 4)) {
                        meanvalues[patchrow * 6 + patchcol, (row % 2) * 2 + col % 2] += values[row * width + col]; // assign index according to bayer position
                        pixelcount[patchrow * 6 + patchcol]++;
                    }
                }
            }*/
            return 0;
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Simply grab a 1*1 pixel from the current color image, and
        ///     use that and copy the new 1*1 image pixels to a byte array and
        ///     then construct a Color from that.
        /// </summary>
        private void CanvImage_MouseMove(object sender, MouseEventArgs e)
        {
            if (!IsMouseDown)
                return;

            try
            {
                var cb = new CroppedBitmap(ColorImage.Source as BitmapSource,
                                           new Int32Rect((int) Mouse.GetPosition(CanvImage).X,
                                                         (int) Mouse.GetPosition(CanvImage).Y, 1, 1));

                var pixels = new byte[4];

                try
                {
                    cb.CopyPixels(pixels, 4, 0);
                }
                catch (Exception)
                {
                    //Ooops
                }

                //Ok now, so update the mouse cursor position and the SelectedColor
                ellipsePixel.SetValue(Canvas.LeftProperty, (Mouse.GetPosition(CanvImage).X - 5));
                ellipsePixel.SetValue(Canvas.TopProperty, (Mouse.GetPosition(CanvImage).Y - 5));
                CanvImage.InvalidateVisual();
                SelectedColor = Color.FromArgb((byte) AlphaSlider.Value, pixels[2], pixels[1], pixels[0]);
            }
            catch (Exception)
            {
                //not much we can do
            }
        }
Ejemplo n.º 13
0
        private Color GetColour(BitmapSource bitmap, int position)
        {
            if (position >= bitmap.Width - 1)
            {
                position = (int)bitmap.Width - 2;
            }

            CroppedBitmap cb = new CroppedBitmap(bitmap, new Int32Rect(position, (int)this.VisualBounds.Height / 2, 1, 1));
            byte[] tricolour = new byte[4];

            cb.CopyPixels(tricolour, 4, 0);
            Color c = Color.FromRgb(tricolour[2], tricolour[1], tricolour[0]);

            return c;
        }
        private byte[] getPixelsFromBMPImage(Point loc, int width, int height)
        {
            byte[] pixels = new byte[width * height * 4]; // allocate mem for current pixel data values
            //int[] col = new int[4]; // color values

            CroppedBitmap chunk = new CroppedBitmap(bmpSource, new Int32Rect((int)loc.X, (int)loc.Y, width, height)); // get 2x2 region from source

            try {
                chunk.CopyPixels(pixels, width * 3, 0); // stuff data into 3 byte per pixel
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
            return pixels;
        }
        private void MenuSRGBCalibration_Click(object sender, RoutedEventArgs e)
        {
            selection.width = selection.width / 2 * 2;
            selection.height = selection.height / 2 * 2;
            byte[] pixels = new byte[selection.width * selection.height * 2]; // allocate mem for current pixel data values
            int[] values = new int[selection.width * selection.height]; // color values
            double[] cumSquareDiff = new double[4];

            selection.X = selection.X / 2 * 2; // force even number, otherwise bayer order is not constant
            selection.Y = selection.Y / 2 * 2;

            CroppedBitmap chunk = new CroppedBitmap(bmpSource, new Int32Rect(selection.X, selection.Y, selection.width, selection.height)); // get 2x2 region from source

            try {
                chunk.CopyPixels(pixels, selection.width * 2, 0); // stuff data into 4 pixel (8 byte) array
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }

            stats.calcMacbethStats(pixels, selection.width, selection.height);

            imagestats.colorvals[] macbethMeans = new imagestats.colorvals[24];

            macbethMeans = stats.getMacbethMean();
        }
        private byte[] getPixelsFromRawImage(Point loc, int width, int height)
        {
            //int[] col = new int[4]; // color values

            int x = (int)(loc.X) / 2 * 2; // force even number, otherwise bayer order is not constant
            int y = (int)(loc.Y) / 2 * 2;

            x = Math.Min(x, openImage.rawWidth - 2); // force 2x2 region inside actual image
            y = Math.Min(y, openImage.rawHeight - 2);

            width = width / 2 * 2;
            height = height / 2 * 2;

            byte[] pixels = new byte[width * height * 2]; // allocate mem for current pixel data values

            CroppedBitmap chunk = new CroppedBitmap(bmpSource, new Int32Rect(x, y, width, height));

            try {
                chunk.CopyPixels(pixels, width*2, 0); // stuff data into 4 pixel (8 byte) array
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
            return pixels;
        }
Ejemplo n.º 17
0
        private void Image_MouseMove(object sender, MouseEventArgs e)
        {
            if (Mouse.LeftButton == MouseButtonState.Pressed)
            {
                if (e.Source.GetType().Equals(typeof (Image)))
                {
                    var cb = new CroppedBitmap();

                    try
                    {
                        cb = new CroppedBitmap((BitmapSource) (((Image) e.Source).Source),
                                               new Int32Rect((int) Mouse.GetPosition(e.Source as Image).X,
                                                             (int) Mouse.GetPosition(e.Source as Image).Y, 1, 1));
                    }
                    catch (Exception)
                    {
                        // no need to log it..
                        return;
                    }

                    _pixels = new byte[4];
                    try
                    {
                        cb.CopyPixels(_pixels, 4, 0);
                        UpdateMarkerPosition();
                        SetColor(Color.FromRgb(_pixels[2], _pixels[1], _pixels[0]));

                        Mouse.Synchronize();
                        UpdateSlider();

                        if (OnColorSelected != null)
                            OnColorSelected(SelectedColor);
                    }
                    catch
                    {
                        // no need to log it
                    }
                }
            }
        }
Ejemplo n.º 18
0
 /// <summary>
 /// 1*1 pixel copy
 /// </summary>
 private Color GetColorFromImage(int x, int y)
 {
     var cb = new CroppedBitmap((BitmapSource)f_image.Source, new Int32Rect(x, y, 1, 1));
     var color = new byte[4];
     cb.CopyPixels(color, 4, 0);
     var colorFromImage = Color.FromArgb(a: f_color.A, r: color[2], g: color[1], b: color[0]);
     return colorFromImage;
 }
Ejemplo n.º 19
0
        void aligned_colorPixelsToBitmap(byte[] pixels, ColorImageFrame colorFrame, int x = 0, int y = 0, int width = 0, int height = 0)
        {
            
            width = width < 95 ? 95 : width;
            height = height < 95 ? 95 : height;
            int stride = colorFrame.Width * 4;
            aligned_colorBitmap = new WriteableBitmap(_sensor.ColorStream.FrameWidth, _sensor.ColorStream.FrameHeight, 96, 96, PixelFormats.Bgr32, null);
            
            
            
            
            // Write the pixel data into our bitmap
            this.aligned_colorBitmap.WritePixels(
              new Int32Rect(0, 0, this.aligned_colorBitmap.PixelWidth, this.aligned_colorBitmap.PixelHeight),
              pixels,
              this.aligned_colorBitmap.PixelWidth * sizeof(int),
              0);

           
            if (width > 0 && height > 0)
            {
                x = (x - 20) > 0 ? x - 20 : 0;
                y = (y - 20) > 0 ? y - 20 : 0;
                

                if (x + width >= 640 || y + height >= 480)
                    return;

                if (width > 0 && height > 0)
                {
                    cb = new CroppedBitmap(aligned_colorBitmap, new Int32Rect(x, y, width, height));

                    //************************ Convert Cropped image to double array of pixel intensities and send to matlab************************** 


                    int array_len = cb.PixelHeight * cb.PixelWidth * 4;
                    byte[] px = new byte[array_len];
                    int stride_cb = cb.PixelWidth * 4;

                    cb.CopyPixels(px, stride_cb, 0);

                    greyHandImage = new double[array_len / 4];

                    // Convert RGBA to Greyscale double

                    for (int i = 0, greyIndex = 0; i < array_len - 4; greyIndex++)
                    {
                        double Red = px[i];
                        double Green = px[i + 1];
                        double Blue = px[i + 2];
                        i = i + 4;


                        greyHandImage[greyIndex] = (Red * 0.212600 + Green * 0.715200 + Blue * 0.072200) /* /255 */;
                       // Console.WriteLine(greyHandImage[greyIndex]);
                    }

                  
                    // Write to matlab
                   
                    matlab.PutWorkspaceData("im", "base", greyHandImage);
                    

                    matlab.Execute("row = floor(sqrt(length(im)));");
                    matlab.Execute("im_1 = reshape(im ,row,row);");
                    matlab.Execute("im_2 = imresize(im_1' , [28 28]);");
                    matlab.Execute("testdata = im_2(:);");
                    matlab.Execute("testdata = (testdata-avg)./sd;");

                   
                      
                        matlab.Execute("[out_class] = stackedAEPredict(stackedAEOptTheta, length(testdata), 200, 5, netconfig, testdata)");
                        
                        int out_class = Convert.ToInt32( matlab.GetVariable("out_class", "base"));


                        if (x_cont == out_class)
                        {
                            counter_gesture++;

                            if (counter_gesture == 13) // 10 to 15 frames checking gives better result
                            {
                                pred = x_cont;
                                counter_gesture = 1;
                            }
                            
                        }
                        else
                        {
                            counter_gesture = 0;
                            x_cont = out_class;
                        }

                
                        if (old_pred != pred)
                        {
                            if (pred == 5)
                            {
                                matlab.Execute("fprintf(se,'%c','5')");
                                sendToSerial = false;
                            }
                            else if (pred == 1 || pred ==2 || pred ==4)
                                sendToSerial = true;
                           
                            

                            if (sendToSerial)
                            {
                                 matlab.PutWorkspaceData("predToSerial", "base", pred);
                                 matlab.Execute("predToSerial = num2str(predToSerial);");
                                 matlab.Execute("fprintf(se,'%c',predToSerial)");
                                // Console.WriteLine(matlab.Execute("imshow((im_1./255)');"));
                               
 
                            }
                           
                            old_pred = pred;
                            Console.WriteLine(pred);
                            
                        }



                       /* To Save image as file
                        * Console.WriteLine(matlab.Execute("imageData1 = [imageData1 testdata];"));
                        matlab.PutWorkspaceData("counter_matlab", "base", counter_matlab);
                        Console.WriteLine(matlab.Execute(@"img_path = sprintf('%s%d%s','C:\Users\Varun Kumar\Dropbox\Codes\Thesis\Data\4_back\',counter_matlab,'.jpeg');"));
                        Console.WriteLine(matlab.Execute("imwrite(im_1', img_path);"));
                        Console.WriteLine(matlab.Execute("imshow((im_1./255)');"));
                        Console.WriteLine("%s %d", "Sent data", counter_matlab);
                        counter_gesture++;
                        */
                }

               
//******************************************************************************************************************
                    img_cropped.Source = aligned_colorBitmap;
                    
               
            }
           
        }
Ejemplo n.º 20
0
        private System.Windows.Media.Color GetPixelColor(InputDevice inputDevice)
        {
            // Translate the input point to bitmap coordinates
            double transformFactor = ColorWheel.Source.Width / ColorWheel.ActualWidth;
            Point inputPoint = inputDevice.GetPosition(ColorWheel);
            Point bitmapPoint = new Point(inputPoint.X * transformFactor, inputPoint.Y * transformFactor);

            // The point is outside the color wheel. Return black.
            if (bitmapPoint.X < 0 || bitmapPoint.X >= ColorWheel.Source.Width ||
                bitmapPoint.Y < 0 || bitmapPoint.Y >= ColorWheel.Source.Height)
            {
                return Colors.Black;
            }

            // The point is inside the color wheel. Find the color at the point.
            CroppedBitmap cb = new CroppedBitmap(ColorWheel.Source as BitmapSource, new Int32Rect((int)bitmapPoint.X, (int)bitmapPoint.Y, 1, 1));
            byte[] pixels = new byte[4];
            cb.CopyPixels(pixels, 4, 0);
            return Color.FromRgb(pixels[2], pixels[1], pixels[0]);
        }
Ejemplo n.º 21
0
        private void ShowErrorUI()
        {
            ImageSource src = null;

            if (_IsInitializing)
            {
                src = XamlDocument.PreviewImage;
            }
            else
            {
                // update the error image
                src = RenderHelper.ElementToGrayscaleBitmap(ContentArea);
                XamlDocument.PreviewImage = src;
            }

            Color c = Color.FromArgb(255, 216, 216, 216);

            if (src is BitmapSource)
            {
                CroppedBitmap croppedSrc = new CroppedBitmap((BitmapSource)src, new Int32Rect(0, 0, 1, 1));
                byte[] pixels = new byte[4];
                croppedSrc.CopyPixels(pixels, 4, 0);
                c = Color.FromArgb(255, pixels[0], pixels[1], pixels[2]);
            }

            ErrorOverlayImage.Source = src;
            ErrorOverlay.Background = new SolidColorBrush(c);

            DoubleAnimation d = (DoubleAnimation)this.FindResource("ShowErrorOverlay");
            d.Completed += new EventHandler(ErrorOverlayAnimationCompleted);
            if (d != null)
            {
                ErrorOverlay.BeginAnimation(OpacityProperty, d);
            }
        }
Ejemplo n.º 22
0
        //
        // Unashamedly copied from online somewhere
        //
        public Color GetPixel(BitmapSource bitmap, int x, int y)
        {
            //Debug.Assert(bitmap != null);
            //Debug.Assert(x >= 0);
            //Debug.Assert(y >= 0);
            //Debug.Assert(x < bitmap.PixelWidth);
            //Debug.Assert(y < bitmap.PixelHeight);
            //Debug.Assert(bitmap.Format.BitsPerPixel >= 24);

            CroppedBitmap cb = new CroppedBitmap(bitmap, new Int32Rect(x, y, 1, 1));
            byte[] pixel = new byte[bitmap.Format.BitsPerPixel / 8];
            cb.CopyPixels(pixel, bitmap.Format.BitsPerPixel / 8, 0);
            return Color.FromRgb(pixel[2], pixel[1], pixel[0]);
        }
Ejemplo n.º 23
0
 private Color PickColor(double x, double y)
 {
     BitmapSource bitmapSource = ColourPicker.Source as BitmapSource;
     if (bitmapSource != null)
     {
         var cb = new CroppedBitmap(bitmapSource,
                                              new Int32Rect((int)Convert.ToInt32(x),
                                                            (int)Convert.ToInt32(y), 1, 1));
         var pixels = new byte[4];
         try
         {
             cb.CopyPixels(pixels, 4, 0);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
         return Color.FromRgb(pixels[2], pixels[1], pixels[0]);
     }
     var emptyColor = new Color();
     emptyColor.A = 255;
     emptyColor.R = 0;
     emptyColor.G = 0;
     emptyColor.B = 0;
     return emptyColor;
 }
Ejemplo n.º 24
0
 private void Image_MouseMove(object sender, MouseEventArgs e)
 {
     if (Mouse.LeftButton == MouseButtonState.Pressed)
     {
         if (e.Source.GetType().Equals(typeof(Image)))
         {
             Int32Rect rect = new Int32Rect((int)Mouse.GetPosition(e.Source as Image).X, (int)Mouse.GetPosition(e.Source as Image).Y, 1, 1);
             try
             {
                 var cb = new CroppedBitmap((BitmapSource)(((Image)e.Source).Source), rect);
                 _pixels = new byte[4];
                 cb.CopyPixels(_pixels, 4, 0);
                 UpdateMarkerPosition();
                 UpdateCurrentColor();
                 Mouse.Synchronize();
             }
             catch
             {
             }
             UpdateSlider();
         }
     }
 }
Ejemplo n.º 25
0
        //==========================================================//
        /// <summary>
        /// Gets the color of a specific pixel.
        /// </summary>
        /// <param name="pt">The point from which to get a color.</param>
        /// <returns>The color of the point.</returns>
        private System.Windows.Media.Color GetPixelColor(Contact contact)
        {
            // Translate the point according to whatever transforms are on the color wheel.
            Point rawPoint = contact.GetPosition(ColorWheel);
            Point transformedPoint = ColorWheel.RenderTransform.Transform(rawPoint);

            // The point is outside the color wheel. Return black.
            if (transformedPoint.X < 0 || transformedPoint.X >= ColorWheel.Source.Width ||
                transformedPoint.Y < 0 || transformedPoint.Y >= ColorWheel.Source.Height)
            {
                return Colors.Black;
            }

            // The point is inside the color wheel. Find the color at the point.
            CroppedBitmap cb = new CroppedBitmap(ColorWheel.Source as BitmapSource, new Int32Rect((int)transformedPoint.X, (int)transformedPoint.Y, 1, 1));
            byte[] pixels = new byte[4];
            cb.CopyPixels(pixels, 4, 0);
            return Color.FromRgb(pixels[2], pixels[1], pixels[0]);
        }
Ejemplo n.º 26
0
 /// <summary>
 /// 获取一个相对于左上角的像素点的颜色
 /// </summary>
 /// <param name="X">检测点X坐标</param>
 /// <param name="Y">检测点Y坐标</param>
 /// <returns>一个ARGB描述的Color实例</returns>
 public Color GetPixelColor(double X, double Y)
 {
     Color c = Color.FromArgb(Byte.MaxValue, 0, 0, 0);
     if (this.SpriteBitmapImage != null)
     {
         try
         {
             CroppedBitmap cb = new CroppedBitmap(this.SpriteBitmapImage, new Int32Rect((int)X, (int)Y, 1, 1));
             byte[] pixels = new byte[4];
             cb.CopyPixels(pixels, 4, 0);
             c = Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]);
         }
         catch (Exception) { }
     }
     return c;
 }
Ejemplo n.º 27
0
 /// <summary>
 /// 1*1 pixel copy is based on an article by Lee Brimelow    
 /// http://thewpfblog.com/?p=62
 /// </summary>
 private Color GetColorFromImage(int i, int j)
 {
     CroppedBitmap cb = new CroppedBitmap(image.Source as BitmapSource,
         new Int32Rect(i,
             j, 1, 1));
     byte[] color = new byte[4];
     cb.CopyPixels(color, 4, 0);
     Color Colorfromimagepoint = Color.FromArgb((byte)SdA.Value, color[2], color[1], color[0]);
     return Colorfromimagepoint;
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Sets a new Selected Color based on the color of the pixel under the mouse pointer.
 /// </summary>
 private void UpdateColor()
 {
     // Test to ensure we do not get bad mouse positions along the edges
     int imageX = (int)Mouse.GetPosition(this.canvasImage).X;
     int imageY = (int)Mouse.GetPosition(this.canvasImage).Y;
     if ((imageX < 0) || (imageY < 0) || (imageX > this.ColorImage.Width - 1) || (imageY > this.ColorImage.Height - 1)) return;
     // Get the single pixel under the mouse into a bitmap and copy it to a byte array
     CroppedBitmap cb = new CroppedBitmap(this.ColorImage.Source as BitmapSource, new Int32Rect(imageX, imageY, 1, 1));
     byte[] pixels = new byte[4];
     cb.CopyPixels(pixels, 4, 0);
     // Update the mouse cursor position and the Selected Color
     this.ellipsePixel.SetValue(Canvas.LeftProperty, (double)(Mouse.GetPosition(this.canvasImage).X - (this.ellipsePixel.Width / 2.0)));
     this.ellipsePixel.SetValue(Canvas.TopProperty, (double)(Mouse.GetPosition(this.canvasImage).Y - (this.ellipsePixel.Width / 2.0)));
     this.canvasImage.InvalidateVisual();
     // Set the Selected Color based on the cursor pixel and Alpha Slider value
     this.SelectedColor = new Color(pixels[2], pixels[1], pixels[0]);
     this.SelectedBrightness = (byte)this.AlphaSlider.Value;
 }
Ejemplo n.º 29
0
		/// <summary>
		/// Simply grab a 1*1 pixel from the current color image, and
		/// use that and copy the new 1*1 image pixels to a byte array and
		/// then construct a Color from that.
		/// </summary>
		private void CanvImage_MouseMove(object sender, MouseEventArgs e)
			{
			if (!IsMouseDown)
				return;

			try
				{
				int MouseX = (int) Mouse.GetPosition (CanvImage).X;
				int MouseY = (int) Mouse.GetPosition (CanvImage).Y;

				int XMax = (int) CanvImage.ActualWidth;
				int YMax = (int) CanvImage.ActualHeight;
				if (MouseX >= XMax)
					MouseX = XMax - 1;
				if (MouseY >= YMax)
					MouseY = YMax - 1;
				CroppedBitmap cb = new CroppedBitmap (ColorImage.Source as BitmapSource,
					new Int32Rect (MouseX, MouseY, 1, 1));

				byte[] pixels = new byte[4];

				try
					{
					cb.CopyPixels(pixels, 4, 0);
					}
				catch (Exception Excp)
					{
					//Ooops
					}

				//Ok now, so update the mouse cursor position and the SelectedColor
				ellipsePixel.SetValue (Canvas.LeftProperty, (double) (MouseX - 5));
				ellipsePixel.SetValue (Canvas.TopProperty, (double) (MouseY - 5));
				CanvImage.InvalidateVisual();
				SelectedColor = Color.FromArgb((byte)AlphaSlider.Value, pixels[2], pixels[1], pixels[0]);
				}
			catch (Exception Excp)
				{
				//not much we can do
				}
			}
Ejemplo n.º 30
0
        private Color GetColorFromImage(int i, int j)
        {
            var cb = new CroppedBitmap(image.Source as BitmapSource, new Int32Rect(i, j, 1, 1));
            var color = new byte[4];

            cb.CopyPixels(color, 4, 0);

            var colorFromImagePoint = Color.FromArgb(255, color[2], color[1], color[0]);

            return colorFromImagePoint;
        }