Using Visual C # to complete basic Digital image processing

Source: Internet
Author: User
Tags filter bool exit contains file system range save file visual studio
Visual

A Overview:

The example of this article is a Digital image processing application, it completes the function includes the image color flip, to the image gray processing and to the image brightening processing. This program to the image processing part of the code included in a special filters class, by calling the class of static member functions, we can implement the corresponding image processing functions. In order to realize the image processing, we should do pixel-by-image processing. We know that the image is made up of pixel points, each pixel of an image is processed accordingly, and finally the whole image is processed. In this process, we only need to deal with each pixel point, in the process of processing but do not need to consider the impact of the surrounding pixels, so relatively speaking, the implementation of the program becomes much simpler.

Because the BitmapData class in GDI + does not provide direct access to the internal data of the image, our only way is to use the pointer to get the internal data of the image, and then we have to use the unsafe keyword to indicate the code block in the function that accesses the image's internal data. In the program, I also use the open file and save the file options, so that our hard work is not in vain.

Two Implementation of the program:

1. Open Visual Studio.NET, create a new project for Visual C #, select Windows application in the template, and the project name can be customized (here is imageprocessor).

2. To enable the form to display an image, we need to overload the form's OnPaint () event function, where we draw an image on the main form of the program, so that the form can display images of different sizes, and we also set the form's AutoScroll property to True. This way, depending on the size of the image, the corresponding scroll bar appears on both sides of the form. The implementation of this function is as follows:

private void Form1_paint (object sender, System.Windows.Forms.PaintEventArgs e) {Graphics g = e.graphics; G.drawimage (m_b Itmap, New Rectangle (this. Autoscrollposition.x, this. AUTOSCROLLPOSITION.Y, (int) (m_bitmap.width), (int) (m_bitmap.height)); }


3. Add a main menu to the main form, which completes some basic operations, including "Open File", "Save File", "Exit", "Flip Operation", "Grayscale operation", "brightening operation", and so on. The previous three operations complete the image file open and save and the program Exit function, the corresponding event handler function is as follows:

private void Menuitemopen_click (object sender, System.EventArgs e) {OpenFileDialog OpenFileDialog = new OpenFileDialog () ; Openfiledialog.filter = "Bitmap file (*.bmp) |*.bmp| JPEG file (*.jpg) |*.jpg| All appropriate documents (*.bmp/*.jpg) |*.bmp/*.jpg "; Openfiledialog.filterindex = 2; Openfiledialog.restoredirectory = true; if (DialogResult.OK = = Openfiledialog.showdialog ()) {M_bitmap = (Bitmap) bitmap.fromfile (Openfiledialog.filename, FALSE); This. AutoScroll = true; This. Autoscrollminsize=new Size ((int) (m_bitmap.width), (int) m_bitmap.height)); This. Invalidate (); } }


Where M_bitmap is a data member of the main form class, declared as Private System.Drawing.Bitmap m_bitmap; (Note: Because the program uses related classes, you should add a using at the beginning of the program file System.Drawing.Imaging) at the same time, in the constructor of the class, we must first give it a new Bitmap object: M_bitmap = new Bitmap (2,2), and this in the preceding code. Invalidate () completes the redraw of the main form, calling the OnPaint () function of the main form, which displays the open image file on the main form.

private void Menuitemsave_click (object sender, System.EventArgs e) {SaveFileDialog SaveFileDialog = new SaveFileDialog () ; Savefiledialog.filter = "Bitmap file (*.bmp) |*.bmp| JPEG file (*.jpg) |*.jpg| All appropriate documents (*.bmp/*.jpg) |*.bmp/*.jpg "; Savefiledialog.filterindex = 1; Savefiledialog.restoredirectory = true; if (DialogResult.OK = = Savefiledialog.showdialog ()) {m_bitmap.save (savefiledialog.filename);}}


Which M_bitmap.save (savefiledialog.filename), a sentence completed the preservation of the image file, it is the use of GDI + 's powerful function, we need a simple statement on the completion of the previous task of heavy workload, so reasonable use. NET is bound to simplify our work greatly.

private void Menuitemexit_click (object sender, System.EventArgs e) {this. Close (); }


Next, the event handler functions for the three main operations are as follows:

private void Menuiteminvert_click (object sender, System.EventArgs e) {if (Filters.invert (M_bitmap)) this. Invalidate (); } private void Menuitemgray_click (object sender, System.EventArgs e) {if (Filters.gray (M_bitmap)) this. Invalidate (); } private void Menuitembright_click (object sender, System.EventArgs e) {Parameter dlg = new Parameter (); dlg.nvalue = 0; if (DialogResult.OK = = dlg. ShowDialog ()) {if (Filters.brightness (M_bitmap, Dlg.nvalue)) this. Invalidate (); } }


In three functions, the corresponding image processing function (invert), Gray (), brightness () and other three functions are called respectively. These three functions filters static functions (with the static keyword) that are public in the class, and their return value types are bool, and we can decide whether to redraw the main form based on the return value.

Invert (), Gray (), brightness () and other three functions are included in the filters class, the Invert () function of the algorithm is as follows:

public static bool Invert (Bitmap b) {BitmapData bmdata = b.lockbits (new Rectangle (0, 0, B.width, b.height), imagelockm Ode. ReadWrite, Pixelformat.format24bpprgb); int stride = Bmdata.stride; System.IntPtr Scan0 = bmdata.scan0; unsafe {byte * p = (byte *) (void *) Scan0 int noffset = stride-b.width*3; int nwidth = B.width * 3; for (int y=0;y<b. Height;++y) {for (int x=0; x < nwidth; ++x) {p[0] = (byte) (255-p[0)); ++p;} p + = Noffset;} B.unlockbits (Bmdata); return true; } 


The functions and the parameters of the subsequent functions are bitmap types, and the objects that pass the value are the image files that are opened in the program. The bmdata of the BitmapData type in this function contains the internal information of the image file, and the Stride property of the Bmdata indicates the width of a line, and its Scan0 property is a pointer to the internal information of the image. This function completes the function is the image color rollover, realizes the method namely uses 255 to subtract the image each pixel point the value, and sets the value to the original pixel point the value, carries on the operation to each pixel point, only then the entire image all processing completes. The unsafe code block in the function is the main part of the whole function, first we get the pointer to the internal data of the image, then set the offset, and set the nwidth as B.width*3, because each pixel contains three color components, each pixel point is processed three times. Next, we use two nested for loops to finish processing each pixel, and the core of the processing is one sentence: p[0] = (byte) (255-p[0);. After unsafe the code block, B can be used. Unlockbits (Bmdata) for the release of image resources. The function succeeds, and finally returns a true value. Note: Because you are compiling unsafe code, you must set the "Allow unsafe code block" property in the Project property page to True, as shown here:

The program effect of this function is as follows:

(Before processing)

(after processing)

The algorithm for the Gray () function is as follows:

public static bool Gray (Bitmap b) {BitmapData bmdata = b.lockbits (new Rectangle (0, 0, B.width, b.height), IMAGELOCKMODE.R Eadwrite, Pixelformat.format24bpprgb); int stride = Bmdata.stride; System.IntPtr Scan0 = bmdata.scan0; unsafe {byte * p = (byte *) (void *) Scan0 int noffset = stride-b.width*3; byte red, green, blue; for (int Y=0;y<b.hei Ght;++y) {for (int x=0; x < b.width; ++x) {blue = p[0]; green = p[1]; red = p[2]; p[0] = p[1] = p[2] = (byte) (. 299 * Red +. 587 * green +. 114 * Blue); p = 3; p + + Noffset; } b.unlockbits (Bmdata); return true; }


The function is to perform grayscale processing of the image, and our basic idea is to average the values of the three color components of each pixel point. However, due to the sensitivity of the human eye, such a complete average of the practice is not good, so in the program I took three best results of the parameters:. 299,.587,.114. However, to indicate to the reader here that the format of the image store in GDI + is BGR rather than RGB, which is the order: Blue, Green, Red. So in the For loop must set a good red, green, blue and other variables of the value, should not be reversed. Returns a true value once the function has been successfully executed.

The program effect of this function is as follows:

(Before processing)

(after processing)

The algorithm for the brightness () function is as follows:

public static bool Brightness (Bitmap b, int nbrightness) {if (Nbrightness < -255 | | nbrightness > 255) return False ; BitmapData bmdata = b.lockbits (new Rectangle (0, 0, B.width, b.height), Imagelockmode.readwrite, PIXELFORMAT.FORMAT24BPPRGB); int stride = Bmdata.stride; System.IntPtr Scan0 = bmdata.scan0; int nval = 0; unsafe {byte * p = (byte *) (void *) Scan0 int noffset = stride-b.width*3; int nwidth = B.width * 3; for (int y=0;y<b. Height;++y) {for (int x=0; x < nwidth; ++x) {nval = (int) (p[0] + nbrightness); if (Nval < 0) Nval = 0; if (Nval & Gt 255) Nval = 255; P[0] = (byte) nval; ++p; p + + Noffset; } b.unlockbits (Bmdata); return true; }


This function completes the function to brighten the image processing, it is more than the above two functions a highlight parameter-nbrightness, this parameter is entered by the user, the range is -255~255. After the brightening parameter is obtained, the Unsafe Code section of the function deals with the different color components of each pixel point individually, that is, adding a brightening parameter on the basis of the original value to get the new value. At the same time, there is also a code to prevent the value of the operation of the bounds, because the RGB component value of the range of 0~255, once exceeded this range will be reset. Once the function is successfully executed, it also returns a true value.

The program effect of this function is as follows:

First, we set the image brightening parameter to 100 (its range is -255~255), and the results are as follows, and the reader can try other parameter values.

(Before processing)

(after processing)

Three Summary:

This article through a simple example to show you the use of Visual C # and GDI + to complete the basic methods of digital image processing, through the example, we can not find that the rational use of new technologies will not only greatly simplify our programming work, but also improve the efficiency of programming. However, we are using the new technology at the same time to understand that the basic programming ideas are the most important, different languages, different mechanisms are only the specific way to achieve different, and its internal thinking is interlinked. For the above example, master the algorithm to write image processing functions, in other ways to achieve also should be feasible. At the same time, on the basis of the above, readers might as well try to extrapolate, write more image processing functions to enrich and perfect this simple example.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.