java:均值哈希实现图像内容相似度比较

雨点打透心脏的1/2处 2022-06-15 23:27 285阅读 0赞

这阵子发现我的图像数据库中有不少内容一样的图像需要剔除,这些内容一样的图像可能尺寸不一样,通道数也可能不一样(灰度/彩色),如下三张图内容完全一样,只是亮度或色彩通道数不同,
这里写图片描述这里写图片描述这里写图片描述
于是想到了用google或baidu的识图功能所用到的“感知哈希算法”来搜索数据库内容一样的图像。
通过这篇文章搞清楚了“感知哈希算法”的基本原理,
《三种基于感知哈希算法的相似图像检索技术》,发现原理很简单,很适合我等粗人,呵呵,于是在java下实现了这个算法的代码 :

java实现

  1. package net.gdface.image;
  2. import java.awt.Graphics;
  3. import java.awt.Image;
  4. import java.awt.color.ColorSpace;
  5. import java.awt.image.BufferedImage;
  6. import java.awt.image.ColorConvertOp;
  7. import java.util.Arrays;
  8. /**
  9. * 均值哈希实现图像指纹比较
  10. * @author guyadong
  11. *
  12. */
  13. public final class FingerPrint {
  14. /**
  15. * 图像指纹的尺寸,将图像resize到指定的尺寸,来计算哈希数组
  16. */
  17. private static final int HASH_SIZE=16;
  18. /**
  19. * 保存图像指纹的二值化矩阵
  20. */
  21. private final byte[] binaryzationMatrix;
  22. public FingerPrint(byte[] hashValue) {
  23. if(hashValue.length!=HASH_SIZE*HASH_SIZE)
  24. throw new IllegalArgumentException(String.format("length of hashValue must be %d",HASH_SIZE*HASH_SIZE ));
  25. this.binaryzationMatrix=hashValue;
  26. }
  27. public FingerPrint(String hashValue) {
  28. this(toBytes(hashValue));
  29. }
  30. public FingerPrint (BufferedImage src){
  31. this(hashValue(src));
  32. }
  33. private static byte[] hashValue(BufferedImage src){
  34. BufferedImage hashImage = resize(src,HASH_SIZE,HASH_SIZE);
  35. byte[] matrixGray = (byte[]) toGray(hashImage).getData().getDataElements(0, 0, HASH_SIZE, HASH_SIZE, null);
  36. return binaryzation(matrixGray);
  37. }
  38. /**
  39. * 从压缩格式指纹创建{@link FingerPrint}对象
  40. * @param compactValue
  41. * @return
  42. */
  43. public static FingerPrint createFromCompact(byte[] compactValue){
  44. return new FingerPrint(uncompact(compactValue));
  45. }
  46. public static boolean validHashValue(byte[] hashValue){
  47. if(hashValue.length!=HASH_SIZE)
  48. return false;
  49. for(byte b:hashValue){
  50. if(0!=b&&1!=b)return false;
  51. }
  52. return true;
  53. }
  54. public static boolean validHashValue(String hashValue){
  55. if(hashValue.length()!=HASH_SIZE)
  56. return false;
  57. for(int i=0;i<hashValue.length();++i){
  58. if('0'!=hashValue.charAt(i)&&'1'!=hashValue.charAt(i))return false;
  59. }
  60. return true;
  61. }
  62. public byte[] compact(){
  63. return compact(binaryzationMatrix);
  64. }
  65. /**
  66. * 指纹数据按位压缩
  67. * @param hashValue
  68. * @return
  69. */
  70. private static byte[] compact(byte[] hashValue){
  71. byte[] result=new byte[(hashValue.length+7)>>3];
  72. byte b=0;
  73. for(int i=0;i<hashValue.length;++i){
  74. if(0==(i&7)){
  75. b=0;
  76. }
  77. if(1==hashValue[i]){
  78. b|=1<<(i&7);
  79. }else if(hashValue[i]!=0)
  80. throw new IllegalArgumentException("invalid hashValue,every element must be 0 or 1");
  81. if(7==(i&7)||i==hashValue.length-1){
  82. result[i>>3]=b;
  83. }
  84. }
  85. return result;
  86. }
  87. /**
  88. * 压缩格式的指纹解压缩
  89. * @param compactValue
  90. * @return
  91. */
  92. private static byte[] uncompact(byte[] compactValue){
  93. byte[] result=new byte[compactValue.length<<3];
  94. for(int i=0;i<result.length;++i){
  95. if((compactValue[i>>3]&(1<<(i&7)))==0)
  96. result[i]=0;
  97. else
  98. result[i]=1;
  99. }
  100. return result;
  101. }
  102. /**
  103. * 字符串类型的指纹数据转为字节数组
  104. * @param hashValue
  105. * @return
  106. */
  107. private static byte[] toBytes(String hashValue){
  108. hashValue=hashValue.replaceAll("\\s", "");
  109. byte[] result=new byte[hashValue.length()];
  110. for(int i=0;i<result.length;++i){
  111. char c = hashValue.charAt(i);
  112. if('0'==c)
  113. result[i]=0;
  114. else if('1'==c)
  115. result[i]=1;
  116. else
  117. throw new IllegalArgumentException("invalid hashValue String");
  118. }
  119. return result;
  120. }
  121. /**
  122. * 缩放图像到指定尺寸
  123. * @param src
  124. * @param width
  125. * @param height
  126. * @return
  127. */
  128. private static BufferedImage resize(Image src,int width,int height){
  129. BufferedImage result = new BufferedImage(width, height,
  130. BufferedImage.TYPE_3BYTE_BGR);
  131. Graphics g = result.getGraphics();
  132. try{
  133. g.drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
  134. }finally{
  135. g.dispose();
  136. }
  137. return result;
  138. }
  139. /**
  140. * 计算均值
  141. * @param src
  142. * @return
  143. */
  144. private static int mean(byte[] src){
  145. long sum=0;
  146. // 将数组元素转为无符号整数
  147. for(byte b:src)sum+=(long)b&0xff;
  148. return (int) (Math.round((float)sum/src.length));
  149. }
  150. /**
  151. * 二值化处理
  152. * @param src
  153. * @return
  154. */
  155. private static byte[] binaryzation(byte[]src){
  156. byte[] dst = src.clone();
  157. int mean=mean(src);
  158. for(int i=0;i<dst.length;++i){
  159. // 将数组元素转为无符号整数再比较
  160. dst[i]=(byte) (((int)dst[i]&0xff)>=mean?1:0);
  161. }
  162. return dst;
  163. }
  164. /**
  165. * 转灰度图像
  166. * @param src
  167. * @return
  168. */
  169. private static BufferedImage toGray(BufferedImage src){
  170. if(src.getType()==BufferedImage.TYPE_BYTE_GRAY){
  171. return src;
  172. }else{
  173. // 图像转灰
  174. BufferedImage grayImage = new BufferedImage(src.getWidth(), src.getHeight(),
  175. BufferedImage.TYPE_BYTE_GRAY);
  176. new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null).filter(src, grayImage);
  177. return grayImage;
  178. }
  179. }
  180. @Override
  181. public String toString() {
  182. return toString(true);
  183. }
  184. /**
  185. * @param multiLine 是否分行
  186. * @return
  187. */
  188. public String toString(boolean multiLine) {
  189. StringBuffer buffer=new StringBuffer();
  190. int count=0;
  191. for(byte b:this.binaryzationMatrix){
  192. buffer.append(0==b?'0':'1');
  193. if(multiLine&&++count%HASH_SIZE==0)
  194. buffer.append('\n');
  195. }
  196. return buffer.toString();
  197. }
  198. @Override
  199. public boolean equals(Object obj) {
  200. if(obj instanceof FingerPrint){
  201. return Arrays.equals(this.binaryzationMatrix,((FingerPrint)obj).binaryzationMatrix);
  202. }else
  203. return super.equals(obj);
  204. }
  205. /**
  206. * 与指定的压缩格式指纹比较相似度
  207. * @param compactValue
  208. * @return
  209. * @see #compare(FingerPrint)
  210. */
  211. public float compareCompact(byte[] compactValue){
  212. return compare(createFromCompact(compactValue));
  213. }
  214. /**
  215. * @param hashValue
  216. * @return
  217. * @see #compare(FingerPrint)
  218. */
  219. public float compare(String hashValue){
  220. return compare(new FingerPrint(hashValue));
  221. }
  222. /**
  223. * 与指定的指纹比较相似度
  224. * @param hashValue
  225. * @return
  226. * @see #compare(FingerPrint)
  227. */
  228. public float compare(byte[] hashValue){
  229. return compare(new FingerPrint(hashValue));
  230. }
  231. /**
  232. * 与指定图像比较相似度
  233. * @param image2
  234. * @return
  235. * @see #compare(FingerPrint)
  236. */
  237. public float compare(BufferedImage image2){
  238. return compare(new FingerPrint(image2));
  239. }
  240. /**
  241. * 比较指纹相似度
  242. * @param src
  243. * @return
  244. * @see #compare(byte[], byte[])
  245. */
  246. public float compare(FingerPrint src){
  247. if(src.binaryzationMatrix.length!=this.binaryzationMatrix.length)
  248. throw new IllegalArgumentException("length of hashValue is mismatch");
  249. return compare(binaryzationMatrix,src.binaryzationMatrix);
  250. }
  251. /**
  252. * 判断两个数组相似度,数组长度必须一致否则抛出异常
  253. * @param f1
  254. * @param f2
  255. * @return 返回相似度(0.0~1.0)
  256. */
  257. private static float compare(byte[] f1,byte[] f2){
  258. if(f1.length!=f2.length)
  259. throw new IllegalArgumentException("mismatch FingerPrint length");
  260. int sameCount=0;
  261. for(int i=0;i<f1.length;++i){
  262. if(f1[i]==f2[i])++sameCount;
  263. }
  264. return (float)sameCount/f1.length;
  265. }
  266. public static float compareCompact(byte[] f1,byte[] f2){
  267. return compare(uncompact(f1),uncompact(f2));
  268. }
  269. public static float compare(BufferedImage image1,BufferedImage image2){
  270. return new FingerPrint(image1).compare(new FingerPrint(image2));
  271. }
  272. }

调用示例

junit测试代码

  1. package test;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import javax.imageio.ImageIO;
  5. import org.junit.Test;
  6. import net.gdface.image.FingerPrint;
  7. import net.gdface.image.NotImage;
  8. import net.gdface.image.UnsupportedFormat;
  9. public class TestFingerPrint {
  10. @Test
  11. public void testCompare() throws IOException{
  12. FingerPrint fp1 = new FingerPrint(ImageIO.read(new File("d:\\tmp\\he049-black.jpg")));
  13. FingerPrint fp2 =new FingerPrint(ImageIO.read(new File("d:\\tmp\\he049-gray.jpg")));
  14. System.out.println(fp1.toString(true));
  15. System.out.printf("sim=%f",fp1.compare(fp2));
  16. }
  17. }

发表评论

表情:
评论列表 (有 0 条评论,285人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Python实现字符串相似比较

    Python实现字符串相似度比较 在日常的开发中,我们可能需要对不同的字符串进行比较,以判断它们之间的相似程度。例如,在搜索引擎、拼写检查和数据清洗等任务中,字符串相似度比较