Click here to Skip to main content
15,880,608 members
Articles / Programming Languages / C#

Cropping Particular Region In Image Using C#

Rate me:
Please Sign up or sign in to vote.
4.64/5 (33 votes)
29 Dec 2013CPOL4 min read 97K   14.2K   45   24
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.<o:p>  

Image 1

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

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.<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>   

C#
//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.  

C#
         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.   

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

C#
// 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<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. 

License

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


Written By
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

 
PraiseImage cropping Pin
sohail naseer29-Dec-19 7:51
sohail naseer29-Dec-19 7:51 
Questionharika proje Pin
Member 1431545418-Apr-19 3:41
Member 1431545418-Apr-19 3:41 
PraiseGood Article Pin
Shailesh vora8-Jun-18 0:59
Shailesh vora8-Jun-18 0:59 
Praisethanks Pin
zhixiang_xue25-Apr-16 14:36
zhixiang_xue25-Apr-16 14:36 
GeneralRe: thanks Pin
furkanavcu7-Aug-16 11:10
professionalfurkanavcu7-Aug-16 11:10 
Questioncropping pdf Pin
Member 1237717515-Mar-16 0:04
Member 1237717515-Mar-16 0:04 
AnswerRe: cropping pdf Pin
furkanavcu29-Mar-16 8:09
professionalfurkanavcu29-Mar-16 8:09 
QuestionHow to change the background color of cropped images Pin
Member 121874728-Dec-15 6:12
Member 121874728-Dec-15 6:12 
QuestionJavascript version Pin
juan antonio ortega26-Jun-15 0:08
juan antonio ortega26-Jun-15 0:08 
AnswerRe: Javascript version Pin
furkanavcu26-Jun-15 8:44
professionalfurkanavcu26-Jun-15 8:44 
GeneralMy vote of 3 Pin
BillWoodruff21-Nov-14 4:17
professionalBillWoodruff21-Nov-14 4:17 
QuestionTouch Pin
Member 106521307-Mar-14 9:42
Member 106521307-Mar-14 9:42 
AnswerRe: Touch Pin
furkanavcu7-Mar-14 13:06
professionalfurkanavcu7-Mar-14 13:06 
Questionasking about the picture that v r cropping. Pin
Yasir Babar1-Mar-14 23:20
Yasir Babar1-Mar-14 23:20 
AnswerRe: asking about the picture that v r cropping. Pin
furkanavcu2-Mar-14 0:09
professionalfurkanavcu2-Mar-14 0:09 
GeneralRe: asking about the picture that v r cropping. Pin
Yasir Babar2-Mar-14 5:45
Yasir Babar2-Mar-14 5:45 
GeneralRe: asking about the picture that v r cropping. Pin
furkanavcu2-Mar-14 13:26
professionalfurkanavcu2-Mar-14 13:26 
GeneralMy vote 5 Pin
Nawaz3437-Jan-14 22:19
Nawaz3437-Jan-14 22:19 
GeneralRe: My vote 5 Pin
furkanavcu7-Jan-14 22:36
professionalfurkanavcu7-Jan-14 22:36 
GeneralMy vote of 1 Pin
Burhan665-Jan-14 23:08
Burhan665-Jan-14 23:08 
Everybody can use OpenCV. This article is not good enough to be published. If you have an algorithm to crop image parts then it could be valuable enough to publish.
GeneralRe: My vote of 1 Pin
Phil Atkin6-Jan-14 0:25
Phil Atkin6-Jan-14 0:25 
GeneralRe: My vote of 1 Pin
furkanavcu6-Jan-14 1:28
professionalfurkanavcu6-Jan-14 1:28 
GeneralRe: My vote of 1 Pin
furkanavcu6-Jan-14 1:09
professionalfurkanavcu6-Jan-14 1:09 
GeneralRe: My vote of 1 Pin
Shailesh vora8-Jun-18 0:58
Shailesh vora8-Jun-18 0:58 

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.