Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Cropping Particular Region In Image Using C#

0.00/5 (No votes)
29 Dec 2013 1  
Image Cropping GUI For General Purpose

Introduction 

       Firstly,  I have to explain why we need this method to crop an image. I prepared and coded this simple application GUI for my requirement, because in our big project we need to focus some region of image that we’re interested in.  So when I start to investigate this requirement and how to do this, I have met only rectangular, circle or square region to crop image. If region that we’re interested in is not rectangular, square, circle etc , what we have to do? We should be able to choose all of points of our region in image.  After now, you can crop particular area in image that you want.  

Figure-1: Crop particular region of image GUI 

Background 

     Firstly, I have to explain the GUI. In this article, i share a screenshot of image crop GUI application. As you see the figure-1, we have to determine which area of our image sample. In this sample, we choose with a piece of wood on the rock in the lake and we want to seperate this image as two parts. One is only piece of wood on the rock and the other is just the sample of image. As you see, labeled as cropped image is one and labeled as original image is the other.  The picturebox is labeled as the name of image is the field to choose crop points. Of course you have to choose the image that you want crop with open option from file menu strip. As you can see the red lines is consist of points choosed with mouse click. At the above GUI screen, the crop button is to serve creating cropped image after you select the points. If you don’t like that you select point, maybe you swapped your hand, the undo button serves you to undo your selection and to provide select true points. You can choose this functions from the options menu strip, and you can save the cropped image to use save option from file menu strip. The mouse points textbox shows the coordinates of your mouse in the image and the polygon points textbox shows you maximum and minumum points that you’ll create.

     Let’s explain some methods to understand this simple GUI application. At the background, we use so simple method to crop image. We use so popular method of image processing is masking two images. Source image is the original image and the second one is  just only full of black image( the black image has rgb values are ‘0’) has same size with original image. But the tip of method is the polygon is formed by points that we choose. We have no just black image has rgb values are ‘0’, only inside the polygon has rgb values are ‘1’. And we multiply (mask) this two image, we have cropped image. So that’s it, it is so simple. 

Using the code

      The codes are seperated two main parts. One of them is choosing polygonpoints, we use pictureBox1_Mouse_Click() event and pictureBox1_MouseMove() event. MouseMove event serves us to know which coordinates value that we are, when we drag mouse cursor on the picturebox that contains our image. MouseClick event serves us to add polygon points with clicking mouse left button, and we can undo with clicking mouse right button. We need  some temp variables to draw polygon.      

        //to choose points of crop region
        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            switch (e.Button)
            {
                case MouseButtons.Left:

                    temp_point = new System.Drawing.Point(e.X, e.Y);
                    temp_count = polygonPoints.Count;
                    polygonPoints.Add(new System.Drawing.Point(e.X, e.Y));
                    if (polygonPoints.Count > 1)
                    {
                        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                        temp_im = bmp.Clone(rect, PixelFormat.Format24bppRgb);
                        this.DrawLine(polygonPoints[polygonPoints.Count - 2], polygonPoints[polygonPoints.Count - 1]);
                    }
                    break;
                // in this point we can undo easily, with pushing mouse right click
                case MouseButtons.Right:

                    if (polygonPoints.Count > 0)
                    {
                        undo();
                    }
                    break;
            }
            pictureBox1.Image = bmp;
        } 

     The second main part is crop() method that we crop region of image. We fill rectangle first to create black image has same size with the original image and fill ‘1’ rgb values inside the polygon. After of that, we multiply two images with using Cv.Mul(CvArr src1,CvArr src2, CvArr dst, double scale) method.  

         private void crop()
        {
            timer1.Stop();
            IplImage accc = Cv.CreateImage(new CvSize(bmp.Width, bmp.Height), BitDepth.U8, 3);

            Graphics Ga = Graphics.FromImage(bmp);
            //the black image
            Ga.FillRectangle(new SolidBrush(Color.Black), new Rectangle(0, 0, bmp.Width, bmp.Height));
            //draw from the last point to first point  
            Ga.DrawLine(new Pen(Color.Red, 3), polygonPoints[polygonPoints.Count - 1], polygonPoints[0]);

            //all of the rgb values are being set 1 inside the polygon 
            SolidBrush Brush = new SolidBrush(Color.FromArgb(1, 1, 1));
          //we have to prepare one mask of Multiplying operation for cropping region
            G.FillClosedCurve(Brush, polygonPoints.ToArray());
            Cv.Mul(BitmapToIplImage(Source), BitmapToIplImage(bmp), accc, 1);
           
            computecrop();
            croplast = accc.ToBitmap().Clone(rectcrop, Source.PixelFormat);//just show cropped region part of image
            pictureBox2.Image = croplast; // crop region of image

        } 

     Of course, we need a method to convert from bitmap to IplImage so BitmapToIplImage(Bitmap src) method works for this purpose.   

        // we have to conversion from bitmap to IplImage to use OpenCvSharp methods
        public static IplImage BitmapToIplImage(Bitmap bitmap)
        {
            IplImage tmp, tmp2;

            Rectangle bRect = new Rectangle(new System.Drawing.Point(0, 0), new Size((int)bitmap.Width, (int)bitmap.Height));
            BitmapData bmData = bitmap.LockBits(bRect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
            tmp = Cv.CreateImage(Cv.Size(bitmap.Width, bitmap.Height), BitDepth.U8, 3);
            tmp2 = Cv.CreateImage(Cv.Size(bitmap.Width, bitmap.Height), BitDepth.U8, 1);
            tmp.ImageData = bmData.Scan0; ;

            bitmap.UnlockBits(bmData);
           // Cv.CvtColor(tmp, tmp2, ColorConversion.RgbToGray);
            return tmp;
        } 

     And then, we have to use some refresh method to free ram and to use some temp variables. The temp variables are for using graphics class methods and create masking object to multiply two images. 

        // we have refresh some assignments operators for new image or cropping new region
        private void first_refresh_im()
        {
            Rectangle rect = new Rectangle(0, 0, resim.Width, resim.Height);
            resimi = resim.ToBitmap() ;
            bmp = resimi.Clone(rect, resimi.PixelFormat);
            Source = resimi.Clone(rect, resimi.PixelFormat);
            pictureBox1.Image = bmp;
            G = Graphics.FromImage(bmp);
            polygonPoints.Clear();
        }
        // when we undo point of region, we have to create new rectangular object with using ex-points
        // and we have to need new bmp Source object
        private void refresh_im()
        {
            Rectangle rect = new Rectangle(0, 0, resim.Width, resim.Height);
            bmp = resimi.Clone(rect, resimi.PixelFormat);
            Source = resimi.Clone(rect, resimi.PixelFormat);
            pictureBox1.Image = bmp;

        } 

Points of Interest

     I hope this GUI would be useful for people who interested in image processing methods. I used some opencvsharp methods, because in image processing implementations most of people use this library and source codes. This article will able to use first level tutorial of opencvsharp simple methods for people.   

Conclusion 

     In this article, we learned some image processing methods and how to use those in .NET platform and we already met opencvsharp methods. After now, we don’t need some other programs for just a particular area image cropping processes. And we can crop particular region in a image that we want, not only rectangular, square, circle shapes. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here