Java實現用漢明距離進行圖片相似度檢測的


Google、Baidu 等搜索引擎相繼推出了以圖搜圖的功能,測試了下效果還不錯~ 那這種技術的原理是什么呢?計算機怎么知道兩張圖片相似呢?

用漢明距離進行圖片相似度檢測的Java實現

根據Neal Krawetz博士的解釋,原理非常簡單易懂。我們可以用一個快速算法,就達到基本的效果。

這里的關鍵技術叫做"感知哈希算法"(Perceptual hash algorithm),它的作用是對每張圖片生成一個"指紋"(fingerprint)字符串,然后比較不同圖片的指紋。結果越接近,就說明圖片越相似。

下面是一個最簡單的實現:

第一步,縮小尺寸。

將圖片縮小到8x8的尺寸,總共64個像素。這一步的作用是去除圖片的細節,只保留結構、明暗等基本信息,摒棄不同尺寸、比例帶來的圖片差異。

 

第二步,簡化色彩。

將縮小后的圖片,轉為64級灰度。也就是說,所有像素點總共只有64種顏色。

第三步,計算平均值。

計算所有64個像素的灰度平均值。

第四步,比較像素的灰度。

將每個像素的灰度,與平均值進行比較。大於或等於平均值,記為1;小於平均值,記為0。

第五步,計算哈希值。

將上一步的比較結果,組合在一起,就構成了一個64位的整數,這就是這張圖片的指紋。組合的次序並不重要,只要保證所有圖片都采用同樣次序就行了。

 =  = 8f373714acfcf4d0

得到指紋以后,就可以對比不同的圖片,看看64位中有多少位是不一樣的。在理論上,這等同於計算"漢明距離"(Hamming distance)。如果不相同的數據位不超過5,就說明兩張圖片很相似;如果大於10,就說明這是兩張不同的圖片。

具體的代碼實現,可以參見WotePython語言寫的imgHash.py。代碼很短,只有53行。使用的時候,第一個參數是基准圖片,第二個參數是用來比較的其他圖片所在的目錄,返回結果是兩張圖片之間不相同的數據位數量(漢明距離)。

這種算法的優點是簡單快速,不受圖片大小縮放的影響,缺點是圖片的內容不能變更。如果在圖片上加幾個文字,它就認不出來了。所以,它的最佳用途是根據縮略圖,找出原圖。

實際應用中,往往采用更強大的pHash算法和SIFT算法,它們能夠識別圖片的變形。只要變形程度不超過25%,它們就能匹配原圖。這些算法雖然更復雜,但是原理與上面的簡便算法是一樣的,就是先將圖片轉化成Hash字符串,然后再進行比較。

下面我們來看下上述理論用Java來做一個DEMO版的具體實現:

 

package reyo.sdk.utils.ai.pic;

import java.awt.Graphics2D;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.imageio.ImageIO;

