汉明距离的应用

Google、Baidu 等搜索引擎相继推出了以图搜图的功能,测试了下效果还不错~ 那这种技术的原理是什么呢?计算机怎么知道两张图片相似呢?

用汉明距离进行图片相似度检测的Java实现

根据Neal Krawetz博士的解释,原理非常简单易懂。我们可以用一个快速算法,就达到基本的效果。

这里的关键技术叫做"感知哈希算法"(Perceptual hash algorithm),它的作用是对每张图片生成一个"指纹"(fingerprint)字符串,然后比较不同图片的指纹。结果越接近,就说明图片越相似。

下面是一个最简单的实现:

第一步,缩小尺寸。

将图片缩小到8x8的尺寸,总共64个像素。这一步的作用是去除图片的细节,只保留结构、明暗等基本信息,摒弃不同尺寸、比例带来的图片差异。

用汉明距离进行图片相似度检测的Java实现 用汉明距离进行图片相似度检测的Java实现

第二步,简化色彩。

将缩小后的图片,转为64级灰度。也就是说,所有像素点总共只有64种颜色。

第三步,计算平均值。

计算所有64个像素的灰度平均值。

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

将每个像素的灰度,与平均值进行比较。大于或等于平均值,记为1;小于平均值,记为0。

第五步,计算哈希值。

将上一步的比较结果,组合在一起,就构成了一个64位的整数,这就是这张图片的指纹。组合的次序并不重要,只要保证所有图片都采用同样次序就行了。

用汉明距离进行图片相似度检测的Java实现 = 用汉明距离进行图片相似度检测的Java实现 = 8f373714acfcf4d0

得到指纹以后,就可以对比不同的图片,看看64位中有多少位是不一样的。在理论上,这等同于计算"汉明距离"(Hamming distance)。如果不相同的数据位不超过5,就说明两张图片很相似;如果大于10,就说明这是两张不同的图片。

具体的代码实现,可以参见Wote用python语言写的imgHash.py。代码很短,只有53行。使用的时候,第一个参数是基准图片,第二个参数是用来比较的其他图片所在的目录,返回结果是两张图片之间不相同的数据位数量(汉明距离)。

这种算法的优点是简单快速,不受图片大小缩放的影响,缺点是图片的内容不能变更。如果在图片上加几个文字,它就认不出来了。所以,它的最佳用途是根据缩略图,找出原图。

实际应用中,往往采用更强大的pHash算法和SIFT算法,它们能够识别图片的变形。只要变形程度不超过25%,它们就能匹配原图。这些算法虽然更复杂,但是原理与上面的简便算法是一样的,就是先将图片转化成Hash字符串,然后再进行比较。

下面我们来看下上述理论用java来做一个DEMO版的具体实现:

