public MainForm() { InitializeComponent(); m_CameraParameters = CameraParameters.Load(@"..\..\..\..\CalibrationFiles\MicrosoftCinema\Focus14\1280x720\MicrosoftCinemaFocus14_1280x720.txt"); m_RawImage = new Image<Bgr, byte>(@"..\..\..\..\CalibrationFiles\MicrosoftCinema\Focus14\1280x720\GroundProjectionCalibration.jpg"); this.CurrentImage = m_RawImage.Clone(); this.BirdsEyeImage = m_RawImage.Clone(); InitializeUndistortMap(m_RawImage); Undistort(m_RawImage, this.CurrentImage); this.ChessBoard = new ChessBoard(8, 10); PointF[] foundCorners = CollectImageCorners(); DrawFoundCorners(this.CurrentImage, foundCorners); // We pick four corners for perspective transform PointF[] outerCorners = new PointF[4]; outerCorners[0] = foundCorners[0]; outerCorners[1] = foundCorners[this.ChessBoard.PatternSize.Width - 1]; outerCorners[2] = foundCorners[this.ChessBoard.PatternSize.Width * this.ChessBoard.PatternSize.Height - this.ChessBoard.PatternSize.Width]; outerCorners[3] = foundCorners[this.ChessBoard.PatternSize.Width * this.ChessBoard.PatternSize.Height - 1]; DrawOuterCorners(this.CurrentImage, outerCorners); float side; float bottom; float centerX; side = 25.0f; bottom = 310.0f; PointF[] physicalPointsForCalculation = new PointF[4]; physicalPointsForCalculation[0] = new PointF(-3 * side, bottom + 8 * side); physicalPointsForCalculation[1] = new PointF(+3 * side, bottom + 8 * side); physicalPointsForCalculation[2] = new PointF(-3 * side, bottom); physicalPointsForCalculation[3] = new PointF(+3 * side, bottom); m_BirdsEyeViewTransformationForCalculation = CameraCalibration.GetPerspectiveTransform(outerCorners, physicalPointsForCalculation); HomographyMatrixSupport.Save(m_BirdsEyeViewTransformationForCalculation, "BirdsEyeViewTransformationForCalculation.txt"); side = 8f; bottom = 700.0f; centerX = (float)m_CameraParameters.Intrinsic.Cx; PointF[] physicalPointsForUI = new PointF[4]; physicalPointsForUI[0] = new PointF(-3 * side + centerX, bottom - 8 * side); physicalPointsForUI[1] = new PointF(+3 * side + centerX, bottom - 8 * side); physicalPointsForUI[2] = new PointF(-3 * side + centerX, bottom); physicalPointsForUI[3] = new PointF(+3 * side + centerX, bottom); m_BirdsEyeViewTransformationForUI = CameraCalibration.GetPerspectiveTransform(outerCorners, physicalPointsForUI); HomographyMatrixSupport.Save(m_BirdsEyeViewTransformationForUI, "BirdsEyeViewTransformationForUI.txt"); //m_BirdsEyeViewTransformationForCalculation.ProjectPoints(outerCorners); CreateAndDrawBirdsEyeView(); }
/// <summary> /// 初始化绘图工具 /// </summary> /// <param name="g">绘图板</param> /// <param name="c">绘图颜色</param> /// <param name="img">初始画布</param> public DrawTools(Graphics g, Color c, Image img) { DrawTools_Graphics = g; drawColor = c; p = new Pen(c, 1); finishingImg = (Image)img.Clone(); orginalImg = (Image)img.Clone(); }
//Implémentation de RLSA (j'ai rien compris mais ça marche) retourne le document structuré public Image<Gray, byte> RLSA(Image<Gray, byte> tmpImg) { Image<Gray, byte> calcul = tmpImg.Clone(); Image<Gray, byte> vertical = RLSAV(calcul); Image<Gray, byte> horizontal = RLSAH(calcul); Image<Gray, byte> structure = tmpImg.Clone(); CvInvoke.BitwiseAnd(vertical, horizontal, structure); return structure; }
public Bitmap GetBrightness(System.Drawing.Image imgOrigin) { Bitmap bmp = (Bitmap)imgOrigin.Clone(); int px = 0; for (int i = 0; i < bmp.Height; i++) { for (int j = 0; j < bmp.Width; j++) { Color c = bmp.GetPixel(j, i); double b = 0.2126 * c.R + 0.7152 * c.G + 0.0722 * c.B; //double b = c.GetBrightness(); _brightness += b; px++; } } _brightness = _brightness / px; int difBright = 150 - (int)_brightness; BrightnessCorrection _filterB = new BrightnessCorrection(difBright); _filterB.ApplyInPlace(bmp); return(bmp); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Returns a darkened version of the specified image. /// </summary> /// ------------------------------------------------------------------------------------ public static Image MakeHotImage(Image img) { if (img == null) return null; float[][] colorMatrixElements = { new[] {0.6f, 0, 0, 0, 0}, new[] {0, 0.6f, 0, 0, 0}, new[] {0, 0, 0.6f, 0, 0}, new[] {0, 0, 0, 1f, 0}, new[] {0.1f, 0.1f, 0.1f, 0, 1} }; img = img.Clone() as Image; using (var imgattr = new ImageAttributes()) using (var g = Graphics.FromImage(img)) { var cm = new ColorMatrix(colorMatrixElements); var rc = new Rectangle(0, 0, img.Width, img.Height); imgattr.SetColorMatrix(cm); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(img, rc, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgattr); return img; } }
public CropTransformation(Image sourceImage, Point point, Size size) { _disposed = false; _sourceImage = sourceImage.Clone() as Image; _point = point; _size = size; }
public EditMapView(string title, int fieldsize, int hitbox, Image image, MapCreatorView mapCreatorView) { InitializeComponent(); this.EveryNode = new BindingList<Node>(); this.title = title; this.Fieldsize = fieldsize; this.hitbox = hitbox; this.Image = (Image)image.Clone(); this.MapCreatorView = mapCreatorView; this.Text = String.Concat("Currently editing: ", title); this.pictureBoxMapImage.Location = new Point(this.Size.Width, this.rButtonAddCarStartPosition.Location.Y); // Grid this.DrawGrid(); // Get all nodes this.CalculateEveryNode(); this.listBoxEveryNode.DataSource = this.EveryNode; this.listBoxEveryNode.ValueMember = "ListDisplay"; this.pictureBoxMapImage.Image = this.Image; this.CalculateNewViewSize(); this.DrawUsedNodesFromList(this.MapCreatorView.CarStartPositions, Color.Red); this.DrawUsedNodesFromList(this.MapCreatorView.RoundFinishedPositions, Color.Black); this.DrawUsedNodesFromList(this.MapCreatorView.ForbiddenPositions, Color.Blue); this.ActiveButton = "carStartPosition"; }
public ResizeTransformation(Image sourceImage, int width, int height) { _disposed = false; _sourceImage = sourceImage.Clone() as Image; _width = width; _height = height; }
public LineDetectionFromFileTesting() { viewer = new ImageViewer(); //create an image viewer //Convert the image to grayscale and filter out the noise // gray = new Image<Gray, Byte>("C:/RoboSub/RoboImagesTest2/92c.png"); fileImage = new Image<Bgr, Byte>(fileName); fileImage = fileImage.Resize(300, 200, Emgu.CV.CvEnum.INTER.CV_INTER_AREA, true); img = fileImage.Clone(); gray = img.Convert<Gray, Byte>(); // img = new Image<Bgr, Byte>("C:/RoboSub/RoboImagesTest2/92c.png"); viewer.Size = new Size(fileImage.Width * 3, fileImage.Height * 3); Thread input = new Thread(getKeyboardInput); input.Start(); Thread test = new Thread(testShapeDetection); test.Start(); Application.Idle += new EventHandler(delegate(object sender, EventArgs e) { //testShapeDetection(); }); viewer.ShowDialog(); test.Abort(); input.Abort(); }
/// <summary> /// Change the opacity of an image /// </summary> /// <param name="originalImage">The original image</param> /// <param name="opacity">Opacity, where 1.0 is no opacity, 0.0 is full transparency</param> /// <returns>The changed image</returns> public static System.Drawing.Image ChangeImageOpacity(System.Drawing.Image originalImage, double opacity) { int bytesPerPixel = 4; if ((originalImage.PixelFormat & PixelFormat.Indexed) == PixelFormat.Indexed) { // Cannot modify an image with indexed colors return(originalImage); } Bitmap bmp = (Bitmap)originalImage.Clone(); // Specify a pixel format. PixelFormat pxf = PixelFormat.Format32bppArgb; // Lock the bitmap's bits. System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, pxf); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. // This code is specific to a bitmap with 32 bits per pixels // (32 bits = 4 bytes, 3 for RGB and 1 byte for alpha). int numBytes = bmp.Width * bmp.Height * bytesPerPixel; byte[] argbValues = new byte[numBytes]; // Copy the ARGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, argbValues, 0, numBytes); // Manipulate the bitmap, such as changing the // RGB values for all pixels in the the bitmap. for (int counter = 0; counter < argbValues.Length; counter += bytesPerPixel) { // argbValues is in format BGRA (Blue, Green, Red, Alpha) // If 100% transparent, skip pixel if (argbValues[counter + bytesPerPixel - 1] == 0) { continue; } int pos = 0; pos++; // B value pos++; // G value pos++; // R value argbValues[counter + pos] = (byte)(argbValues[counter + pos] * opacity); } // Copy the ARGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(argbValues, 0, ptr, numBytes); // Unlock the bits. bmp.UnlockBits(bmpData); return(bmp); }
public bool UploadRawImage(System.Drawing.Image img, string newid, string containerName, string directoryPath) { try { CloudBlobContainer container = blobClient.GetContainerReference(containerName); CloudBlobDirectory dir = container.GetDirectoryReference(directoryPath); // Create the container if it doesn't already exist container.CreateIfNotExist(); container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); System.Drawing.Image imgFull = (System.Drawing.Image)img.Clone(); // Retrieve reference to a blob by username CloudBlob blobFull = dir.GetBlobReference(newid); using (MemoryStream ms = new MemoryStream()) { imgFull.Save(ms, ImageFormat.Png); blobFull.UploadByteArray(ms.ToArray()); } return(true); } catch { return(false); } }
public static Bitmap ChangeAllColorTo(Image img, Color c) { if (img == null) return null; if (img.PixelFormat.HasFlag(PixelFormat.Indexed)) return (Bitmap)img; Bitmap bmp = (Bitmap)img.Clone(); BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); IntPtr ptr = bmpData.Scan0; int len = bmp.Width * bmp.Height * 4; byte[] data = new byte[len]; Marshal.Copy(ptr, data, 0, len); byte R = c.R; byte G = c.G; byte B = c.B; for (int i = 0; i < data.Length; i += 4) if (data[i + 3] != 0) { data[i + 0] = B; data[i + 1] = G; data[i + 2] = R; } Marshal.Copy(data, 0, ptr, len); bmp.UnlockBits(bmpData); return bmp; }
private Image DrawString(Image BaseImage, string Message, int StartX, int StartY, Color? TC = null) { Color TextColor = TC.HasValue ? TC.Value : Color.Black; int CurX = StartX; int CurY = StartY; Bitmap NewImage = BaseImage.Clone() as Bitmap; using (Graphics g = Graphics.FromImage(NewImage)) { foreach (char c in Message) { if (c == '\n') { CurY += 20; CurX = StartX; } else { FontCharacter cur = Characters[GetValue(c)]; g.DrawImage(cur.GetGlyph(TextColor), new Point(CurX, CurY - cur.CropHeight)); CurX += cur.CropWidth; } } } return NewImage; }
/// <summary> /// Crops and resizes the original image (if necessary) and saves it to disk /// </summary> /// <param name="originalImage">The original image that needs to be cropped/resized</param> /// <param name="savePath">The location for the resized image to be saved - This should be a full physical path including the filename and extension</param> /// <param name="size">A Size object containing the desired width and height of the thumbnail</param> private static void CreateThumbnail(Image originalImage, string savePath, Size size) { Image resized, thumbnail; double originalAspectRatio = (double)originalImage.Width / (double)originalImage.Height; double newAspectRatio = (double)size.Width / (double)size.Height; //this image is already the correct size or is smaller than the requested thumbnail - don't do anything just copy it into the new directory //TODO: should images smaller than requested thumbnail be stretched? if (originalImage.Width == size.Width && originalImage.Height == size.Height) { thumbnail = (Image)originalImage.Clone(); } else if (originalAspectRatio != newAspectRatio) { //if the new thumbnail does not have the same aspect ratio as the source resize first, then crop resized = ResizeImage(originalImage, size); thumbnail = CropImage(resized, size); } else { //the aspect ratio either hasn't changed or is a perfect square so no need to crop resized = ResizeImage(originalImage, size); thumbnail = resized; } thumbnail.Save(savePath); }
private static System.Drawing.Image makeItSquare(System.Drawing.Image imgToResize) { int sourceWidth = imgToResize.Width; int sourceHeight = imgToResize.Height; int startingx, startingy, newwidth, newheight; if (sourceWidth == sourceHeight) { return((System.Drawing.Image)imgToResize.Clone()); } else if (sourceWidth > sourceHeight) { startingx = (sourceWidth - sourceHeight) / 2; startingy = 0; newwidth = sourceHeight; newheight = newwidth; } else { startingx = 0; startingy = (sourceHeight - sourceWidth) / 2; newwidth = sourceWidth; newheight = newwidth; } Bitmap b = new Bitmap(newwidth, newheight); Graphics g = Graphics.FromImage((System.Drawing.Image)b); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgToResize, new Rectangle(0, 0, newwidth, newheight), new Rectangle(startingx, startingy, newwidth, newheight), GraphicsUnit.Pixel); g.Dispose(); return((System.Drawing.Image)b); }
public static System.Drawing.Image HorizontalScale(this System.Drawing.Image self, int newWidth) { System.Drawing.Image reself = (System.Drawing.Image)self.Clone(); reself.FixToOriginalOrientation(); int wSource = reself.Width; int hSource = reself.Height; int wResult = newWidth; int hResult = (hSource * newWidth) / wSource; //Criando Bitmap Bitmap result = new Bitmap(wResult, hResult, reself.PixelFormat); result.SetResolution(reself.HorizontalResolution, reself.VerticalResolution); using (Graphics graphics = Graphics.FromImage(result)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(reself, new Rectangle(0, 0, wResult, hResult), new Rectangle(0, 0, wSource, hSource), GraphicsUnit.Pixel); } return(result); }
public bool HandlePoint(Point point, System.Drawing.Graphics graphics, Image image) { if (IsNowPartitionDrawing) { if (!isPartitionExists) { isPartitionExists = true; LastBitmap = image.Clone() as Bitmap; } if (!isBeginPointSet) { partitionBegin.X = point.X; partitionBegin.Y = point.Y; isBeginPointSet = true; } else { partitionEnd.X = point.X; partitionEnd.Y = point.Y; graphics.DrawLine(new Pen(partitionColor), partitionBegin, partitionEnd); isBeginPointSet = false; return true; } } return false; }
protected override void Execute(CodeActivityContext context) { img = image.Get(context); string fileName = this.FileName.Get(context); try { if (img != null) { } else { Bitmap bit = new Bitmap(fileName); img = bit as System.Drawing.Image; } img_noise = (System.Drawing.Image)img.Clone(); int v = ComputeThresholdValue((Bitmap)img_noise); System.Drawing.Image img_bg = RemoveBg((Bitmap)img_noise, v);//-----------去背景,内存法 Common com = new Common(); imgBged = com.Image2Num((Bitmap)img_bg); _Image.Set(context, img_bg); } catch (Exception e) { SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message); } }
//private static string imgurl; protected override void Execute(CodeActivityContext context) { img = image.Get(context); string fileName = this.FileName.Get(context); Int32 noise = Noise.Get(context); try { if (img != null) { } else { Bitmap bit = new Bitmap(fileName); img = bit as System.Drawing.Image; } System.Drawing.Image img_noise = RemoveNoise((Bitmap)img.Clone(), noise); Common com = new Common(); imgNoised = com.Image2Num((Bitmap)img_noise); // WriteToFile(imgNoised, "experiment\\" + Path.GetFileNameWithoutExtension(imgurl) + "_noised.txt"); _Image.Set(context, img_noise); } catch (Exception e) { SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message); } }
/// <summary> /// Getting the frames out of a GIF image. /// </summary> /// <param name="originalImg"></param> /// <returns></returns> public static BitmapImage[] GetFrames(Image originalImg) { int numberOfFrames = originalImg.GetFrameCount(FrameDimension.Time); Image[] frames = new System.Drawing.Image[numberOfFrames]; BitmapImage[] bitmapFrames = new BitmapImage[numberOfFrames]; for (int i = 0; i < numberOfFrames; i++) { originalImg.SelectActiveFrame(FrameDimension.Time, i); frames[i] = ((System.Drawing.Image)originalImg.Clone()); using (var ms = new MemoryStream()) { frames[i].Save(ms, ImageFormat.Png); ms.Seek(0, SeekOrigin.Begin); var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = ms; bitmapImage.EndInit(); bitmapFrames[i] = bitmapImage; } } return(bitmapFrames); }
/// <summary> /// Construct a ImagePicture from a C# Image object /// </summary> public static ImagePicture FromImage(Image img) { ImagePicture ret = new ImagePicture(); ret.m_img = (Image)img.Clone(); return ret; }
public static Image AppendMouseToDesktop(Image screen, Image cursor, int cursorX, int cursorY) { Image mergedImage = null; Graphics g = null; try { lock (screen) { mergedImage = (Image)screen.Clone(); } Rectangle r; lock (cursor) { r = new Rectangle(cursorX, cursorY, cursor.Width, cursor.Height); } g = Graphics.FromImage(mergedImage); g.DrawImage(cursor, r); g.Flush(); } catch (Exception ex) { throw new Exception(ex.Message, ex); } finally { if (g != null) { g.Dispose(); } } return mergedImage; }
/// <summary> /// Most of the time it just returns a black screen, this is because the game is rendering straight to the /// graphics card using directx and bypassing whatever windows usually uses for PrintWindow /// AFAIK directx screenshots only work if the window is currently visible (not overlaid by the bot itself) /// </summary> /// <returns></returns> public Image<Bgr, byte> TakeScreenshot() { Bitmap frame = new Bitmap(1024, 768); using (Graphics g = Graphics.FromImage(frame)) { IntPtr deviceContextHandle = g.GetHdc(); PrintWindow(GetGameWindowHandle(), deviceContextHandle, 1); g.ReleaseHdc(); } //we have the bitmap now //turn it into an Image for emgu BitmapData bmpData = frame.LockBits(new Rectangle(0, 0, frame.Width, frame.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); Image<Bgr, byte> tempImage = new Image<Bgr, byte>(frame.Width, frame.Height, bmpData.Stride, bmpData.Scan0); //to prevent any corrupted memory errors that crop up for some reason Image<Bgr, byte> image = tempImage.Clone(); frame.UnlockBits(bmpData); //dispose all unused image data to prevent memory leaks frame.Dispose(); tempImage.Dispose(); image.Save("screenshot.png"); return image; }
/// <summary> /// 合并图像 /// </summary> /// <param name="imageBackground"></param> /// <param name="imageForeground"></param> /// <param name="alignment"></param> /// <returns></returns> public static Image CombineImage(Image imageBackground, Image imageForeground, ContentAlignment alignment) { Image imageBk = imageBackground.Clone() as Image; Graphics g = Graphics.FromImage(imageBk); Point point; switch (alignment) { case ContentAlignment.TopLeft: point = new Point(0, 0); break; case ContentAlignment.TopRight: point = new Point(imageBackground.Width - imageForeground.Width, 0); break; case ContentAlignment.BottomLeft: point = new Point(0, imageBackground.Height - imageForeground.Height); break; case ContentAlignment.BottomRight: point = new Point(imageBackground.Width - imageForeground.Width, imageBackground.Height - imageForeground.Height); break; case ContentAlignment.TopCenter: point = new Point(imageBackground.Width / 2 - imageForeground.Width / 2, 0); break; case ContentAlignment.BottomCenter: point = new Point(imageBackground.Width / 2 - imageForeground.Width / 2, imageBackground.Height - imageForeground.Height); break; default: throw new NotSupportedException("Not supported alignment"); } g.DrawImage(imageForeground, point); return imageBk; }
public static Image ToGreyScale(Image Source) { Bitmap grayscale = (Bitmap)Source.Clone(); Rectangle bounds = new Rectangle(0, 0, grayscale.Width, grayscale.Height); ColorMatrix colorMatrix = new ColorMatrix(); int mX = 0; int mY = 0; for (mX = 0; mX <= 2; mX++) { for (mY = 0; mY <= 2; mY++) { colorMatrix[mX, mY] = 0.333333F; } } ImageAttributes imgAttr = new System.Drawing.Imaging.ImageAttributes(); imgAttr.SetColorMatrix(colorMatrix); System.Drawing.Graphics graphics = Graphics.FromImage(grayscale); try { graphics.DrawImage(grayscale, bounds, 0, 0, grayscale.Width, grayscale.Height, System.Drawing.GraphicsUnit.Pixel, imgAttr); } finally { graphics.Dispose(); } return grayscale; }
protected override void Execute(CodeActivityContext context) { img = image.Get(context); string fileName = this.FileName.Get(context); try { if (img != null) { } else { Bitmap bit = new Bitmap(fileName); img = bit as System.Drawing.Image; } imgBinary = (System.Drawing.Image)img.Clone(); imgBinary = Binary((Bitmap)imgBinary); Common com = new Common(); imgBinaried = com.Image2Num((Bitmap)imgBinary); _Image.Set(context, imgBinary); } catch (Exception e) { SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message); } }
public object Clone() { TOCNode tn = new TOCNode(); tn.Identifier = Identifier; tn.Resource = Resource; tn.ResourceIdentifier = ResourceIdentifier; tn.Title = Title; if (Thumbnail != null) { tn.Thumbnail = (Image)Thumbnail.Clone(); } if (Children != null) { tn.Children = (TOCList)Children.Clone(); } if (Extension != null) { if (Extension is ICloneable) { tn.Extension = ((ICloneable)Extension).Clone(); } } return(tn); }
public static Image MergeScreenAndCursor(Image screen, Image cursor, int cursorX, int cursorY) { Image mergedImage; Graphics g = null; try { lock (screen) { mergedImage = (Image)screen.Clone(); } Rectangle r; lock (cursor) { r = new Rectangle(cursorX, cursorY, cursor.Width, cursor.Height); } g = Graphics.FromImage(mergedImage); g.DrawImage(cursor, r); g.Flush(); } finally { if (g != null) { g.Dispose(); } } return mergedImage; }
/// <summary> /// Apply an anti-aliasing algorithm on a Bitmap object /// </summary> /// <param name="_input">A Bitmap to anti-alias</param> /// <returns>The anti-aliased Bitmap</returns> public static Bitmap AntiAliasing(Bitmap _input) { Image<Bgra, Byte> input; Image<Bgra, Byte> outputGaussian; Image<Bgra, Byte> outputGaussianResized; Image<Bgra, Byte> outputThreshold; Image<Bgra, Byte> outputThresholdResized; // Image loading input = new Image<Bgra, Byte>(_input); // Gaussian filter outputGaussian = input.Clone(); for (int i = 1; i < 10; i = i + 2) { CvInvoke.cvSmooth(input, outputGaussian, SMOOTH_TYPE.CV_GAUSSIAN, i, i, 0, 0); } // Resize the image after the Gaussian filter (2 times bigger) outputGaussianResized = new Image<Bgra, Byte>(outputGaussian.Cols * 2, outputGaussian.Rows * 2); CvInvoke.cvResize(outputGaussian, outputGaussianResized, INTER.CV_INTER_CUBIC); // Threshold outputThreshold = outputGaussianResized.Clone(); CvInvoke.cvThreshold(outputGaussianResized, outputThreshold, 127, 255, THRESH.CV_THRESH_BINARY); // Resize the image after the threshold (2 times smaller) outputThresholdResized = new Image<Bgra, Byte>(outputThreshold.Cols / 2, outputThreshold.Rows / 2); CvInvoke.cvResize(outputThreshold, outputThresholdResized, INTER.CV_INTER_CUBIC); // Return the processed image return outputThresholdResized.Bitmap; }
Image[] getFrames(Image originalImg) { int numberOfFrames; FrameDimension TargetDimension; try { numberOfFrames = originalImg.GetFrameCount(FrameDimension.Time); TargetDimension = FrameDimension.Time; } catch { numberOfFrames = originalImg.GetFrameCount(FrameDimension.Page); TargetDimension = FrameDimension.Page; } Image[] frames = new Image[numberOfFrames]; for (int i = 0; i < numberOfFrames; i++) { originalImg.SelectActiveFrame(TargetDimension, i); frames[i] = ((Image)originalImg.Clone()); } return(frames); }
public override Image Watermark(Image img) { img = (Image)img.Clone(); string text = (string)ConfigurationControl.Parameters["Text"]; Font font = (Font)ConfigurationControl.Parameters["Font"]; Color color = (Color)ConfigurationControl.Parameters["Color"]; ContentAlignment align = (ContentAlignment)ConfigurationControl.Parameters["Align"]; int offsetX = (int)ConfigurationControl.Parameters["OffsetX"]; int offsetY = (int)ConfigurationControl.Parameters["OffsetY"]; int trans = (int)ConfigurationControl.Parameters["Transparency"]; using (Graphics g = Graphics.FromImage(img)) { int x, y; Size size = g.MeasureString(text, font).ToSize(); // 计算文本位置 CaculateLocation(img.Size, size, align, offsetX, offsetY, out x, out y); // 计算透明度 0 - 255 之间 int o = (int)((trans / 100.00) * 255); // 创建具有透明度的画刷 Brush b = new SolidBrush(Color.FromArgb(o, color)); // 写水印文字 g.DrawString(text, font, b, new PointF(x, y)); return img; } }
/// <summary> /// Initializes a new instance of <see cref="T:Dataweb.NShape.WinFormsUI.ImageEditor" />. /// </summary> public ImageEditor(Image image, string path) : this() { if (image == null) throw new ArgumentNullException("image"); if (path == null) throw new ArgumentNullException("name"); resultImage.Image = (Image)image.Clone(); resultImage.Name = path; }
//ADDS A CAPTURED FRAME TO A THREAD SAFE QUEUE FOR EASY ACESS WHEN THE FRAME IS PROCESSED BY MULTIPLE FRAMES public bool AddNextFrameToQueueForProcessing() { using (current_frame = FramesManager.GetNextFrame(camera.camera_capture)) { if (current_frame != null) { int width = Singleton.MAIN_WINDOW.GetControl(MainWindow.MainWindowControls.review_image_box).Width; int height = Singleton.MAIN_WINDOW.GetControl(MainWindow.MainWindowControls.review_image_box).Height; Size new_size = new Size(width, height); Singleton.REVIEW_FRAMES_TO_BE_PROCESSED.Enqueue(FramesManager.ResizeColoredImage(current_frame.Clone(), new_size)); return true; } //FRAME IS NULL //MEANING END OF FILE IS REACHED else { //ADD BLACK FRAME TO DATASTORE AND TERMINATE THREAD //ALSO SIGNAL TO OTHERS THAT THIS THREAD IS DONE WORK_DONE = true; running = false; Debug.WriteLine("Terminating video from file"); return false; } } }
/// <summary> /// 复制对象 /// </summary> /// <returns>复制后的对象</returns> public XImageValue Clone() { XImageValue obj = new XImageValue(); if (myValue != null) { obj.myValue = (System.Drawing.Image)myValue.Clone(); } if (bsImage != null) { obj.bsImage = new byte[bsImage.Length]; Array.Copy(bsImage, 0, obj.bsImage, 0, bsImage.Length); } obj._ContentVersion = this._ContentVersion; return(obj); }
private void button2_Click(object sender, EventArgs e) { var kernel = new double[, ] { { 0.1, 0.1, 0.1 }, { 0.1, 0.1, 0.1 }, { 0.1, 0.1, 0.1 } }; var imag = (Bitmap)image.Clone(); const double scale = 9; byte[,] mask3 = new byte[, ] { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }; //Convolution(imag, kernel); pictureBox2.Image = Filter33(imag, mask3, scale); }
private void webcam_ImageCaptured(object source, WebcamEventArgs e) { lock (_image) { _image = e.WebCamImage; _frameImage.Image = _image.Clone() as Image; } }
public SShotCaptured(Image img, bool isShowPath, string path) { InitializeComponent(); this.isautosave = isShowPath; this.pictureBox1.Image = (Image)img.Clone(); if (isShowPath) this.textBox1.Text = path; else { this.label1.Text = "스크린샷이 캡춰되었습니다"; this.Size = new Size(385, this.Size.Height); } }
public MainWindow(Image image) { singleWindow = false; doubleWindowMode = false; modeButtonMode = true; InitializeComponent(); pBox.Image = (Image)image.Clone(); }
public void FloodFill(Image currentImage, Color fillColor, Color polygonColor, Color backColor, Point fillStartPoint) { LastBitmap = currentImage.Clone() as Bitmap; FloodFillContext context = new FloodFillContext(currentImage as Bitmap, data, fillStartPoint, polygonColor, fillColor, backColor); CreateWorker(context.bitmap); floodFillerStrategy.SlowMode = _EnableSlowing; worker.RunWorkerAsync(context); }
public void Process(Image<Bgr, byte> image2) { _width = image2.Width; _height = image2.Height; _image = image2.Clone(); var t = new Thread(ProcessImage); t.Start(); }
//ADDS A CAPTURED FRAME TO THREAD SAFE QUEUES //FOR EASY ACESS WHEN THE FRAME IS PROCESSED BY MULTIPLE THREADS LATER public bool AddNextFrameToQueuesForProcessing() { //get next frame from camera current_frame = FramesManager.GetNextFrame(camera_capture); if (current_frame != null) { int new_width = Singleton.MAIN_WINDOW.GetControl(MainWindow.MainWindowControls.live_stream_image_box1).Width; int new_height = Singleton.MAIN_WINDOW.GetControl(MainWindow.MainWindowControls.live_stream_image_box1).Height; Size new_size = new Size(new_width,new_height); //add frame to queue for display Singleton.LIVE_FRAMES_TO_BE_DISPLAYED.Enqueue(FramesManager.ResizeColoredImage(current_frame.Clone(), new_size)); //add frame to queue for storage Singleton.FRAMES_TO_BE_STORED.Enqueue(current_frame.Clone()); //resize frame to save on memory and improve performance int width = Singleton.MAIN_WINDOW.GetControl(MainWindow.MainWindowControls.review_image_box).Width; int height = Singleton.MAIN_WINDOW.GetControl(MainWindow.MainWindowControls.review_image_box).Height; Size size = new Size(width,height); current_frame = FramesManager.ResizeColoredImage(current_frame,size); //add frame to queue for face detection and recognition Singleton.LIVE_FRAMES_TO_BE_PROCESSED.Enqueue(current_frame.Clone()); //return return true; } //FRAME IS NULL //MEANING END OF FILE IS REACHED else { //ADD BLACK FRAME TO DATASTORE AND TERMINATE THREAD //ALSO SIGNAL TO OTHERS THAT THIS THREAD IS DONE WORK_DONE = true; running = false; Debug.WriteLine("Terminating camera output"); return false; } }
private CvBlobs GetBlobs(Image<Gray, Byte> img) { Image<Gray, Byte> im = img.Clone(); im._Dilate(2); im._Erode(2); CvBlobs blobs = new CvBlobs(); detector.Detect(im, blobs); return blobs; }
public static Image CreateFilteredImage(Image image) { if (image == null) throw new ArgumentNullException("image"); Bitmap img = image.Clone() as Bitmap; BitmapProcessing.AdjustOpacity(img, TreeNode.FilteredNodeOpacity); return img; }
public bool BallTracking(System.Drawing.Image newFrame) { if (newFrame == null) { return(false); } Bitmap cleanImage = (Bitmap)newFrame.Clone(); Bitmap trackingImage = (Bitmap)newFrame.Clone(); _hslFilter.ApplyInPlace(trackingImage); //_jitterFilter.ApplyInPlace(trackingImage); //_contrastFilter.ApplyInPlace(trackingImage); _blobFilter.ApplyInPlace(trackingImage); _blobCounter.ProcessImage(trackingImage); _rectangles = _blobCounter.GetObjectsRectangles(); if (DrawBoxes) { using (Pen pen = new Pen(Color.Red, 2)) using (Graphics t = Graphics.FromImage(trackingImage)) using (Graphics c = Graphics.FromImage(cleanImage)) { foreach (Rectangle rect in _rectangles) { t.DrawRectangle(pen, rect); c.DrawRectangle(pen, rect); } } } _colorImage = cleanImage; _trackingImage = trackingImage; if (NewCameraImage != null) { NewCameraImage(this, new EventArgs()); } return(true); }
public Bitmap GrayScale(System.Drawing.Image imgOrigin) { Bitmap bmp = (Bitmap)imgOrigin.Clone(); Grayscale _filterGray = new Grayscale(0.2125, 0.7154, 0.0721); Threshold filter = new Threshold(100); //filter.ApplyInPlace(bmp); bmp = _filterGray.Apply(bmp); return(bmp); }
/// <summary> /// Initializes a new instance of the <see cref="PdfImage"/> class from image with optional image configuration. /// </summary> /// <param name="image">A reference to image object.</param> /// <param name="configuration">Image configuration reference.</param> internal PdfImage(NativeImage image, PdfImageConfig configuration = null) { var safeConfiguration = configuration; if (configuration == null) { safeConfiguration = PdfImageConfig.Default; } Path = null; Configuration = safeConfiguration.Clone(); OriginalImage = (NativeImage)image.Clone(); var concreteOriginalImage = (Bitmap)image.Clone(); if (Configuration.UseTransparentBackground) { if (Configuration.TransparentColor.Equals(PdfImageConfig.DefaultColor, StringComparison.OrdinalIgnoreCase)) { Configuration.SetParentImage(concreteOriginalImage); } concreteOriginalImage.MakeTransparent(Configuration.GetColor()); } NativeImage processedImage = (NativeImage)concreteOriginalImage.Clone(); if (Configuration.Effects != null) { processedImage = (NativeImage)concreteOriginalImage.ApplyEffects(Configuration.Effects).Clone(); } ProcessedImage = (NativeImage)processedImage.Clone(); ScaledHeight = processedImage.Height; ScaledWidth = processedImage.Width; Image = NativePdfImage.GetInstance(ProcessedImage, ImageFormat.Png); IsValid = true; }
public static Bitmap ConvertToBitmap(MagickImage image) { Bitmap test; using (MemoryStream memoryStream = new MemoryStream()) { image.Write(memoryStream, MagickFormat.Png32); memoryStream.Position = 0; Image temp = Image.FromStream(memoryStream); test = (Bitmap)temp.Clone(); } return(test); }
public void AddWatermark(string backgroundImagePath, string watermarkPath) { System.Drawing.Image backImage = Image.FromFile(backgroundImagePath); System.Drawing.Image waterImage = Image.FromFile(watermarkPath); Graphics g = Graphics.FromImage(backImage); g.SmoothingMode = SmoothingMode.AntiAlias; g.DrawImage(waterImage, backImage.Width * 4 / 5, 10, backImage.Width / 5, backImage.Height / 9); Bitmap layoutImageToBitmap = backImage.Clone() as Bitmap; if (System.IO.File.Exists("5.png")) { System.IO.File.Delete("5.png"); } layoutImageToBitmap.Save("5" + ".png", ImageFormat.Png); }
private void MenuLoad_Click(object sender, RoutedEventArgs e) { filePath = GetFilePath(); if (filePath != null) { loadedImage = Image.FromFile(filePath); edittedImage = loadedImage.Clone() as System.Drawing.Image; BitmapSource source = GetImageSource(edittedImage); ImageControl.Source = source; fileName = Path.GetFileNameWithoutExtension(filePath); fileNameExtension = Path.GetExtension(filePath); fileDirectory = Path.GetDirectoryName(filePath); } }
private void SetNewVideoImage() { if (arDroneControl.IsConnected) { System.Drawing.Image newImage = arDroneControl.GetDisplayedImage(); if (newImage != null) { frameCountSinceLastCapture++; if (videoRecorder.IsVideoCaptureRunning) { videoRecorder.AddFrame((System.Drawing.Bitmap)newImage.Clone()); } pictureBoxVideo.Image = newImage; } } }
////public Rectangle[] EasyWay(System.Drawing.Image original) ////{ //// // create an instance of blob counter algorithm //// BlobCounter bc = new BlobCounter(); //// // process binary image //// bc.ProcessImage((Bitmap)original); //// Rectangle[] rects = bc.GetObjectsRectangles(); //// // process blobs //// return rects; ////} public List <Square> SquareExtraction(System.Drawing.Image original) { this.Squares = new List <Square>(); Bitmap image = (Bitmap)original.Clone(); int width = image.Width - 1; int height = image.Height - 1; _commonController.ToBlackWhite(ref image, width, height); for (int y = 1; y < height; y++) { for (int x = 1; x < width; x++) { ValidadeMasks((Bitmap)original, y, x); } } return(Squares); }
/// <summary> /// Redimensiona uma imagem tornando-a "quadrada" cortando as sobras em direção do centro /// </summary> /// <param name="self">Imagem a ser redimensionada</param> /// <param name="newSize">Tamanho dos lados da imagem</param> /// <returns>A imagem redimensionada</returns> public static System.Drawing.Image ToSquare(this System.Drawing.Image self, int newSize) { System.Drawing.Image reself = (System.Drawing.Image)self.Clone(); reself.FixToOriginalOrientation(); int wSource = reself.Width; int hSource = reself.Height; int wResult = 0; int hResult = 0; if (wSource <= hSource) { wResult = newSize; hResult = newSize * hSource / wSource; } else { hResult = newSize; wResult = newSize * wSource / hSource; } int xResult = (newSize - wResult) / 2; int yResult = (newSize - hResult) / 2; //Criando Bitmap Bitmap result = new Bitmap(newSize, newSize, self.PixelFormat); result.SetResolution(reself.HorizontalResolution, reself.VerticalResolution); using (Graphics graphics = Graphics.FromImage(result)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(reself, new Rectangle(xResult, yResult, wResult, hResult), new Rectangle(0, 0, wSource, hSource), GraphicsUnit.Pixel); } return(result); }
protected override void Execute(CodeActivityContext context) { string fileName = this.FileName.Get(context); img = image.Get(context); try { if (img != null) { } else { Bitmap bit = new Bitmap(fileName); img = bit as System.Drawing.Image; } System.Drawing.Image img_grey = (System.Drawing.Image)img.Clone(); Common com = new Common(); string imgOriginal = com.Image2Num((Bitmap)img_grey); graytype = 2; if (_max) { graytype = 1; } if (_quanzhong) { graytype = 3; } img_grey = Gray((Bitmap)img_grey, graytype); imgGreied = com.Image2Num((Bitmap)img_grey); _Image.Set(context, img_grey); } catch (Exception e) { SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message); } }
/// <summary> /// 获取运行目录下的图片文件,以第一张图片作为身份照 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public Bitmap getStartPathImage(ref string filePath) { Bitmap bmp = null; try { string[] files = Directory.GetFiles(System.Windows.Forms.Application.StartupPath, "*.*", SearchOption.AllDirectories) .Where(s => s.ToLower().EndsWith(".bmp") || s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".png")).ToArray(); if (files != null && files.Length > 0) { filePath = files[0]; using (System.Drawing.Image tempBmp = CommonUtil.ReadFromFile(filePath)) { bmp = (Bitmap)tempBmp.Clone(); } } } catch (Exception ex) { LogUtil.LogInfo(GetType(), ex); } return(bmp); }
public static Bitmap PrepareForObjectDetection(this System.Drawing.Image bmpOriginalImage, int whiteLevel, bool overrideWhite) { Bitmap bmp = (Bitmap)bmpOriginalImage.Clone(); ColorFiltering colorFilter = new ColorFiltering(); int white = whiteLevel; if (!overrideWhite) { white = PreprocessingHelper.GetWhiteLevel(bmp); } colorFilter.Red = new IntRange(0, white / 3); colorFilter.Green = new IntRange(0, white / 3); colorFilter.Blue = new IntRange(0, white / 3); colorFilter.FillOutsideRange = true; colorFilter.FillColor = new RGB(Color.White); colorFilter.ApplyInPlace(bmp); ExtractChannel extract_channel = new ExtractChannel(0); bmp = extract_channel.Apply(bmp); Invert invert = new Invert(); invert.ApplyInPlace(bmp); Threshold threshholdFilter = new Threshold(10); threshholdFilter.ApplyInPlace(bmp); bmp = bmp.Clone(new Rectangle(0, 0, bmp.Width, bmp.Height), PixelFormat.Format24bppRgb); return(bmp); }