The examples in this article share the source code of Java fingerprint recognition and image recognition for your reference. The specific content is as follows
Main category:
import java.awt.image.BufferedImage;import java.util.ArrayList;import java.util.List;public class SimilarImageSearch { /** * @param args */ public static void main(String[] args) { List<String> hashCodes = new ArrayList<String>(); String filename = ImageHelper.path + "//images//"; String hashCode = null; for (int i = 0; i < 6; i++) { hashCode = produceFingerPrint(filename + "example" + (i + 1) + ".jpg"); hashCodes.add(hashCode); } System.out.println("Resources: "); System.out.println(hashCodes); System.out.println(); String sourceHashCode = produceFingerPrint(filename + "source.jpg"); System.out.println("Source: "); System.out.println(sourceHashCode); System.out.println(); for (int i = 0; i < hashCodes.size(); i++) { int difference = hammingDistance(sourceHashCode, hashCodes.get(i)); System.out.print("Hamming distance:"+difference+" "); if(difference==0){ System.out.println("source.jpg picture is the same as example"+(i+1)+".jpg"); }else if(difference<=5){ System.out.println("source.jpg image is very similar to example"+(i+1)+".jpg"); }else if(difference<=10){ System.out.println("source.jpg image is somewhat similar to example"+(i+1)+".jpg"); }else if(difference>10){ System.out.println("source.jpg image is completely different from example"+(i+1)+".jpg"); } } } /** * Calculate "Hamming distance". * If the data bits of different do not exceed 5, it means that the two pictures are very similar; if they are greater than 10, it means that these are two different pictures. * @param sourceHashCode Source hashCode * @param hashCode Comparison hashCode */ public static int hammingDistance(String sourceHashCode, String hashCode) { int difference = 0; int len = sourceHashCode.length(); for (int i = 0; i < len; i++) { if (sourceHashCode.charAt(i) != hashCode.charAt(i)) { difference ++; } } return difference; } /** * Generate image fingerprint* @param filename filename* @return Image fingerprint*/ public static String produceFingerPrint(String filename) { BufferedImage source = ImageHelper.readPNGImage(filename);// Read the file int width = 8; int height = 8; // The first step is to reduce the size. // Shrink the image to 8x8 size, with a total of 64 pixels. The purpose of this step is to remove the details of the picture, retain only basic information such as structure, light and dark, and abandon the differences in picture caused by different sizes and proportions. BufferedImage thumb = ImageHelper.thumb(source, width, height, false); // The second step is to simplify the color. // Turn the reduced image to level 64 grayscale. That is to say, there are only 64 colors in all pixels. int[] pixels = new int[width * height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { pixels[i * height + j] = ImageHelper.rgbToGray(thumb.getRGB(i, j)); } } // The third step is to calculate the average. // Calculate the grayscale average of all 64 pixels. int avgPixel = ImageHelper.average(pixels); // Step 4, compare the grayscale of the pixels. // Compare the grayscale of each pixel with the average value. If it is greater than or equal to the average value, it is denoted as 1; if it is less than the average value, it is denoted as 0. int[] comps = new int[width * height]; for (int i = 0; i < comps.length; i++) { if (pixels[i] >= avgPixel) { comps[i] = 1; } else { comps[i] = 0; } } // Step 5, calculate the hash value. // Combine the comparison results of the previous step together to form a 64-bit integer, which is the fingerprint of this picture. The order of combinations is not important, just make sure that all pictures are in the same order. StringBuffer hashCode = new StringBuffer(); for (int i = 0; i < comps.length; i+= 4) { int result = comps[i] * (int) Math.pow(2, 3) + comps[i + 1] * (int) Math.pow(2, 2) + comps[i + 2] * (int) Math.pow(2, 1) + comps[i + 2]; hashCode.append(binaryToHex(result)); } // After getting the fingerprint, you can compare different pictures to see how many bits are different in the 64-bit. return hashCode.toString(); } /** * Convert binary to hex * @param int binary * @return char hex */ private static char binaryToHex(int binary) { char ch = ''; switch (binary) { case 0: ch = '0'; break; case 1: ch = '1'; break; case 2: ch = '2'; break; case 3: ch = '3'; break; case 4: ch = '4'; break; case 5: ch = '5'; break; case 6: ch = '6'; break; case 7: ch = '7'; break; case 8: ch = '8'; break; case 9: ch = '9'; break; case 10: ch = 'a'; break; case 11: ch = 'b'; break; case 12: ch = 'c'; break; case 13: ch = 'd'; break; case 14: ch = 'e'; break; case 15: ch = 'f'; break; default: ch = ''; } return ch; }} Tools:
import java.awt.AlphaComposite;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.Image;import java.awt.RenderingHints;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.awt.image.ColorModel;import java.awt.image.WritableRaster;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.ImageFormatException;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageDecoder;import com.sun.image.codec.jpeg.JPEGImageEncoder;/** * Image tool class, mainly for image watermark processing* * @author 025079 * @version [version number, 2011-11-28] * @see [Related Class/Method] * @since [Product/Module Version] */public class ImageHelper { // Project root directory path public static final String path = System.getProperty("user.dir"); /** * Generate thumbnails<br/> * Save:ImageIO.write(BufferedImage, imgType[jpg/png/...], File); * * @param source * Original image * @param width * Thumbnail width * Thumbnail height * Thumbnail height * @param b * Is it equally scaled* */ public static BufferedImage thumb(BufferedImage source, int width, int height, boolean b) { // targetW, targetH indicates the target length and width respectively int type = source.getType(); BufferedImage target = null; double sx = (double) width / source.getWidth(); double sy = (double) height / source.getHeight(); if (b) { if (sx > sy) { sx = sy; width = (int) (sx * source.getWidth()); } else { sy = sx; height = (int) (sy * source.getHeight()); } } if (type == BufferedImage.TYPE_CUSTOM) { // handmade ColorModel cm = source.getColorModel(); WritableRaster raster = cm.createCompatibleWritableRaster(width, height); boolean alphaPremultiplied = cm.isAlphaPremultiplied(); target = new BufferedImage(cm, raster, alphaPremultiplied, null); } else target = new BufferedImage(width, height, type); Graphics2D g = target.createGraphics(); // smoother than exlax: g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy)); g.dispose(); return target; } /** * Image watermark* * @param imgPath * Pending image* @param markPath * Watermark image* @param x * Watermark is in the upper left corner of the image The x coordinate value of the @param y * Watermark is in the upper left corner of the image The y coordinate value of the @param alpha * Watermark transparency 0.1f ~ 1.0f * */ public static void waterMark(String imgPath, String markPath, int x, int y, float alpha) { try { // Load the pending image file Image img = ImageIO.read(new File(imgPath)); BufferedImage image = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.drawImage(img, 0, 0, null); // Load the watermark image file Image src_biao = ImageIO.read(new File(markPath)); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); g.drawImage(src_biao, x, y, null); g.dispose(); // Save the processed file FileOutputStream out = new FileOutputStream(imgPath); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); out.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Text watermark* * @param imgPath * Pending image* @param text * Watermark text* @param font * Watermark font information* @param color * Watermark font color* @param x * Watermark x coordinate value at the upper left corner of the picture* @param y * Watermark is in the y coordinate value at the upper left corner of the picture* @param alpha * Watermark transparency 0.1f ~ 1.0f */ public static void textMark(String imgPath, String text, Font font, Color color, int x, int y, float alpha) { try { Font Dfont = (font == null) ? new Font("宋体", 20, 13) : font; Image img = ImageIO.read(new File(imgPath)); BufferedImage image = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.drawImage(img, 0, 0, null); g.setColor(color); g.setFont(Dfont); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); g.drawString(text, x, y); g.dispose(); FileOutputStream out = new FileOutputStream(imgPath); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); out.close(); } catch (Exception e) { System.out.println(e); } } /** * Read JPEG image* @param filename Filename* @return BufferedImage Image object*/ public static BufferedImage readJPEGImage(String filename) { try { InputStream imageIn = new FileInputStream(new File(filename)); // Get the input encoder and encode the file stream in jpg format JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(imageIn); // Get the encoded image object BufferedImage sourceImage = decoder.decodeAsBufferedImage(); return sourceImage; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ImageFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * Read JPEG picture* @param filename Filename* @return BufferedImage Image object*/ public static BufferedImage readPNGImage(String filename) { try { File inputFile = new File(filename); BufferedImage sourceImage = ImageIO.read(inputFile); return sourceImage; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ImageFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * Grayscale value calculation* @param pixels pixels * @return int Grayscale value*/ public static int rgbToGray(int pixels) { // int _alpha = (pixels >> 24) & 0xFF; int _red = (pixels >> 16) & 0xFF; int _green = (pixels >> 8) & 0xFF; int _blue = (pixels) & 0xFF; return (int) (0.3 * _red + 0.59 * _green + 0.11 * _blue); } /** * Calculate the average of the array* @param pixels Array* @return int average*/ public static int average(int[] pixels) { float m = 0; for (int i = 0; i < pixels.length; ++i) { m += pixels[i]; } m = m / pixels.length; return (int) m; }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.