Click here to Skip to main content
12,763,466 members (32,683 online)
Click here to Skip to main content
Add your own
alternative version


38 bookmarked
Posted 29 Dec 2013

Cropping Particular Region In Image Using C#

, 29 Dec 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Image Cropping GUI For General Purpose


       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.<o:p />  

Figure-1: Crop particular region of image GUI <o:p />


     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.<o:p />

     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.<o:p /> 

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.   <o:p />   

//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]);
        // in this point we can undo easily, with pushing mouse right click
        case MouseButtons.Right:

            if (polygonPoints.Count > 0)
    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()
            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);
            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; ;

   // 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.<o:p /> 

// 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);
// 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<o:p /> 

     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. 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

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.

You may also be interested in...


Comments and Discussions

Praisethanks Pin
zhixiang_xue25-Apr-16 15:36
memberzhixiang_xue25-Apr-16 15:36 
GeneralRe: thanks Pin
furkanavcu7-Aug-16 12:10
professionalfurkanavcu7-Aug-16 12:10 
Questioncropping pdf Pin
Member 1237717515-Mar-16 1:04
memberMember 1237717515-Mar-16 1:04 
AnswerRe: cropping pdf Pin
furkanavcu29-Mar-16 9:09
professionalfurkanavcu29-Mar-16 9:09 
QuestionHow to change the background color of cropped images Pin
Member 121874728-Dec-15 7:12
memberMember 121874728-Dec-15 7:12 
QuestionJavascript version Pin
juan antonio ortega26-Jun-15 1:08
memberjuan antonio ortega26-Jun-15 1:08 
AnswerRe: Javascript version Pin
furkanavcu26-Jun-15 9:44
professionalfurkanavcu26-Jun-15 9:44 
GeneralMy vote of 3 Pin
BillWoodruff21-Nov-14 5:17
professionalBillWoodruff21-Nov-14 5:17 
QuestionTouch Pin
Member 106521307-Mar-14 10:42
memberMember 106521307-Mar-14 10:42 
AnswerRe: Touch Pin
furkanavcu7-Mar-14 14:06
professionalfurkanavcu7-Mar-14 14:06 
Questionasking about the picture that v r cropping. Pin
Yasir Babar2-Mar-14 0:20
memberYasir Babar2-Mar-14 0:20 
AnswerRe: asking about the picture that v r cropping. Pin
furkanavcu2-Mar-14 1:09
professionalfurkanavcu2-Mar-14 1:09 
GeneralRe: asking about the picture that v r cropping. Pin
Yasir Babar2-Mar-14 6:45
memberYasir Babar2-Mar-14 6:45 
GeneralRe: asking about the picture that v r cropping. Pin
furkanavcu2-Mar-14 14:26
professionalfurkanavcu2-Mar-14 14:26 
GeneralMy vote 5 Pin
Nawaz3437-Jan-14 23:19
memberNawaz3437-Jan-14 23:19 
GeneralRe: My vote 5 Pin
furkanavcu7-Jan-14 23:36
professionalfurkanavcu7-Jan-14 23:36 
GeneralMy vote of 1 Pin
Burhan666-Jan-14 0:08
memberBurhan666-Jan-14 0:08 
GeneralRe: My vote of 1 Pin
Phil Atkin6-Jan-14 1:25
memberPhil Atkin6-Jan-14 1:25 
GeneralRe: My vote of 1 Pin
furkanavcu6-Jan-14 2:28
professionalfurkanavcu6-Jan-14 2:28 
GeneralRe: My vote of 1 Pin
furkanavcu6-Jan-14 2:09
professionalfurkanavcu6-Jan-14 2:09 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 30 Dec 2013
Article Copyright 2013 by furkanavcu
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid