安卓感知哈希算法

这篇博客详细介绍了如何在安卓平台上实现感知哈希算法,用于图像识别。首先通过缩小图片尺寸到8x8来减少高频和细节,然后将图片转化为64级灰度,接着计算所有像素的平均值。接下来,比较每个像素的灰度值与平均值,大于等于平均值的标记为1,反之为0。最后,将这些比较结果组合成一个字符串作为图片的指纹。这种方法可以用来识别相似图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static String getHash(Bitmap bmp){
	    /**
	     * 第一步,缩小尺寸。
		 * 最快速的去除高频和细节,只保留结构明暗的方法就是缩小尺寸。
		 * 将图片缩小到8x8的尺寸,总共64个像素。摒弃不同尺寸、比例带来的图片差异
	     */
		int width = bmp.getWidth();
	    int height = bmp.getHeight();
	    int newWidth = 8;
	    int newHeight = 8;
	    float scaleWidth = ((float) newWidth) / width;
	    float scaleHeight = ((float) newHeight) / height;
	    Matrix matrix = new Matrix();
	    matrix.postScale(scaleWidth, scaleHeight);
	    Bitmap newbmp = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix,true);
	    /**
	     * 第二步,简化色彩。
		 * 将缩小后的图片,转为64级灰度。也就是说,所有像素点总共只有64种颜色。
	     */
	    int width1 = newbmp.getWidth();   //获取位图的宽
	    int height1 = newbmp.getHeight();  //获取位图的高
	     
	     int []pixels = new int[width1 * height1]; //通过位图的大小创建像素点数组
	     
	     newbmp.getPixels(pixels, 0, width1, 0, 0, width1, height1);
	     int alpha = 0xFF << 24; 
	     for(int i = 0; i < height1; i++) {
	      for(int j = 0; j < width1; j++) {
	       int grey = pixels[width1 * i + j];
	       
	       int red = ((grey  & 0x00FF0000 ) >> 16);
	       int green = ((grey & 0x0000FF00) >> 8);
	       int blue = (grey & 0x000000FF);
	       
	       grey = (int)((float) red * 0.3 + (float)green * 0.59 + (float)blue * 0.11);
	       grey = alpha | (grey << 16) | (grey << 8) | grey;
	       pixels[width1 * i + j] = grey;
	      }
	     }
	     Bitmap result = Bitmap.createBitmap(width1, height1, Config.RGB_565);
	     result.setPixels(pixels, 0, width1, 0, 0, width1, height1);
	     
	     /**
	      * 第三步,计算平均值。
	      * 计算所有64个像素的灰度平均值。
	      */
	     int sum = 0;
	     for(int i=0;i<result.getWidth();i++){
	    	 for(int j=0;j<result.getHeight();j++){
	    		 int x = result.getPixel(i, j);
	    		 sum+=x;
	    	 }
	     }
	     int ave = sum/(result.getWidth()*result.getHeight());
	     
	     
	     /**
	      * 第四步,比较像素的灰度。
		  * 算法的精髓,简单、有趣,又充满深意。
		  * 将每个像素的灰度,与平均值进行比较。大于或等于平均值,记为1;小于平均值,记为0。
	      */
	     StringBuffer sb = new StringBuffer();
	     for(int i=0;i<result.getWidth();i++){
	    	 for(int j=0;j<result.getHeight();j++){
	    		 int x = result.getPixel(i, j);
	    		 if(x>ave){
	    			 sb.append("1");
	    		 }else{
	    			 sb.append("0");
	    		 }
	    	 } 
	     }
	     /**
	      * 第五步,计算哈希值。
	      * 将上一步的比较结果,组合在一起成为一个字符串,这就是这张图片的指纹。组合的次序并不重要,
	      * 只要保证所有图片都采用同样次序就行了(例如,自左到右、自顶向下、big-endian)。
	      */
	     
	     
	      
	 	return sb.toString();

	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值