圖片相似原理--Java實現


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

 

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

打開Google圖片搜索頁面:

點擊使用上傳一張原圖:

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

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

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

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

 

預處理:讀取圖片

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

 

第一步,縮小尺寸。

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

int width= 8;
intheight = 8;
// targetW,targetH分別表示目標長和寬
int type= sourceImage.getType();// 圖片類型
BufferedImagethumbImage = null;
double sx= (double) width / sourceImage.getWidth();
double sy= (double) height / sourceImage.getHeight();
// 將圖片寬度和高度都設置成一樣,以長度短的為准
if (b) {
      if(sx > sy) {
            sx= sy;
            width= (int) (sx * sourceImage.getWidth());
      }else {
            sy= sx;
            height= (int) (sy * sourceImage.getHeight());
      }
}
// 自定義圖片
if (type== BufferedImage.TYPE_CUSTOM) { // handmade
     ColorModelcm = sourceImage.getColorModel();
     WritableRasterraster = cm.createCompatibleWritableRaster(width,height);
     booleanalphaPremultiplied = cm.isAlphaPremultiplied();
     thumbImage= new BufferedImage(cm, raster, alphaPremultiplied, null);
 } else {
     // 已知圖片,如jpg,png,gif
     thumbImage= new BufferedImage(width, height, type);
}
// 調用畫圖類畫縮小尺寸后的圖
Graphics2Dg = target.createGraphics();
//smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.drawRenderedImage(sourceImage,AffineTransform.getScaleInstance(sx, sy));
g.dispose();

 

第二步,簡化色彩。

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

int[]pixels = new int[width * height];
for (inti = 0; i < width; i++) {
      for(int j = 0; j < height; j++) {
            pixels[i* height + j] = rgbToGray(thumbImage.getRGB(i, j));
      }
}
/**
 * 灰度值計算
 * @param pixels 彩色RGB值(Red-Green-Blue 紅綠藍)
 * @return int 灰度值
 */
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);
}

 

第三步,計算平均值。

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

int avgPixel= 0;
int m = 0;
for (int i =0; i < pixels.length; ++i) {
      m +=pixels[i];
}
m = m /pixels.length;
avgPixel = m;

 

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

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

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

 

第五步,計算哈希值。

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

 .= . = 8f373714acfcf4d0

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

 

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

int difference = 0;
int len =sourceHashCode.length();
       
for (inti = 0; i < len; i++) {
   if(sourceHashCode.charAt(i) != hashCode.charAt(i)) {
       difference++;
   }
}

 

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

 

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

 

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

 

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

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

 


免責聲明!

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



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