Google 以圖搜圖 - 相似圖片搜索原理 - Java實現

分類: Java 實踐者的思想 1151人閱讀 評論(6)收藏 舉報

前陣子在阮一峯的博客上看到了這篇《相似圖片搜索原理》博客,就有一種衝動要將這些原理實現出來了。

 

Google "相似圖片搜索":你可以用一張圖片,搜索互聯網上所有與它相似的圖片。

打開Google圖片搜索頁面:


點擊使用上傳一張angelababy原圖:


點擊搜索後,Google將會找出與之相似的圖片,圖片相似度越高就越排在前面。如:


這種技術的原理是什麼?計算機怎麼知道兩張圖片相似呢?

根據Neal Krawetz博士的解釋,實現相似圖片搜素的關鍵技術叫做"感知哈希算法"(Perceptualhash algorithm),它的作用是對每張圖片生成一個"指紋"(fingerprint)字符串,然後比較不同圖片的指紋。結果越接近,就說明圖片越相似。

 

以下是一個最簡單的Java實現:

 

預處理:讀取圖片

  1. File inputFile = newFile(filename);   
  2. BufferedImage sourceImage = ImageIO.read(inputFile);//讀取圖片文件  

第一步,縮小尺寸。

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

  1. int width= 8;  
  2. intheight = 8;  
  3. // targetW,targetH分別表示目標長和寬   
  4. int type= sourceImage.getType();// 圖片類型  
  5. BufferedImagethumbImage = null;  
  6. double sx= (double) width / sourceImage.getWidth();  
  7. double sy= (double) height / sourceImage.getHeight();  
  1. // 將圖片寬度和高度都設置成一樣,以長度短的爲準   
  2. if (b) {  
  3.       if(sx > sy) {  
  4.             sx= sy;  
  5.             width= (int) (sx * sourceImage.getWidth());  
  6.       }else {  
  7.             sy= sx;  
  8.             height= (int) (sy * sourceImage.getHeight());  
  9.       }  
  10. }  
  11. // 自定義圖片   
  12. if (type== BufferedImage.TYPE_CUSTOM) { // handmade  
  13.      ColorModelcm = sourceImage.getColorModel();  
  14.      WritableRasterraster = cm.createCompatibleWritableRaster(width,height);  
  15.      booleanalphaPremultiplied = cm.isAlphaPremultiplied();  
  16.      thumbImage= new BufferedImage(cm, raster, alphaPremultiplied, null);  
  17.  } else {  
  18.      // 已知圖片,如jpg,png,gif   
  19.      thumbImage= new BufferedImage(width, height, type);  
  20. }  
  21. // 調用畫圖類畫縮小尺寸後的圖   
  22. Graphics2Dg = target.createGraphics();  
  23. //smoother than exlax:   
  24. g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);  
  25. g.drawRenderedImage(sourceImage,AffineTransform.getScaleInstance(sx, sy));  
  26. g.dispose();  

 

第二步,簡化色彩。

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

  1. int[]pixels = new int[width * height];  
  2. for (inti = 0; i < width; i++) {  
  3.       for(int j = 0; j < height; j++) {  
  4.             pixels[i* height + j] = rgbToGray(thumbImage.getRGB(i, j));  
  5.       }  
  6. }  
  7. /**  
  8.  * 灰度值計算  
  9.  * @param pixels 彩色RGB值(Red-Green-Blue 紅綠藍)  
  10.  * @return int 灰度值  
  11.  */  
  12. public static int rgbToGray(int pixels) {  
  13.        // int _alpha =(pixels >> 24) & 0xFF;  
  14.        int _red = (pixels >> 16) & 0xFF;  
  15.        int _green = (pixels >> 8) & 0xFF;  
  16.        int _blue = (pixels) & 0xFF;  
  17.        return (int) (0.3 * _red + 0.59 * _green + 0.11 * _blue);  
  18. }  


第三步,計算平均值。

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

  1. int avgPixel= 0;  
  2. int m = 0;  
  3. for (int i =0; i < pixels.length; ++i) {  
  4.       m +=pixels[i];  
  5. }  
  6. m = m /pixels.length;  
  7. avgPixel = m;  


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

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

  1. int[] comps= new int[width * height];  
  2. for (inti = 0; i < comps.length; i++) {  
  3.     if(pixels[i] >= avgPixel) {  
  4.         comps[i]= 1;  
  5.     }else {  
  6.         comps[i]= 0;  
  7.     }  
  8. }  

第五步,計算哈希值。

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

 =  = 8f373714acfcf4d0

  1. StringBufferhashCode = new StringBuffer();  
  2. for (inti = 0; i < comps.length; i+= 4) {  
  3.       intresult = 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];  
  4.       hashCode.append(binaryToHex(result));//二進制轉爲16進制  
  5. }  
  6. StringsourceHashCode = hashCode.toString();  


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

  1. int difference = 0;  
  2. int len =sourceHashCode.length();  
  3.          
  4. for (inti = 0; i < len; i++) {  
  5.    if(sourceHashCode.charAt(i) != hashCode.charAt(i)) {  
  6.        difference++;  
  7.    }  
  8. }  

你可以將幾張圖片放在一起,也計算出他們的漢明距離對比,就可以看看兩張圖片是否相似。

 

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

 

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


以上內容大部分直接從阮一峯的網站上覆制過來,想看原著的童鞋可以去在最上面的鏈接點擊進去看。


提供源碼下載,源碼下載鏈接:http://download.csdn.net/detail/luohong722/3965112 

參考鏈接:神奇的圖像處理算法11款相似圖片搜索引擎推薦,以圖搜圖將不再是難事http://insidesearch.blogspot.com/2011/07/teaching-computers-to-see-image.html

發佈了22 篇原創文章 · 獲贊 12 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章