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,915評論 18 139
  • 不同圖像灰度不同,邊界處一般會有明顯的邊緣,利用此特征可以分割圖像。需要說明的是:邊緣和物體間的邊界并不等同,邊緣...
    大川無敵閱讀 13,948評論 0 29
  • 巷尾深,腳步輕 打火機一明一滅 呼吸急 誰煽動罪的火 半小時撕扯 半小時蹂躪 黑夜給了她黑色的陰影 黑色的眼睛 黑...
    沐鴿閱讀 345評論 1 1
  • 文/蕭路人 在我接受的知識理念里,我一直都堅定的認同:護膚是女人一生都應該堅持的事業,身為一個女人,在任何時候都不...
    路人記閱讀 35,719評論 136 1,471
  • 愚子讀《論語》十六 《論語·陽貨篇》子曰:“唯女子與小人為難養也,近之則不孫,遠之則怨。” 孔子說:“只有女人和小...
    公子小白ahan閱讀 289評論 0 2