Este artigo compartilha um programa simples de reconhecimento de código de verificação de imagem Javase para sua referência. O conteúdo específico é o seguinte
Primeiro, você deve provar a imagem e depois em escala de cinza a amostra, ou seja, transformá -la em preto e branco.
Em seguida, você pode usar esta classe para analisar o arquivo de objeto. Eu acho que esta classe é muito clara sobre como implementá -la. É mover a amostra horizontalmente da esquerda e ajustar as coordenadas para a próxima posição, se corresponder a uma adequada.
Este programa foi escrito há mais de 3 anos, mas depois não foi escrito em profundidade. O reconhecimento de imagem é um campo muito profundo, que requer profundas habilidades matemáticas e capacidade de pensar. O programa Java não é eficiente e não pode reconhecer imagens deformadas ou esticadas. No entanto, foi o suficiente naquela época. Se você tiver melhor código de reconhecimento de imagem de código aberto, escreva para se comunicar :)
/*** Motor de análise de imagem, adequado para análise dos códigos de verificação do site. * Primeiro, a amostra deve ser carregada, o analisador escaneará horizontalmente da esquerda para a direita e gravará automaticamente se for encontrado na amostra. * Obviamente, este programa não é adequado para amostras e não é único, ou seja, a imagem a ser identificada é escalada ou as coordenadas são alteradas ou deformadas. Este programa não pode executar essa identificação. * Se a cor mudar muito na imagem, este programa poderá ter problemas. Obviamente, você pode escolher um valor padrão como padrão para convertê -lo em uma matriz 0,1. * * Produção de amostra: converta a amostra no modo de escala de cinza. É melhor conter apenas duas cores. Obviamente, se você não se converter, também o ajudarei a convertê -lo. * */importar java.awt.image; importar java.awt.image.bufferedImage; importar java.io.file; importar java.util.arraylist; importar java.util.iterator; import java.util.list; import javax.imageio.imageio; publicparparser {ClassPaRparser: • // Matrifed Private Byte [] [] TargetColors; // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- valores [i] = string.valueof (i); } Imageparser parse = new ImageParser (arquivos, valores); long start = system.currenttimemillis (); tente {// analisar o sistema de imagem.out.println (parse.parsevalue ("d:/workspace/szxcliientApp/res/validatenum"); long sincetime = System.CurrentTimemillis (); System.out.println ("tempo gasto =" + (sincetime - start)); } catch (Exceção e) {e.printStackTrace (); }} // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- System.out.println ("O arquivo de amostra não corresponde ao valor da amostra! Reinicie -o!"); retornar; } switches = new ArrayList (filesLength); swatchevalues = new ArrayList (valoresLength); int i = 0; tente {for (; i <files.length; i ++) {switches.add (imageTomatrix (arquivos [i])); swatchevalues.add (i, valores [i]); }} catch (Exceção e) {System.out.println (arquivos [i] + "não pode ser analisado"); E.PrintStackTrace (); }}} public imageParser () {super (); if (swatches == null || swatchevalues == null) {System.out.println ("Você não carregou a amostra, carregue a amostra primeiro!"); }} / *** analisando o valor da imagem** @param parsefilepath* Dê ao caminho da imagem* @return retornar a string* @throws Exceção* / public String parsevalue (String parsefilepath) lança exceção {stringbuffer resultado = new StringBuffer (); TargetColors = ImageTomatrix (parsefilepath); // printMatrix (TargetColors); int height = TargetColors.length; int TargetWidth = TargetColors [0] .Length; int width = 0; Iterator it = switches.iterator (); while (it.hasnext ()) {byte [] [] bytes = (byte [] []) it.next (); int temple = bytes [0] .Length; if (templen> width) largura = templen; } // System.out.println ("maxwidth =" + width); // system.out.println ("maxHeight =" + altura); int xtag = 0; while ((xtag + largura) <TargetWidth) {cout: {iterator itx = switches.iterator (); int i = 0; while (itx.hasnext ()) {byte [] [] bytes = (byte [] []) itx.next (); byte [] [] temp = splitMatrix (TargetColors, xtag, 0, largura, altura); // System.out.println (i ++); if (ismatrixInbigMatrix (bytes, temp)) {xtag += width; // system.out.println ("new maxtrix:"); // printMatrix (temp); resultado.append (swatchevalues.get (i)); quebrar cout; } i ++; } xtag ++; }} retornar resultado.toString (); } // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- bigMatrix * Matrix grande * @return retornar true se existir */ private estático final booleano ismatrixinbigMatrix (byte [] [] fonte, byte [] [] bigMatrix) {if (fonte == bigmatrix) retorna true; if (fonte == null || bigMatrix == null) retorna false; if (fonte.Length> bigmatrix.length) retorna false; tente {for (int i = 0; i <fonte.length; i ++) {if (fonte [i] .Length> bigMatrix [i] .Length) return false; }} catch (ArrayIndexoutOfBoundSexception e) {return false; } int altura = fonte.length; int width = fonte [0] .Length; int x = 0, y = 0; int i = 0, j = 0; int conting = 0; int compareCount = altura * largura; para (; i <bigmatrix.Length - altura+1; i ++) {for (j = 0; j <bigmatrix [i] .Length - largura+1; j ++) {cout: {x = 0; contagem = 0; for (int k = i; k <altura+i; k ++) {y = 0; para (int l = j; l <largura + j; l ++) {// System.out.println ("bytes [" + x + "] [" + y + "]" // + "=" + fonte [x] [y] + "," + "outro [" // + k + "] [" + l + "] =" BigMatrix [ if ((fonte [x] [y] e bigmatrix [k] [l]) == fonte [x] [y]) {count ++; } mais quebrar o cout; y ++; } x ++; } // System.out.println ("count =" + count); if (count == compareCount) retorna true; }}} retorna false; } / *** Corte a matriz** @param fonte* Matrix de origem* @param x* x coordenadas* @param y* y coordenadas* @param width* width of the matrix* @param altura* altura IntrTrT do matrix* @return corte* / private static final {byte [] [] resultadoBytes = novo byte [altura] [largura]; para (int i = y, k = 0; i <altura+y; i ++, k ++) {for (int j = x, l = 0; j <largura+x; j ++, l ++) {resultadobytes [k] [l] = fonte [i] [j]; // system.out.println ("fonte [" + i + "] [" + j + "]" + "=" + // fonte [i] [j] + "," + "resultbytes [" // + k + "] [" + l + "] =" + resultadobytes [k] [l]); }} retornar o resultadoBytes; } / *** Converta a imagem em uma matriz matriz** @param filepath* caminho do arquivo* @return retorna a matriz* @throws exceção* Uma exceção pode ser lançada* / privado byte [] [] imageTomatrix (string filepath) lança exceção {// na imagem do arquivo imagem = imagem.read (new FilePath); int w = image.getWidth (nulo); int h = image.getheight (nulo); BufferImage src = new bufferiMage (w, h, bufferImage.type_int_rgb); src.getgraphics (). drawimage (imagem, 0, 0, nulo); byte [] [] cores = novo byte [h] [w]; for (int i = 0; i <h; i ++) {for (int j = 0; j <w; j ++) {int rgb = src.getRgb (j, i); // Processamento em escala de cinza de pixels string sred = integer.tohexstring (rgb) .substring (2, 4); String sgreen = integer.tohexString (rgb) .substring (4, 6); String sblank = Integer.toHexString (RGB) .Substring (6, 8); Long IRED = Math.Round ((Integer.parseint (Sred, 16) * 0,3 + 0,5d)); verde longo = math.Round ((inteiro.parseint (sgreen, 16) * 0,59 + 0,5d)); Long Iblank = Math.Round ((Integer.parseint (sblank, 16) * 0,11 + 0,5d)); long al = irred + 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); / * Converta a imagem para 0,1 */ // O valor aqui pode ser modificado no valor que você precisa julgar nas cores futuras [i] [j] = (byte) (al> 127? 0: 1); } // System.out.println (); } retornar cores; } / ** * Imprima matriz * * @param matriz * / private estático final void printMatrix (byte [] [] matrix) {for (int i = 0; i <matrix.length; i ++) {para (int j = 0; else System.out.print ("1"); } System.out.println (); }}}O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.