C # Identification Related technologies

Source: Internet
Author: User

Original text: C # identification related technology

Recent study of C # related OCR technology, image recognition generally C and C + + This low-level language to do more, C # mainly relies on a number of packaged components to call, here are three ways to identify identity cards.

A: Call the big company API interface, Baidu, Cloud vein, Wen Tong technology have related API introduction.
Second: Call the image Processing Class library, EMGUCV is a cross-platform. NET package of OPENCV, the package can also be compiled onto the mono platform and allow to run on multiple platforms such as Windows, Mac OS, Android, IPhone, ipad, etc.
Three: Calling the Office2007 component

I. Credential Identification API interface

Take the API interface in the aggregated data as an example, because the official API does not provide C # calling method, the URL is as follows: Credential recognition interface

<summary>///upload image///</summary>///<returns></returns>public static string Cardupload () {T ry {string appkey = "website self-applied key";//Configure the Appkey you requested Httppostedfile file = HttpContext.Current.Requ Est.        Files[0];        String url = "Http://api2.juheapi.com/cardrecon/upload";        var parameters = new dictionary<string, string> (); Parameters.        ADD ("Key", Appkey); Parameters.        ADD ("Cardtype", "2"); string result = Httppostdata (URL, 60000, "pic", file.)        InputStream, parameters); Jobject info = jobject.parse (jobject.parse (result) ["result"].        ToString ());        var cardinfo = new {name = info["Name"], card = info["citizenship Number"};    return Cardinfo.tojson (); } catch (Exception ex) {return ex.    ToString (); }}///<summary>///Post call api///</summary>///<param name= "url" >api address </param>///<param Name= "Timeout" > Access time-out </param>///<paRam Name= "Filekeyname" > File parameter name </param>///<param name= "file" > File stream </param>///<param name= " Stringdict "> Parameter list </param>///<returns> result set </returns>private static string Httppostdata (string     URL, int timeOut, string filekeyname, Stream file, dictionary<string, string> stringdict) {    String responsecontent;    var memstream = new MemoryStream ();    var webRequest = (HttpWebRequest) webrequest.create (URL);    The boundary character var boundary = "---------------" + DateTime.Now.Ticks.ToString ("x");    Boundary character var beginboundary = Encoding.ASCII.GetBytes ("--" + boundary + "\ r \ n");    The last terminator var endboundary = Encoding.ASCII.GetBytes ("--" + Boundary + "--\r\n");    Set Property Webrequest.method = "POST";    Webrequest.timeout = Timeout; Webrequest.contenttype = "Multipart/form-data;    boundary= "+ boundary;    Write start boundary character Memstream.write (beginboundary, 0, beginboundary.length); Write file const string filepartheader = "COntent-disposition:form-data; Name=\ "{0}\";    Filename=\ "{1}\" \ r \ n "+" content-type:application/octet-stream\r\n\r\n "; var header = string.    Format (Filepartheader, Filekeyname, "card.jpg");    var headerbytes = Encoding.UTF8.GetBytes (header); Memstream.write (headerbytes, 0, Headerbytes.    Length); File.    CopyTo (Memstream);  Write the string key var Stringkeyheader = "\r\n--" + boundary + "\r\ncontent-disposition:form-data;    Name=\ "{0}\" "+" \r\n\r\n{1}\r\n "; foreach (byte[] formitembytes in from string key in Stringdict.keys select String.                                         Format (Stringkeyheader, Key, Stringdict[key]) into Formitem Select Encoding.UTF8.GetBytes (Formitem)) {memstream.write (formitembytes, 0, Formitembytes.    Length);    }//write The last end of the bounding character Memstream.write (endboundary, 0, endboundary.length); Webrequest.contentlength = Memstream.length;    After construction, execute the Post method var requeststream = Webrequest.getrequeststream ();    memstream.position = 0;    var tempbuffer = new Byte[memstream.length];    Memstream.read (tempbuffer, 0, tempbuffer.length);    Memstream.close ();    requestStream.Write (tempbuffer, 0, tempbuffer.length);    Requeststream.close ();    var HttpWebResponse = (HttpWebResponse) webrequest.getresponse ();                                                    Using var httpstreamreader = new StreamReader (Httpwebresponse.getresponsestream (),    Encoding.GetEncoding ("Utf-8")) {responsecontent = Httpstreamreader.readtoend ();    } httpwebresponse.close ();    Webrequest.abort (); return responsecontent;}
Second, EMGUCV class library call environment construction

: EMGUCV official website

Download this exe under the file category, install it, find the corresponding component in the directory after installation, and some application cases.

C # for recognition, picture two value processing and OCR call related DLLs can be downloaded at my address: 360 Cloud Disk extract: 89f4
DLL is referenced in a C # project, X64,x86,tessdata corresponds to a class library and a language library for OCR recognition, and I have added the Chinese language pack in Tessdata to put these three folders into the Program execution folder.

Demo

I do the small demo ID image is Baidu downloaded

The relevant code is as follows:

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.linq;using system.text;using system.windows.forms;using emgu.cv;using emgu.cv.ocr;using emgu.cv.structure;using system.io;namespace imagemanage{public partial class Form1:form {Image<gray, B        Yte> Imagethreshold;        Public Form1 () {InitializeComponent ();            } private void Btn_convert_click (object sender, EventArgs e) {//The first parameter is the address of the language Pack folder and does not write by default under the execution folder            Tesseract _OCR = new Tesseract ("", "Chi_sim", ocrenginemode.tesseractonly); _OCR.            recognize (imagethreshold); String Text = _OCR.            GetText ();        This.textBox1.Text = Text; private void PictureBox1_Click (object sender, EventArgs e) {OpenFileDialog of = new Openfiledi            Alog (); Of.            Title = "Please select Picture"; if (of.          ShowDialog () = = DialogResult.OK) {      string file = of.                FileName;                Image img = image.fromfile (file);                        pictureBox1.Image = img;            } Bitmap Bitmap = (Bitmap) this.pictureBox1.Image;            IMAGE&LT;BGR, byte> imagesource = new IMAGE&LT;BGR, byte> (bitmap);            Image<gray, byte> Imagegrayscale = Imagesource.convert<gray, byte> ();            Imagegrayscale = Randon (Imagegrayscale);            Imagethreshold = Imagegrayscale.thresholdbinary (new gray, new Gray (255));        This.pictureBox2.Image = Imagethreshold.tobitmap (); }///<summary>//rotation correction///</summary>/<param name= "Imageinput" ></pa ram>//<returns></returns> private Image<gray, byte> Randon (Image<gray, byte> i            Mageinput)//Image projection rotation Tilt correction sub function definition {int nwidth = Imageinput.width;            int nheight = Imageinput.height;            int sum; int SuMofcha;            int sumofchatemp = 0;            int[] Sumhang = new Int[nheight];            Image<gray, byte> resultimage = imageinput;            Image<gray, byte> imrotaimage; Adjustment within 20 degrees for (int ang = -20; ang < Ang = ang + 1) {imrotaimage = Imageinpu                T.rotate (Ang, New Gray (1));                    for (int i = 0; i < nheight; i++) {sum = 0;                    for (int j = 0; J < nwidth; J + +) {sum + = Imrotaimage.data[i, j, 0];                } Sumhang[i] = sum;                } sumofcha = 0; for (int k = 0; k < nheight-1; k++) {Sumofcha = Sumofcha + (Math.Abs (sumhang[k)-                Sumhang[k + 1]));                    } if (Sumofcha > sumofchatemp) {resultimage = Imrotaimage; SumofchatEMP = Sumofcha;        }} return resultimage; }    }}
Iii. Office 2007 Components

This component is free and has a high level of recognition.

Environment construction

Office 2007 Components Modi, need to install Ofiice2007, and due to compatibility needs to install patches, SP1 or SP2 are OK, the patch is as follows:
SP1 SP2
After installation, Control Panel--Uninstall or update--select Office2007--> Select Change--select Add or Fix Features--pop up the following interface to run the corresponding component.

Run the Office Tools-->microsoft tools under Office Document Imaging

You can reference COM components in a C # project:

If the Office component app is not on a local program and needs to be deployed on IIS, you also have to set the application pool permissions for the app as shown in: Program App pool--Advanced settings--identity

Demo
StringBuilder sb = new StringBuilder();MODI.Document doc = new MODI.Document();doc.Create(fullFileName);MODI.Image image;MODI.Layout layout;doc.OCR(MODI.MiLANGUAGES.miLANG_CHINESE_SIMPLIFIED, true, true);  // 识别文字类型for (int i = 0; i < doc.Images.Count; i++){    image = (MODI.Image)doc.Images[i];    layout = image.Layout;    sb.Append(layout.Text);}

The above is some C # for identity card identification method, according to the different needs of their projects to choose.

C # Identification Related technologies

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.