/* 
 *
 * 漢明距離越大表明圖片差異越大,如果不相同的數據位不超過5,就說明兩張圖片很相似;如果大於10,就說明這是兩張不同的圖片。
 *
 * pHash-like image hash.  
 * Author: Elliot Shepherd (elliot@jarofworms.com
 * Based On: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
 */ public class ImagePHash { // 項目根目錄路徑 public static final String path = System.getProperty("user.dir"); private int size = 32; private int smallerSize = 8; public ImagePHash() { initCoefficients(); } public ImagePHash(int size, int smallerSize) { this.size = size; this.smallerSize = smallerSize; initCoefficients(); } public int distance(String s1, String s2) { int counter = 0; for (int k = 0; k < s1.length(); k++) { if (s1.charAt(k) != s2.charAt(k)) { counter++; } } return counter; } // Returns a 'binary string' (like. 001010111011100010) which is easy to do // a hamming distance on. public String getHash(InputStream is) throws Exception { BufferedImage img = ImageIO.read(is); /* * 1. Reduce size. Like Average Hash, pHash starts with a small image. * However, the image is larger than 8x8; 32x32 is a good size. This is * really done to simplify the DCT computation and not because it is * needed to reduce the high frequencies. */ img = resize(img, size, size); /* * 2. Reduce color. The image is reduced to a grayscale just to further * simplify the number of computations. */ img = grayscale(img); double[][] vals = new double[size][size]; for (int x = 0; x < img.getWidth(); x++) { for (int y = 0; y < img.getHeight(); y++) { vals[x][y] = getBlue(img, x, y); } } /* * 3. Compute the DCT. The DCT separates the image into a collection of * frequencies and scalars. While JPEG uses an 8x8 DCT, this algorithm * uses a 32x32 DCT. */ long start = System.currentTimeMillis(); double[][] dctVals = applyDCT(vals); System.out.println("DCT: " + (System.currentTimeMillis() - start)); /* * 4. Reduce the DCT. This is the magic step. While the DCT is 32x32, * just keep the top-left 8x8. Those represent the lowest frequencies in * the picture. */ /* * 5. Compute the average value. Like the Average Hash, compute the mean * DCT value (using only the 8x8 DCT low-frequency values and excluding * the first term since the DC coefficient can be significantly * different from the other values and will throw off the average). */ double total = 0; for (int x = 0; x < smallerSize; x++) { for (int y = 0; y < smallerSize; y++) { total += dctVals[x][y]; } } total -= dctVals[0][0]; double avg = total / (double) ((smallerSize * smallerSize) - 1); /* * 6. Further reduce the DCT. This is the magic step. Set the 64 hash * bits to 0 or 1 depending on whether each of the 64 DCT values is * above or below the average value. The result doesn't tell us the * actual low frequencies; it just tells us the very-rough relative * scale of the frequencies to the mean. The result will not vary as * long as the overall structure of the image remains the same; this can * survive gamma and color histogram adjustments without a problem. */ String hash = ""; for (int x = 0; x < smallerSize; x++) { for (int y = 0; y < smallerSize; y++) { if (x != 0 && y != 0) { hash += (dctVals[x][y] > avg ? "1" : "0"); } } } return hash; } private BufferedImage resize(BufferedImage image, int width, int height) { BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = resizedImage.createGraphics(); g.drawImage(image, 0, 0, width, height, null); g.dispose(); return resizedImage; } private ColorConvertOp colorConvert = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); private BufferedImage grayscale(BufferedImage img) { colorConvert.filter(img, img); return img; } private static int getBlue(BufferedImage img, int x, int y) { return (img.getRGB(x, y)) & 0xff; } // DCT function stolen from // http://stackoverflow.com/questions/4240490/problems-with-dct-and-idct-algorithm-in-java private double[] c; private void initCoefficients() { c = new double[size]; for (int i = 1; i < size; i++) { c[i] = 1; } c[0] = 1 / Math.sqrt(2.0); } private double[][] applyDCT(double[][] f) { int N = size; double[][] F = new double[N][N]; for (int u = 0; u < N; u++) { for (int v = 0; v < N; v++) { double sum = 0.0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { sum += Math.cos(((2 * i + 1) / (2.0 * N)) * u * Math.PI) * Math.cos(((2 * j + 1) / (2.0 * N)) * v * Math.PI) * (f[i][j]); } } sum *= ((c[u] * c[v]) / 4.0); F[u][v] = sum; } } return F; } public static void main(String[] args) { // 項目根目錄路徑 String filename = ImagePHash.path + "\\images\\"; ImagePHash p = new ImagePHash(); String image1; String image2; try { for (int i = 0; i < 10; i++) { image1 = p.getHash(new FileInputStream(new File(filename + "example" + (i + 1) + ".jpg"))); image2 = p.getHash(new FileInputStream(new File(filename + "source.jpg"))); System.out.println("example" + (i + 1) + ".jpg:source.jpg Score is " + p.distance(image1, image2)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }

 

運行結果為:

DCT: 249
DCT: 237
example1.jpg:source.jpg Score is 25
DCT: 102
DCT: 103
example2.jpg:source.jpg Score is 16
DCT: 103
DCT: 104
example3.jpg:source.jpg Score is 17
DCT: 104
DCT: 103
example4.jpg:source.jpg Score is 2
DCT: 103
DCT: 103
example5.jpg:source.jpg Score is 0
DCT: 104
DCT: 104
example6.jpg:source.jpg Score is 10
DCT: 105
DCT: 104
example7.jpg:source.jpg Score is 25
DCT: 103
DCT: 103
example8.jpg:source.jpg Score is 28
DCT: 102
DCT: 103
example9.jpg:source.jpg Score is 25
DCT: 102
DCT: 103
example10.jpg:source.jpg Score is 31

 

如果不相同的數據位不超過5,就說明兩張圖片很相似;如果大於10,就說明這是兩張不同的圖片。

代碼參考:http://pastebin.com/Pj9d8jt5
原理參考:http://www.ruanyifeng.com/blog/2011/07/principle_of_similar_image_search.html
漢明距離:http://baike.baidu.com/view/725269.htm

來自:http://stackoverflow.com/questions/6971966/how-to-measure-percentage-similarity-between-two-images

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM