Este artículo comparte un programa simple de reconocimiento del código de verificación de imagen Javase para su referencia. El contenido específico es el siguiente
Primero, debe probar la imagen y luego la muestra de la muestra, es decir, convertirla en blanco y negro.
Luego puede usar esta clase para analizar el archivo de objeto. Creo que esta clase es muy clara sobre cómo implementarla. Es mover la muestra horizontalmente desde la izquierda y ajustar las coordenadas a la siguiente posición si coincide con una adecuada.
Este programa fue escrito hace más de 3 años, pero luego no fue escrito en profundidad. El reconocimiento de imágenes es un campo muy profundo, que requiere habilidades matemáticas profundas y habilidades de pensamiento. El programa Java no es eficiente y no puede reconocer imágenes deformadas o estiradas. Sin embargo, fue suficiente en esa época. Si tiene un mejor código de reconocimiento de imagen de código abierto, asegúrese de escribir para comunicarse :)
/*** Motor de análisis de imágenes, adecuado para el análisis de los códigos de verificación del sitio web. * Primero, la muestra debe cargarse, el analizador escaneará horizontalmente de izquierda a derecha, y se registrará automáticamente si se encuentra en la muestra. * Por supuesto, este programa no es adecuado para muestras y no es único, es decir, la imagen a identificar se escala o las coordenadas se cambian o deforman. Este programa no puede realizar dicha identificación. * Si el color cambia mucho en la imagen, este programa puede tener problemas. Por supuesto, puede elegir un valor estándar como estándar para convertirlo en una matriz 0,1. * * Producción de muestra: convierta la muestra en modo de escala de grises. Es mejor contener solo dos colores. Por supuesto, si no se convierte, también lo ayudaré a convertirlo. * */import java.awt.image; import java.awt.image.bufferedImage; import java.io.file; import java.util.arrayList; import java.util.iterator; import java.util.list; import javax.imageio.Imageio; clase pública IMAGAR PARTARSer {// ----------------------------------------------------------------------------------- // byte privado matricial [] [] TargetColors; // ----------------------------------------------------------------------- ----------------------------------------------------------------------- valores [i] = string.ValueOf (i); } ImageParser parse = new ImageParser (archivos, valores); Long Start = System.CurrentTimemillis (); Pruebe {// analice la imagen System.out.println (parse.parsevalue ("d:/workspace/szxclientapp/res/validateTenum")); largo sincetime = System.CurrentTimemillis (); System.out.println ("Time scent =" + (sincetime - inicio)); } catch (Exception e) {E.PrintStackTrace (); }} // ------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- System.out.println ("¡El archivo de muestra no coincide con el valor de la muestra! ¡Reinicielo!"); devolver; } switches = new ArrayList (FilesLength); swatcheValues = new ArrayList (valueLength); int i = 0; Pruebe {for (; i <files.length; i ++) {switches.add (imageTomatrix (files [i])); swatchEvalues.add (i, valores [i]); }} capt (excepción e) {system.out.println (archivos [i] + "no se pueden analizar"); E.PrintStackTrace (); }}} public ImageParser () {super (); if (swatches == null || swatcheValues == null) {system.out.println ("No ha cargado la muestra, por favor cargue la muestra primero!"); }} / *** Poner el valor de la imagen** @param parsefilePath* Dé la ruta de la imagen* @return return la cadena* @throws excepción* / public string parseValue (string parsefilePath) lanza excepción {stringBuffer resultado = new StringBuffer (); TargetColors = imageTomatrix (parsefilepath); // printmatrix (TargetColors); int hight = TargetColors.length; int TargetWidth = TargetColors [0] .length; int ancho = 0; Iterador it = switches.iterator (); while (it.hasnext ()) {byte [] [] bytes = (byte [] []) it.next (); int temple = bytes [0] .length; if (templen> width) ancho = templen; } // system.out.println ("maxwidth =" + ancho); // system.out.println ("maxHeight =" + altura); int xtag = 0; while (((xtag + ancho) <targetWidth) {cout: {iterator itx = switches.iterator (); int i = 0; while (itx.hasnext ()) {byte [] [] bytes = (byte [] []) itx.next (); byte [] [] temp = SplitMatrix (TargetColors, xtag, 0, ancho, altura); // System.out.println (i ++); if (isMatrixInBigMatrix (bytes, temp)) {xtag += width; // System.out.println ("New Maxtrix:"); // printmatrix (temp); resultado.append (swatcheValues.get (i)); rompa cout; } i ++; } xtag ++; }} return result.toString (); } // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- BigMatrix * gran matriz * @return return verdadero si existe */ privado estático final boolean ismatrixInBigMatrix (byte [] [] fuente, byte [] [] bigmatrix) {if (fuente == bigMatrix) return true; if (fuente == null || bigMatrix == null) return false; if (fuente.length> bigmatrix.length) return false; Pruebe {for (int i = 0; i <source.length; i ++) {if (fuente [i] .length> bigMatrix [i] .length) return false; }} Catch (ArrayInDexuToFboundSexception e) {return false; } int HIED = Source.length; int width = fuente [0] .length; int x = 0, y = 0; int i = 0, j = 0; int count = 0; int comparecount = altura * ancho; para (; i <bigMatrix.length - altura+1; i ++) {for (j = 0; j <bigMatrix [i] .length - width+1; j ++) {cout: {x = 0; recuento = 0; para (int k = i; k <altura+i; k ++) {y = 0; for (int l = j; l <width + j; l ++) {// system.out.println ("bytes [" + x + "] [" + y + "]" // + "=" + fuente [x] [y] + "," + "otros [" // + k + "] [ + l +"] = " + bigmatrix [k] [l]); if ((fuente [x] [y] & bigmatrix [k] [l]) == fuente [x] [y]) {count ++; } else Break Cout; y ++; } x ++; } // system.out.println ("count =" + count); if (count == CompareCount) return true; }}} return false; } / *** Matriz de corte** @param Fuente* Matriz de origen* @param x* x coordenadas* @param y* y coordenadas* @param ancho* ancho de la matriz* @param altura* altura de la matriz* @return corta matriz* / private estático final final [] [] dividido (byte [] [] source, int x, intd x, intd them, int altiendo), intd thing, ints, intd. byte [] [] resultBytes = nuevo byte [altura] [ancho]; para (int i = y, k = 0; i <altura+y; i ++, k ++) {for (int j = x, l = 0; j <width+x; j ++, l ++) {resultbytes [k] [l] = fuente [i] [j]; // system.out.println ("fuente [" + i + "] [" + j + "]" + "=" + // fuente [i] [j] + "," + "resultBytes [" // + k + "] [" + l + "] =" + resultadobytes [k] [l]); }} return resultBytes; } / *** Convierta la imagen en una matriz de matriz** @param filepath* ruta del archivo* @return return the matrix* @throws excepción* una excepción puede ser lanzada* / private byte [] [] imageTomatrix (string filePath) lanza excepción {// leer en el archivo imagen de imagen = imageIO.Read (nuevo archivo)); int w = image.getWidth (nulo); int h = image.getheight (nulo); BufferedImage src = new BufferedImage (W, H, BufferedImage.Type_int_rgb); src.getGraphics (). DrawImage (imagen, 0, 0, nulo); byte [] [] colores = nuevo byte [h] [w]; para (int i = 0; i <h; i ++) {for (int j = 0; j <w; j ++) {int rgb = src.getrgb (j, i); // Procesamiento de escala de grises de la cadena de píxeles sred = integer.tohexString (rgb) .substring (2, 4); String sgreen = integer.tohexString (rgb) .substring (4, 6); Cadena sblank = integer.toHexString (rgb) .substring (6, 8); Long ired = math.round ((integer.parseint (sred, 16) * 0.3 + 0.5d)); long green = math.round ((integer.parseint (sgreen, 16) * 0.59 + 0.5d)); long iBlank = Math.round ((Integer.ParseInt (Sblank, 16) * 0.11 + 0.5D)); Long al = ired + verde + iblank; // if (al> 127) // system.out.print ("" + ""); // else // system.out.print ("" + "1"); // system.out.print ("" + (tempint> = maxint? 0: 1)); // system.out.println ("tempint =" + tempint); / * Convierta la imagen en 0,1 */ // El valor aquí puede modificarse al valor que necesita juzgar en los colores futuros [i] [j] = (byte) (al> 127? 0: 1); } // system.out.println (); } colores de retorno; } / ** * Imprimir matriz * * @param matrix * / private static final void printmatrix (byte [] [] matrix) {for (int i = 0; i <matrix.length; i ++) {for (int j = 0; j <matrix [i] .length; j ++) {if (matrix [i] [j] == 0) System. else System.out.print ("1"); } System.out.println (); }}}Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.