Click here to Skip to main content
Click here to Skip to main content

Cropping Particular Region In Image Using C#

, 29 Dec 2013
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

furkanavcu
Student University Of Kocaeli
Turkey Turkey
I am student University of Kocaeli and my department is Electronics and Telecommunication Engineering. It's my last year. So my interests are software developing and hardware developing for embedded platform.

Comments and Discussions

 
QuestionTouch PinmemberMember 106521307-Mar-14 9:42 
AnswerRe: Touch Pinprofessionalfurkanavcu7-Mar-14 13:06 
Questionasking about the picture that v r cropping. PinmemberYasir Babar1-Mar-14 23:20 
AnswerRe: asking about the picture that v r cropping. Pinprofessionalfurkanavcu2-Mar-14 0:09 
GeneralRe: asking about the picture that v r cropping. PinmemberYasir Babar2-Mar-14 5:45 
GeneralRe: asking about the picture that v r cropping. Pinprofessionalfurkanavcu2-Mar-14 13:26 
GeneralMy vote 5 PinmemberNawaz3437-Jan-14 22:19 
GeneralRe: My vote 5 Pinprofessionalfurkanavcu7-Jan-14 22:36 
GeneralMy vote of 1 PinmemberBurhan665-Jan-14 23:08 
GeneralRe: My vote of 1 PinmemberPhil Atkin6-Jan-14 0:25 
GeneralRe: My vote of 1 Pinprofessionalfurkanavcu6-Jan-14 1:28 
GeneralRe: My vote of 1 Pinprofessionalfurkanavcu6-Jan-14 1:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 30 Dec 2013
Article Copyright 2013 by furkanavcu
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid