iOS判断图片模糊程度

1.获取灰度图

 -(UIImage*)getGrayscale:(UIImage*)sourceImage
    {
      int width = sourceImage.size.width;
      int height = sourceImage.size.height;
      CGColorSpaceRef colorSpace =  CGColorSpaceCreateDeviceGray();
      CGContextRef context = CGBitmapContextCreate (nil,width,height,8,width,colorSpace,kCGImageAlphaNone);
      CGColorSpaceRelease(colorSpace);
      if (context == NULL) {
      return nil;
   }
    CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);
     UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
    CGContextRelease(context);

return grayImage;
}

2.计算模糊程度(小于500认为是模糊图,这个值可以自己看情况定义)

 double getImgBlurDegree(unsigned char* ImgdataGray, int nWidth, int nHeight)
{
  if(ImgdataGray == NULL || nWidth <= 4 || nHeight <= 4)
{
    return 0.0;
}
int row= nHeight;
int col= nWidth;
int widthstep=nWidth;
double S=0;
unsigned char* data  = ImgdataGray;
for(int x = 1;x<row-1;x+=2)
{
    unsigned char *pre_row=data +(x-1)*widthstep;
    unsigned char *cur_row=data +x*widthstep;
    unsigned char *nex_row=data +(x+1)*widthstep;
    int Sx,Sy;
    for(int y = 1;y<col-1;y+=2)
    {
        Sx=(int)pre_row[y+1]+2*(int)cur_row[y+1]+(int)nex_row[y+1]//一定要转为uchar
        -(int)pre_row[y-1]-2*(int)cur_row[y-1]-(int)nex_row[y-1];
        Sy=(int)nex_row[y-1]+2*(int)nex_row[y]+(int)nex_row[y+1]
        -(int)pre_row[y-1]-2*(int)pre_row[y]-(int)pre_row[y+1];  
        S+=Sx*Sx+Sy*Sy;  
    }  
} 
  return S/(row/2-2)/(col/2-2);  
}

使用

- (double)getImageDimValue:(UIImage *)sourceImage {
if (!sourceImage) {
    return 0;
}
UIImage *grayscale = [self getGrayscale:sourceImage];

CGImageRef imageRef = [grayscale CGImage];
CGFloat width = CGImageGetWidth(imageRef);
CGFloat height = CGImageGetHeight(imageRef);

CGDataProviderRef provider =  CGImageGetDataProvider(imageRef);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
uint8_t *grayscaleData = (uint8_t *)[data bytes];

return  getImgBlurDegree(grayscaleData, width, height);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 不同图像灰度不同,边界处一般会有明显的边缘,利用此特征可以分割图像。需要说明的是:边缘和物体间的边界并不等同,边缘...
    大川无敌阅读 13,968评论 0 29
  • 巷尾深,脚步轻 打火机一明一灭 呼吸急 谁煽动罪的火 半小时撕扯 半小时蹂躏 黑夜给了她黑色的阴影 黑色的眼睛 黑...
    沐鸽阅读 346评论 1 1
  • 文/萧路人 在我接受的知识理念里,我一直都坚定的认同:护肤是女人一生都应该坚持的事业,身为一个女人,在任何时候都不...
    路人记阅读 35,729评论 136 1,471
  • 愚子读《论语》十六 《论语·阳货篇》子曰:“唯女子与小人为难养也,近之则不孙,远之则怨。” 孔子说:“只有女人和小...
    公子小白ahan阅读 289评论 0 2