[java]  view plain  copy
  1.  import java.awt.Graphics2D;  
  2. import java.awt.color.ColorSpace;  
  3. import java.awt.image.BufferedImage;  
  4. import java.awt.image.ColorConvertOp;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileNotFoundException;  
  8. import java.io.InputStream;  
  9.   
  10. import javax.imageio.ImageIO;  
  11. /* 
  12. * pHash-like image hash.  
  13. * Author: Elliot Shepherd ([email protected] 
  14. * Based On: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html 
  15. */  
  16. public class ImagePHash {  
  17.   
  18.    private int size = 32;  
  19.    private int smallerSize = 8;  
  20.      
  21.    public ImagePHash() {  
  22.        initCoefficients();  
  23.    }  
  24.      
  25.    public ImagePHash(int size, int smallerSize) {  
  26.        this.size = size;  
  27.        this.smallerSize = smallerSize;  
  28.          
  29.        initCoefficients();  
  30.    }  
  31.      
  32.    public int distance(String s1, String s2) {  
  33.        int counter = 0;  
  34.        for (int k = 0; k < s1.length();k++) {  
  35.            if(s1.charAt(k) != s2.charAt(k)) {  
  36.                counter++;  
  37.            }  
  38.        }  
  39.        return counter;  
  40.    }  
  41.      
  42.    // Returns a 'binary string' (like. 001010111011100010) which is easy to do a hamming distance on.   
  43.    public String getHash(InputStream is) throws Exception {  
  44.        BufferedImage img = ImageIO.read(is);  
  45.          
  46.        /* 1. Reduce size.  
  47.         * Like Average Hash, pHash starts with a small image.  
  48.         * However, the image is larger than 8x8; 32x32 is a good size.  
  49.         * This is really done to simplify the DCT computation and not  
  50.         * because it is needed to reduce the high frequencies. 
  51.         */  
  52.        img = resize(img, size, size);  
  53.          
  54.        /* 2. Reduce color.  
  55.         * The image is reduced to a grayscale just to further simplify  
  56.         * the number of computations. 
  57.         */  
  58.        img = grayscale(img);  
  59.          
  60.        double[][] vals = new double[size][size];  
  61.          
  62.        for (int x = 0; x < img.getWidth(); x++) {  
  63.            for (int y = 0; y < img.getHeight(); y++) {  
  64.                vals[x][y] = getBlue(img, x, y);  
  65.            }  
  66.        }  
  67.          
  68.        /* 3. Compute the DCT.  
  69.         * The DCT separates the image into a collection of frequencies  
  70.         * and scalars. While JPEG uses an 8x8 DCT, this algorithm uses  
  71.         * a 32x32 DCT. 
  72.         */  
  73.        long start = System.currentTimeMillis();  
  74.        double[][] dctVals = applyDCT(vals);  
  75.        System.out.println("DCT: " + (System.currentTimeMillis() - start));  
  76.          
  77.        /* 4. Reduce the DCT.  
  78.         * This is the magic step. While the DCT is 32x32, just keep the  
  79.         * top-left 8x8. Those represent the lowest frequencies in the  
  80.         * picture. 
  81.         */  
  82.        /* 5. Compute the average value.  
  83.         * Like the Average Hash, compute the mean DCT value (using only  
  84.         * the 8x8 DCT low-frequency values and excluding the first term  
  85.         * since the DC coefficient can be significantly different from  
  86.         * the other values and will throw off the average). 
  87.         */  
  88.        double total = 0;  
  89.          
  90.        for (int x = 0; x < smallerSize; x++) {  
  91.            for (int y = 0; y < smallerSize; y++) {  
  92.                total += dctVals[x][y];  
  93.            }  
  94.        }  
  95.        total -= dctVals[0][0];  
  96.          
  97.        double avg = total / (double) ((smallerSize * smallerSize) - 1);  
  98.      
  99.        /* 6. Further reduce the DCT.  
  100.         * This is the magic step. Set the 64 hash bits to 0 or 1  
  101.         * depending on whether each of the 64 DCT values is above or  
  102.         * below the average value. The result doesn't tell us the  
  103.         * actual low frequencies; it just tells us the very-rough  
  104.         * relative scale of the frequencies to the mean. The result  
  105.         * will not vary as long as the overall structure of the image  
  106.         * remains the same; this can survive gamma and color histogram  
  107.         * adjustments without a problem. 
  108.         */  
  109.        String hash = "";  
  110.          
  111.        for (int x = 0; x < smallerSize; x++) {  
  112.            for (int y = 0; y < smallerSize; y++) {  
  113.                if (x != 0 && y != 0) {  
  114.                    hash += (dctVals[x][y] > avg?"1":"0");  
  115.                }  
  116.            }  
  117.        }  
  118.          
  119.        return hash;  
  120.    }  
  121.      
  122.    private BufferedImage resize(BufferedImage image, int width,    int height) {  
  123.        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);  
  124.        Graphics2D g = resizedImage.createGraphics();  
  125.        g.drawImage(image, 00, width, height, null);  
  126.        g.dispose();  
  127.        return resizedImage;  
  128.    }  
  129.      
  130.    private ColorConvertOp colorConvert = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);  
  131.   
  132.    private BufferedImage grayscale(BufferedImage img) {  
  133.        colorConvert.filter(img, img);  
  134.        return img;  
  135.    }  
  136.      
  137.    private static int getBlue(BufferedImage img, int x, int y) {  
  138.        return (img.getRGB(x, y)) & 0xff;  
  139.    }  
  140.      
  141.    // DCT function stolen from http://stackoverflow.com/questions/4240490/problems-with-dct-and-idct-algorithm-in-java  
  142.   
  143.    private double[] c;  
  144.    private void initCoefficients() {  
  145.        c = new double[size];  
  146.          
  147.        for (int i=1;i<size;i++) {  
  148.            c[i]=1;  
  149.        }  
  150.        c[0]=1/Math.sqrt(2.0);  
  151.    }  
  152.      
  153.    private double[][] applyDCT(double[][] f) {  
  154.        int N = size;  
  155.          
  156.        double[][] F = new double[N][N];  
  157.        for (int u=0;u<N;u++) {  
  158.          for (int v=0;v<N;v++) {  
  159.            double sum = 0.0;  
  160.            for (int i=0;i<N;i++) {  
  161.              for (int j=0;j<N;j++) {  
  162.                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]);  
  163.              }  
  164.            }  
  165.            sum*=((c[u]*c[v])/4.0);  
  166.            F[u][v] = sum;  
  167.          }  
  168.        }  
  169.        return F;  
  170.    }  
  171.   
  172.    public static void main(String[] args) {  
  173.          
  174.        ImagePHash p = new ImagePHash();  
  175.        String image1;  
  176.        String image2;  
  177.        try {  
  178.            image1 = p.getHash(new FileInputStream(new File("C:/Users/june/Desktop/1.jpg")));  
  179.            image2 = p.getHash(new FileInputStream(new File("C:/Users/june/Desktop/1.jpg")));  
  180.            System.out.println("1:1 Score is " + p.distance(image1, image2));  
  181.            image1 = p.getHash(new FileInputStream(new File("C:/Users/june/Desktop/1.jpg")));  
  182.            image2 = p.getHash(new FileInputStream(new File("C:/Users/june/Desktop/2.jpg")));  
  183.            System.out.println("1:2 Score is " + p.distance(image1, image2));  
  184.            image1 = p.getHash(new FileInputStream(new File("C:/Users/june/Desktop/1.jpg")));  
  185.            image2 = p.getHash(new FileInputStream(new File("C:/Users/june/Desktop/3.jpg")));  
  186.            System.out.println("1:3 Score is " + p.distance(image1, image2));  
  187.            image1 = p.getHash(new FileInputStream(new File("C:/Users/june/Desktop/2.jpg")));  
  188.            image2 = p.getHash(new FileInputStream(new File("C:/Users/june/Desktop/3.jpg")));  
  189.            System.out.println("2:3 Score is " + p.distance(image1, image2));  
  190.              
  191.            image1 = p.getHash(new FileInputStream(new File("C:/Users/june/Desktop/4.jpg")));  
  192.            image2 = p.getHash(new FileInputStream(new File("C:/Users/june/Desktop/5.jpg")));  
  193.            System.out.println("4:5 Score is " + p.distance(image1, image2));  
  194.              
  195.        } catch (FileNotFoundException e) {  
  196.            e.printStackTrace();  
  197.        } catch (Exception e) {  
  198.            e.printStackTrace();  
  199.        }  
  200.   
  201.    }  
  202. }   

运行结果为:

[java]  view plain  copy
  1. DCT: 163  
  2. DCT: 158  
  3. 1:1 Score is 0  
  4. DCT: 168  
  5. DCT: 164  
  6. 1:2 Score is 4  
  7. DCT: 156  
  8. DCT: 156  
  9. 1:3 Score is 3  
  10. DCT: 157  
  11. DCT: 157  
  12. 2:3 Score is 1  
  13. DCT: 157  
  14. DCT: 156  
  15. 4:5 Score is 21  
说明:其中1,2,3是3张非常相似的图片,图片分别加了不同的文字水印,肉眼分辨的不是太清楚,下面会有附图,4、5是两张差异很大的图,图你可以随便找来测试,这两张我就不上传了。

结果说明:汉明距离越大表明图片差异越大,如果不相同的数据位不超过5,就说明两张图片很相似;如果大于10,就说明这是两张不同的图片。从结果可以看到1、2、3是相似图片,4、5差异太大,是两张不同的图片。

附:图1、2、3

图1

图2

图3

参考地址:

代码参考: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