iOS Question Example GPUImage Bulge Distortion Filter and Face Detection

naifnas

Active Member
Licensed User
Hi all
This 2 small Example
First example GPUImage Bulge Distortion Filter and Face Detection
next Filter and Face Detection
maybe Weak simple example
It enlarges part of the image, suitable for making facial, eye and nose expressions
First example need add GPUImageFramework.
next example dont need ..
The two examples may contain notes. I wish to know.
I do this just for fun and hobby.
B4X:
#Region  Project Attributes
    #ApplicationLabel: B4i Example
    #Version: 1.0.0
    'Orientation possible values: Portrait, LandscapeLeft, LandscapeRight and PortraitUpsideDown
    #iPhoneOrientations: Portrait, LandscapeLeft, LandscapeRight
    #iPadOrientations: Portrait, LandscapeLeft, LandscapeRight, PortraitUpsideDown
    #Target: iPhone, iPad
    #ATSEnabled: True
    #MinVersion: 8
        #PlistExtra:<key>NSFaceIDUsageDescription</key><string>Uses n</string>


'    #PlistExtra: <key>UIBackgroundModes</key><array><string>fetch</string></array>
    #PlistExtra: <key>UIFileSharingEnabled</key><true/>

    #PlistExtra:<key>NSPhotoLibraryUsageDescription</key><string>For Select Photos From The Album </string>
    #PlistExtra:<key>NSPhotoLibraryAddUsageDescription</key><string>For Add Project Photos To The Photo Album</string>
    #PlistExtra: <key>UIViewControllerBasedStatusBarAppearance</key><false/>
    #PlistExtra: <key>NSCameraUsageDescription</key><string>App WriteToGif requires To access your photo library To show image on profile And send via chat</string>

#End Region

Sub Process_Globals
    Public App As Application
    Public NavControl As NavigationController
    Private Page1 As Page
    Private Panel1 As Panel
    Private Button5 As Button
    Private Button2 As Button
    Private Button1 As Button
    Private Label1 As Label
    Private Label2 As Label
End Sub

Private Sub Application_Start (Nav As NavigationController)
    NavControl = Nav
    Page1.Initialize("Page1")
    Page1.RootPanel.LoadLayout("Page1")
    NavControl.ShowPage(Page1)
'    Panel2.Color=Colors.Black
'    App.KeyController = NavControl
End Sub
Sub Button1_Click
    Private ImageView5 As ImageView
    ImageView5.Initialize("ImageView5")
'    Panel2.RemoveAllViews
    Panel1.AddView(ImageView5,0,0,100,100)
'    Panel2.AddView(ImageView7,0,0,100,100)
    ImageView5.Bitmap= LoadBitmap(File.DirAssets,"me.png")'ImageView1.Bitmap
'    ImageView5.ContentMode=ImageView5.MODE_FILL
    ImageView5.SizeToFit
    Private noMe As NativeObject = Me
    Dim o As Object
    noMe.RunMethod("markFaces250::",Array( ImageView5,Label2))
'    Panel1.AddView(o,0,300,300,300)

    Log(o)
End Sub
Sub Button2_Click
    Dim o As Object
    Dim no As NativeObject =Me
    App.KeyController=no.RunMethod("application2",Null)
    'Panel1.AddView(o,0,0,100%x,100%y)
'    Button1_Click
End Sub


Sub Page1_Click
End Sub

'//#import <XCTest/XCTest.h>
#If OBJC
          
        
    
#import <Photos/Photos.h>





#end if
#if objc

// ايحاد زاوية الوجه مطلوب
- (CGFloat)GetAngleWithRadius:(UIImageView *)facePicture
{
       CGFloat exifOrientation = 6;
    facePicture.left =0 ;
    facePicture.top =0 ;
 
    CGAffineTransform transform = CGAffineTransformMakeScale(1, -1);
     transform = CGAffineTransformTranslate(transform, 0, -facePicture.bounds.size.height);
    
    CIImage* image = [CIImage imageWithCGImage:facePicture.image.CGImage];

    CIContext *context = [CIContext context];
    CIDetector* detector = [CIDetector detectorOfType:CIDetectorTypeFace  context
                                  :context options
                                  :[NSDictionary dictionaryWithObject
                                  :CIDetectorAccuracyHigh forKey:CIDetectorAccuracy]];
                                            
    NSArray *features = [detector featuresInImage:image  options:@{ CIDetectorSmile : @YES,
                                                         CIDetectorEyeBlink : @YES,
                                                         CIDetectorImageOrientation :[NSNumber numberWithInt:6] }];

    for(int i = 0; i < [features count]; i++)
    {
        CIFaceFeature* faceFeature = features[i];
         if (faceFeature.hasFaceAngle) {
              CGFloat faceAngle = faceFeature.faceAngle ;   
            return faceAngle;
        }
    }
    
    return 0;
}

// دوران الصورة حسب الزاوية  مطلوب
static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees :(UIImage*) Image
{   
    // calculate the size of the rotated view's containing box for our drawing space
    UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,Image.size.width, Image.size.height)];
    CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
    rotatedViewBox.transform = t;
    CGSize rotatedSize = rotatedViewBox.frame.size;

    // Create the bitmap context
    UIGraphicsBeginImageContext(rotatedSize);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();

    // Move the origin to the middle of the image so we will rotate and scale around the center.
    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

    //   // Rotate the image context
    CGContextRotateCTM(bitmap, DegreesToRadians(degrees));

    // Now, draw the rotated/scaled image into the context
    CGContextScaleCTM(bitmap, 1.0, -1.0);
    CGContextDrawImage(bitmap, CGRectMake(-Image.size.width / 2, -Image.size.height / 2, Image.size.width, Image.size.height), Image.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;

}


- (UIColor *)getColorBetweenColor:(UIColor *)color1 :(UIColor *)color2 :(CGFloat)percent {
    CGFloat red1, green1, blue1, alpha1;
    CGFloat red2, green2, blue2, alpha2;

    [color1 getRed:&red1 green:&green1 blue:&blue1 alpha:&alpha1];
    [color2 getRed:&red2 green:&green2 blue:&blue2 alpha:&alpha2];

    double resultRed = red1 + percent * (red2 - red1);
    double resultGreen = green1 + percent * (green2 - green1);
    double resultBlue = blue1 + percent * (blue2 - blue1);

    return [UIColor colorWithRed:resultRed green:resultGreen blue:resultBlue alpha:1];
}


- (BOOL)colorbool:(UIColor *)color1
             :(UIColor *)color2
            :(CGFloat)tolerance {

    CGFloat r1, g1, b1, a1, r2, g2, b2, a2;
    [color1 getRed:&r1 green:&g1 blue:&b1 alpha:&a1];
    [color2 getRed:&r2 green:&g2 blue:&b2 alpha:&a2];

    return
        fabs(r1 - r2) <= tolerance &&
        fabs(g1 - g2) <= tolerance &&
        fabs(b1 - b2) <= tolerance &&
        fabs(a1 - a2) <= tolerance;
}

// ايجاد لون النقاط مطلوب
- (UIColor *)colorAtPixel:(CGPoint)point :(UIImage *)image {

    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), point)) {
        return nil;
    }

    // Create a 1x1 pixel byte array and bitmap context to draw the pixel into.
    NSInteger pointX = trunc(point.x);
    NSInteger pointY = trunc(point.y);
    CGImageRef cgImage = image.CGImage;
    NSUInteger width = image.size.width;
    NSUInteger height = image.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * 1;
    NSUInteger bitsPerComponent = 8;
    unsigned char pixelData[4] = { 0, 0, 0, 0 };
    CGContextRef context = CGBitmapContextCreate(pixelData, 1, 1, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy);

    // Draw the pixel we are interested in onto the bitmap context
    CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
    CGContextRelease(context);

    // Convert color values [0..255] to floats [0.0..1.0]
    CGFloat red   = (CGFloat)pixelData[0] / 255.0f;
    CGFloat green = (CGFloat)pixelData[1] / 255.0f;
    CGFloat blue  = (CGFloat)pixelData[2] / 255.0f;
    CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;

    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

// ايجاد لون الوجه مطلوب
- (UIColor *) GetcolorsFace :(UIImageView *)facePicture :(CGSize)size :(CGPoint)PointStart {
    CGFloat totalR  = 0;
    CGFloat totalG  = 0;
    CGFloat totalB  = 0;
    CGPoint PointLocatin ;
 //    NSMutableArray * colors = [[NSMutableArray alloc] init];

    for (int f=0; f<size.height-1; f++){

            for (int ff=0; ff<size.width-1; ff++){
                PointLocatin = CGPointMake(PointStart.x+ff,PointStart.y+f);
                
                UIColor * color  = [self colorAtPixel: PointLocatin:facePicture.image ];
                if (!color){
                    break ;
                }
                const CGFloat* components = CGColorGetComponents([color CGColor]);
                totalR = totalR + components[0] ;
                totalG = totalG + components[1] ;
                totalB = totalB + components[2] ;
    

            }
    }


        CGFloat Sizes= ((size.height-1)*(size.width-1)) ;
        totalR = totalR / Sizes ;
        totalG = totalG / Sizes ;
        totalB = totalB / Sizes ;
    UIColor * colornew = [UIColor colorWithRed: totalR green: totalG blue: totalB alpha: 1.0];
    return colornew;


}


//------------------------------------       


// ايجاد محتويات  المصفوفة الاكثر مطلوب
-(float)findMax:array :obj {
    float max = [[[array objectAtIndex:0] objectForKey:obj] floatValue];
    for ( NSDictionary *dict in array ) {
        if(max<[[dict objectForKey:obj] floatValue])
        {
         max=[[dict objectForKey:obj] floatValue];
         NSLog(@" MaximumValue = %f", max);
        }
    }
    return max;
}

// تحويل اللون من رقم الى اربج
- (UIColor *)UIColorFromRGB:(NSInteger)rgbValue {
    return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0
                           green:((float)((rgbValue & 0xFF00) >> 8))/255.0
                            blue:((float)(rgbValue & 0xFF))/255.0
                           alpha:1.0];
}

-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{

        NSMutableArray* names = [NSMutableArray arrayWithObjects:@"Andy", @"Bart", @"Bob", nil];
        NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
        NSArray* namesStartingWithB = [names filteredArrayUsingPredicate: predicate];
        // namesStartingWithB now contains @"Bart" & @"Bob"
}



// العام
-(void)markFaces250:(UIImageView *)facePicture :(UIView*)lblface  {


       CGFloat exifOrientation = 6;
     NSLog(@"facePicture.imageOrientation is %d", facePicture.image.imageOrientation);
//    const vertices ARBodyTrackingConfiguration(); //[anchor.geometry.vertices[9]]; // nose
     facePicture.left =0 ;
     facePicture.top =0 ;
 
       CGFloat widthorginal = facePicture.image.size.width ;
     CGFloat heighorginal = facePicture.image.size.height ;
 // تعديل الصورة حسب الزاوية************************************
         CGFloat faceAngleGet   ;   
        faceAngleGet =[ self GetAngleWithRadius :facePicture] ;// حساب الزاوية
        facePicture.image =[ self imageRotatedByDegrees:90-faceAngleGet :facePicture.image ];//دوران

 //*************************************************************
     facePicture.left =0 ;
     facePicture.top =0 ;


     // تغيير حجم الصورة
    CGSize newSize = CGSizeMake(widthorginal,heighorginal) ;
     UIGraphicsBeginImageContext(newSize);
    [facePicture.image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImages = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    facePicture.image=newImages ;
     NSLog(@"widthorginal. is %f", widthorginal);
     NSLog(@"heighorginal. is %f", heighorginal);



CIImage* image = [CIImage imageWithCGImage:facePicture.image.CGImage];
//-----------------------
    // create an array containing all the detected faces from the detector   
    NSDictionary *options = @{ CIDetectorSmile: @(YES), CIDetectorEyeBlink: @(YES),};
    CIContext *context = [CIContext context];
    CIDetector *smileDetector = [CIDetector detectorOfType:CIDetectorTypeFace
                            context:nil
                            options:@{CIDetectorTracking: @YES,
                            CIDetectorAccuracy: CIDetectorAccuracyHigh}];
//------------------------
    CIDetector* detector = [CIDetector detectorOfType:CIDetectorTypeFace
             context:context options:[NSDictionary dictionaryWithObject:CIDetectorAccuracyHigh forKey:CIDetectorAccuracy]];

                                            
//    NSArray *features = [detector featuresInImage:image options:@{CIDetectorSmile:@YES}];
    NSArray *features = [detector featuresInImage:image  options:@{ CIDetectorSmile : @YES,
                                                         CIDetectorEyeBlink : @YES,
                                                         CIDetectorImageOrientation :[NSNumber numberWithInt:exifOrientation] }];

    NSLog(@"Number of faces %d",[features count]);
     CGAffineTransform transform = CGAffineTransformMakeScale(1, -1);
     transform = CGAffineTransformTranslate(transform, 0, -facePicture.bounds.size.height);

//for(CIFaceFeature* faceFeature in features)
//{
for(int i = 0; i < [features count]; i++)
{
CIFaceFeature* faceFeature = features[i];

 
    // Get the face rect: Translate CoreImage coordinates to UIKit coordinates
    const CGRect faceRect = CGRectApplyAffineTransform(faceFeature.bounds, transform);

        UIView* faceView = [[UIView alloc] initWithFrame:CGRectMake(faceFeature.bounds.origin.x,
                              facePicture.image.size.height-faceFeature.bounds.origin.y - faceFeature.bounds.size.height,
                              faceFeature.bounds.size.width,
                              faceFeature.bounds.size.height)];
    faceView = [[UIView alloc] initWithFrame:faceRect];
   //  faceView.layer.backgroundColor = [[UIColor redColor] CGColor];
   faceView.layer.borderWidth = 3;
    faceView.layer.borderColor = [[UIColor redColor] CGColor];
 

//   يضبط اطار  الوجه
    faceView.transform = CGAffineTransformMakeRotation(((faceFeature.faceAngle) * M_PI)/180 );//(M_PI_2); //rotation in radians

   [facePicture addSubview:faceView];

    CGFloat faceWidth = faceFeature.bounds.size.width;
    CGFloat faceheight = faceFeature.bounds.size.height;
       if (faceheight >=  faceWidth) {
        faceWidth = faceFeature.bounds.size.height;
        faceheight = faceFeature.bounds.size.width;
    }else{
        faceWidth = faceFeature.bounds.size.width;
        faceheight = faceFeature.bounds.size.height;
    }

    faceheight =faceView.frame.size.width ;
 //   [facePicture addSubview:faceView];
 //   [pic addSubview:faceView];


 //   رسم خط بين العينين
    UIBezierPath *path = [UIBezierPath bezierPath];
   const CGPoint rightEyePos1 = CGPointApplyAffineTransform(faceFeature.rightEyePosition, transform);
   const CGPoint leftEyePos1 = CGPointApplyAffineTransform(faceFeature.leftEyePosition, transform);

    CGFloat PointX  = rightEyePos1.x ;
    CGFloat PointX1  = leftEyePos1.x ;
    CGFloat PointY  = rightEyePos1.y ;
    CGFloat PointY1  = leftEyePos1.y ;

    [path moveToPoint:CGPointMake(PointX,PointY)];
    [path addLineToPoint:CGPointMake(PointX1,PointY1)];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
    shapeLayer.lineWidth = 3.0;
    shapeLayer.fillColor = [[UIColor blueColor] CGColor];
    [facePicture.layer addSublayer:shapeLayer];
    
 //   ايجاد مركز نقطة بين العينين
    CGFloat PointXc  = PointX-((PointX-PointX1)/2) ;
    CGFloat PointYc  = PointY-((PointY-PointY1)/2) ;
 
    CGFloat PointYc1  = facePicture.image.size.height-faceFeature.bounds.origin.y  ;
    const CGPoint mouthPos1 = CGPointApplyAffineTransform(faceFeature.mouthPosition, transform);

      NSLog(@"mouthPos1.y : %f",mouthPos1.y);


// ايجاد النقاط من  منتصف العينين الى اسفل الوجه
    CGPoint fromPointA = CGPointMake(mouthPos1.x, PointYc) ;
    NSArray *getNumberOfPointsA ;// = [[NSArray alloc] init];
    getNumberOfPointsA = [self getNumberOfPoints9 :20 :fromPointA :mouthPos1 :faceWidth];
// مركز نقطة منتصف العين
//    CGPoint fromPointAa = [getNumberOfPointsA[0] CGPointValue];


    // مركز نقطة اسفل الوجه
     CGPoint fromPointAr = [getNumberOfPointsA[[getNumberOfPointsA count]-10] CGPointValue];// نقطة اسفل الوجه

    // مركز نقطة االانف
// المسافة بين الفم ومنتصف العين
    CGFloat DistansMoEyes =sqrt(pow((fromPointA.x-mouthPos1.x),2)+pow((fromPointA.y-mouthPos1.y),2)) ;

    CGFloat PointXNose  =mouthPos1.x ;  // PointXc-((PointXc-fromPointAaS.x)/3) ;
    CGFloat PointYNose  =mouthPos1.y-(DistansMoEyes/2 ) ;  // PointYc-((PointYc-fromPointAaS.y)/3) ;
    
    //رسم دائرة الانف
    #define myColor [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0]

    
    UIColor *lightGreen = [UIColor colorWithRed:100.0/255.0 green:178.0f/255.0f        blue:238.0f/255.0f alpha:1.0f];

    UIBezierPath *path11 = [UIBezierPath bezierPath];

 
// رسم دائرة اسفل الوجه
    CAShapeLayer *circleLayer9 = [CAShapeLayer layer];
    [circleLayer9 setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(fromPointAr.x-7.5,
               fromPointAr.y-7.5, 15, 15)] CGPath]];
    circleLayer9.strokeColor = [[UIColor yellowColor] CGColor];
    circleLayer9.fillColor = [[UIColor yellowColor] CGColor];
    circleLayer9.lineWidth = 3.0;
    [facePicture.layer addSublayer:circleLayer9];


// مد خط من اسفل الوجه الى الراس اعلى
    NSArray *getNumberOfPointsA1 ;// = [[NSArray alloc] init];
    getNumberOfPointsA1 = [self getNumberOfPoints90 :20 :fromPointA :fromPointAr :faceWidth];
    CGPoint fromPointAa = [getNumberOfPointsA1[0] CGPointValue];

    UIBezierPath *path119 = [UIBezierPath bezierPath];

    //مركز نقطة اعلى الوجه
     CGPoint fromPointAr1 = [getNumberOfPointsA1[[getNumberOfPointsA1 count]-1] CGPointValue];//نقطة اعلى الوجه
// رسم دائرة اعلى الوجه
    CAShapeLayer *circleLayer90 = [CAShapeLayer layer];
    [circleLayer90 setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(mouthPos1.x-15,
               fromPointAr1.y-15, 30, 30)] CGPath]];
    circleLayer90.strokeColor = [[UIColor redColor] CGColor];
    circleLayer90.fillColor = [[UIColor redColor] CGColor];
    circleLayer90.lineWidth = 3.0;
    [facePicture.layer addSublayer:circleLayer90];

//  ايجاد حدود الوجه من اعلى
// حساب مركز منتصف العين مع العيون
    CGFloat PointmouthX  = mouthPos1.x ;
    CGFloat PointmouthY  = mouthPos1.y ;
//    CGFloat PointY  = rightEyePos1.y ;
//    CGFloat PointY1  = leftEyePos1.y ;
// مد خط العينين
 //   CGFloat longspaceL =sqrt(pow((fromPointA.x-PointX),2)+pow((fromPointA.y-PointY),2)) ; // حساب المسافة بين العينين
// المسافة بين العينين مطلوب
    CGFloat longspaceL =sqrt(pow((PointX1-PointX),2)+pow((PointY1-PointY),2)) ; // حساب المسافة بين العينين
    NSLog(@"  لمسافة بين العينين  : %f",longspaceL);

    NSArray *getNumberOfPointsEysR ;
    NSArray *getNumberOfPointsEysL ;
    getNumberOfPointsEysR = [self getNumberOfPoints90 :5 :rightEyePos1 :leftEyePos1 :longspaceL*3.0];
    getNumberOfPointsEysL = [self getNumberOfPoints90 :5 :leftEyePos1  : rightEyePos1 :longspaceL*3.0];
    CGPoint fromPointEysR = [getNumberOfPointsEysR[[getNumberOfPointsEysR  count]-1] CGPointValue];
    CGPoint fromPointEysL = [getNumberOfPointsEysL[[getNumberOfPointsEysL  count]-1] CGPointValue];

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
    
//  احتساب المسافة بين منتصف العين والفم
    CGFloat FromEyestoM =sqrt(pow((fromPointAr.x-fromPointA.x),2)+pow((fromPointAr.y-fromPointA.y),2)) ;
    NSLog(@"  المسافة بين منتصف العين و والفم : %f",FromEyestoM);


    NSLog(@"عرض الوجه : %f",faceheight);
//  احتساب قرق عرض مع العيون
    CGFloat FromEyestoMainWitHiht =(longspaceL/faceheight)*100 ;
    NSLog(@"احتساب قرق عرض مع العيون %f",FromEyestoMainWitHiht);
//  احتساب قرق  العيون
    NSLog(@"faceheight   %f",faceheight);
    NSLog(@"faceView.frame.size.width %f",faceView.frame.size.width);
    
//****************************************************************
// رسم حدود الوجه *************************************************
 // موقع بداية الوجه
///    CGPoint FacePicLeftTop = CGPointMake(faceFeature.bounds.origin.x
///                        , facePicture.image.size.height-faceFeature.bounds.origin.y - faceFeature.bounds.size.height) ; // موقع مركز الوجه


    CGPoint FacePicLeftTop = CGPointMake(faceView.frame.origin.x
                        , fromPointAr1.y ) ; // موقع مركز الوجه

// ايجاد المسافة بين متصف العين الايسر نهاية الوجه
     CGFloat FaceWidhToCenter =sqrt(pow((mouthPos1.x-FacePicLeftTop.x),2)+pow((fromPointAr1.y-FacePicLeftTop.y),2)) ; // حساب المسافة

     CGFloat FaceWidhToCenterlongL = FaceWidhToCenter-(longspaceL/2) ;
     NSLog(@"  المسافة بين العين الايسر نهاية الوجه %f",FaceWidhToCenterlongL);
//  ايجاد نقطة اخر الوجه يمين
     CGPoint FacePicRightLeftTop = CGPointMake(FacePicLeftTop.x+faceView.frame.size.width , FacePicLeftTop.y);
// ايجاد المسافة بين منتصف العين الايمن بداية الوجه
     CGFloat FaceWidhToCenterRight =sqrt(pow((mouthPos1.x-FacePicRightLeftTop.x),2)+pow((fromPointAr1.y-FacePicRightLeftTop.y),2)) ; // حساب المسافة
 
     CGFloat FaceWidhToCenterlongR = FaceWidhToCenterRight-(longspaceL/2) ;
     NSLog(@" المسافة بين العين الايمن نهاية الوجه %f",FaceWidhToCenterlongR);

// هل التفاف يمين او يسار
       if (FaceWidhToCenterlongL ==  FaceWidhToCenterlongR) {
         NSLog(@" التفاف وسط %@",@" التفاف وسط %@");
    } else {
           if (FaceWidhToCenterlongL >  FaceWidhToCenterlongR) {
             NSLog(@" التفاف يمين %@",@" التفاف يمين %@");
        }else{
             NSLog(@" التفاف يسار %@",@" التفاف يسار %@");
    } }


// مطلوب*************************************
// ايجاد لون الوجه العام

    CGPoint PointStart = CGPointMake(faceFeature.bounds.origin.x
                        , facePicture.image.size.height-faceFeature.bounds.origin.y - faceFeature.bounds.size.height) ; // موقع مركز الوجه

     UIColor * ColorFace = [self GetcolorsFace:facePicture  :faceFeature.bounds.size  :PointStart ];
    lblface.backgroundColor =  [ ColorFace  colorWithAlphaComponent:1.0];
/*
        CAShapeLayer * circleLayereysw12p1mq = [CAShapeLayer layer];
        [circleLayereysw12p1mq setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(150
                   ,50, 80, 80)] CGPath]];
        circleLayereysw12p1mq.strokeColor = [ColorFace CGColor];
        circleLayereysw12p1mq.fillColor = [ColorFace CGColor];
        circleLayereysw12p1mq.lineWidth = 3.0;
        [facePicture.layer addSublayer:circleLayereysw12p1mq];
*/
//---------------------------------------------//


    // LEFT EYE
    if (faceFeature.hasFaceAngle) {
                NSLog(@"faceAngle : %f",faceFeature.faceAngle);
    }
    
    NSLog(@"TEST left eyeblink: %@", faceFeature.leftEyeClosed ? @"YES" : @"NO");
    NSLog(@"TEST right eyeblink: %@", faceFeature.rightEyeClosed ? @"YES" : @"NO");
         if(faceFeature.leftEyeClosed)
        {
            NSLog(@"leftEyeClosed :%@",faceFeature.leftEyeClosed ? @"YES" : @"NO");
        }
         if(faceFeature.rightEyeClosed)
        {
            NSLog(@"rightEyeClosed :%@",faceFeature.rightEyeClosed ? @"YES" : @"NO");
        }
    
    
         if(faceFeature.hasSmile)
        {
            NSLog(@"hasSmile :%@",faceFeature.hasSmile ? @"YES" : @"NO");
        }
            NSLog(@"hasSmile :%@",faceFeature.hasSmile ? @"YES" : @"NO");

    if(faceFeature.hasLeftEyePosition)
    {

        const CGPoint leftEyePos = CGPointApplyAffineTransform(faceFeature.leftEyePosition, transform);

        UIView *leftEyeView = [[UIView alloc] initWithFrame:CGRectMake(leftEyePos.x - faceWidth* 0.3f*0.5f,
                                                                       leftEyePos.y - faceWidth* 0.3f*0.5f
                                                                       ,faceWidth* 0.3f,
                                                                       faceWidth* 0.3f)];
        NSLog(@"Left Eye X = %0.1f Y = %0.1f Width = %0.1f Height = %0.1f",leftEyePos.x - faceWidth* 0.3f*0.5f,
              leftEyePos.y - faceWidth* 0.3f*0.5f,faceWidth* 0.3f,
              faceWidth* 0.3f);

        leftEyeView.backgroundColor = [[UIColor magentaColor] colorWithAlphaComponent:0.3];
        leftEyeView.layer.cornerRadius = faceWidth* 0.3f*0.5;


        [facePicture addSubview:leftEyeView];
        
    }

    // RIGHT EYE
    if(faceFeature.hasRightEyePosition)
    {

        const CGPoint rightEyePos = CGPointApplyAffineTransform(faceFeature.rightEyePosition, transform);


        UIView *rightEye = [[UIView alloc] initWithFrame:CGRectMake(rightEyePos.x - faceWidth* 0.3f*0.5,
                                                                    rightEyePos.y - faceWidth* 0.3f*0.5,
                                                                    faceWidth* 0.3f,
                                                                    faceWidth* 0.3f)];

        NSLog(@"Right Eye X = %0.1f Y = %0.1f Width = %0.1f Height = %0.1f",rightEyePos.x - faceWidth* 0.3f*0.5f,
              rightEyePos.y - faceWidth* 0.3f*0.5f,faceWidth* 0.3f,
              faceWidth* 0.3f);

        rightEye.backgroundColor = [[UIColor blueColor] colorWithAlphaComponent:0.2];
        rightEye.layer.cornerRadius = faceWidth* 0.3f*0.5;
        [facePicture addSubview:rightEye];

    }


    // MOUTH
    if(faceFeature.hasMouthPosition)
    {

        const CGPoint mouthPos = CGPointApplyAffineTransform(faceFeature.mouthPosition, transform);
        UIView* mouth = [[UIView alloc] initWithFrame:CGRectMake(mouthPos.x - faceWidth*0.4f*0.5,
                                                                 mouthPos.y - faceWidth*0.4f*0.5,
                                                                 faceWidth*0.4f,
                                                                 faceWidth*0.4f)];

        NSLog(@"Mouth X = %0.1f Y = %0.1f Width = %0.1f Height = %0.1f",mouthPos.x - faceWidth*0.4f*0.5f,
              mouthPos.y - faceWidth*0.4f*0.5f,faceWidth*0.4f,
              faceWidth*0.4f);


        mouth.backgroundColor = [[UIColor yellowColor] colorWithAlphaComponent:0.3];
        mouth.layer.cornerRadius = faceWidth*0.4f*0.5;
        [facePicture addSubview:mouth];

    }

//        }else{
//        }



        const CGFloat* components = CGColorGetComponents([ColorFace CGColor]);
    // تحويل اللون الى رقم
        float red, green, blue;
        red=components[0];
        green=components[1];
        blue=components[2];
        NSUInteger redInt = (NSUInteger)(red * 255 + 0.5);
        NSUInteger greenInt = (NSUInteger)(green * 255 + 0.5);
        NSUInteger blueInt = (NSUInteger)(blue * 255 + 0.5);

        NSUInteger colorint =(redInt << 16) | (greenInt << 8) | blueInt;


}

}
//معرفة النقاط على مستقيم
- (NSArray * )getNumberOfPoints9:(int)num :(CGPoint)p :(CGPoint)q :(CGFloat)facew {

    NSMutableArray *ret = [NSMutableArray arrayWithCapacity:num];
    CGFloat epsilon = 0.01f ;// (float)num;
    int count = 1;
//    for(float  t = 0;  count <= num ; t += epsilon)
    for(float  t = 0;  t <= 5000 ; t += epsilon)
{
        float x = (1-t)*p.x + t*q.x;
        float y = (1-t)*p.y + t*q.y;
        [ret addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
              CGFloat longspace =sqrt(pow((x-p.x),2)+pow((y-p.y),2)) ;
            if (longspace > facew -(facew* 0.17f)) {
              break;
            }
 
  //      count++;
    }

     NSLog(@"Vector: points made: %d",(int)[ret count]);
     NSLog(@"Vector: epsilon: %f",epsilon);
  //   NSLog(@"Vector: points: %@",ret);
     return [ret copy];
}
//معرفة النقاط على مستقيم رجوع
- (NSArray * )getNumberOfPoints90:(int)num :(CGPoint)p :(CGPoint)q :(CGFloat)facew {

    NSMutableArray *ret = [NSMutableArray arrayWithCapacity:num];
    CGFloat epsilon = 0.01f ;// (float)num;
    int count = 1;
//    for(float  t = 0;  count <= num ; t += epsilon)
    for(float  t = 0;  t <= 5000 ; t -= epsilon)
{
        float x = (1-t)*p.x + t*q.x;
        float y = (1-t)*p.y + t*q.y;
        [ret addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
              CGFloat longspace =sqrt(pow((x-p.x),2)+pow((y-p.y),2)) ;
            if (longspace > (facew* 0.17f)) {
              break;
            }
 
  //      count++;
    }

     NSLog(@"Vector: points made: %d",(int)[ret count]);
  //   NSLog(@"Vector: points: %@",ret);
     return [ret copy];
}

#End If
'UITableView

B4X:
Sub Class_Globals
    
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    
End Sub
#If objc

#import "BulgeClass.h"
      UIImageView *myImage ;
      UIImageView *myImage1 ;
     UISlider *slider ;
     GPUImageBulgeDistortionFilter *ImageFilter ;
     UIImage *inputImage , *FilteredImage ;
    CGPoint location ;
@end

@implementation BulgeClass
@synthesize window = _window;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

//-------------------------------------------------
 -(void)loadslider
{

   CGRect frame = CGRectMake(60, 640.0, 200.0, 10.0);
//    UISlider *slider = [[UISlider alloc] initWithFrame:frame];
    slider = [[UISlider alloc] initWithFrame:frame];

    [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [slider setBackgroundColor:[UIColor clearColor]];
    slider.minimumValue = 0.0;
    slider.maximumValue = 1.0;
    slider.continuous = YES;
    slider.value = 0.5;

    //You can change y axis what you want
    [self.view addSubview:slider];

    UIButton *buttonAplly = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonAplly addTarget:self
               action:@selector(buttonApllyClicked:)
     forControlEvents:UIControlEventTouchUpInside];
    [buttonAplly setTitle:@"Apply" forState:UIControlStateNormal];
    buttonAplly.frame = CGRectMake(80.0, 590.0, 160.0, 40.0);
    [self.view addSubview:buttonAplly];

    UIButton *buttonCamera = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonCamera addTarget:self
               action:@selector(buttonCameraClicked:)
     forControlEvents:UIControlEventTouchUpInside];
    [buttonCamera setTitle:@"Camera" forState:UIControlStateNormal];
    buttonCamera.frame = CGRectMake(0.0, 570.0, 100.0, 40.0);
    [self.view addSubview:buttonCamera];


    UIButton *buttonImage = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonImage addTarget:self
               action:@selector(buttonImageClicked:)
     forControlEvents:UIControlEventTouchUpInside];
    [buttonImage setTitle:@"Image" forState:UIControlStateNormal];
    buttonImage.frame = CGRectMake(0.0, 520.0, 100.0, 40.0);
    [self.view addSubview:buttonImage];

}
-(void)change
{
      CGRect mainScreenFrame = [[UIScreen mainScreen] applicationFrame];   
      CGFloat Width = round(mainScreenFrame.size.width);
      CGFloat height = round(mainScreenFrame.size.height);
    NSLog(@"w %f:",Width );
    NSLog(@"w %f:",height );

         CGFloat Width1 = location.x/Width ;
         CGFloat height1 = location.y/height ;
    NSLog(@"w %f:",Width1 );
    NSLog(@"w %f:",height1 );
 
      [myImage removeFromSuperview];
      CGFloat value= slider.value ;
      [ImageFilter setScale:1.0];
      [ ImageFilter setCenter:CGPointMake(Width1, height1)];
      [ ImageFilter setRadius:value];

      FilteredImage = [ImageFilter imageByFilteringImage:inputImage];
       myImage.image = FilteredImage;
      [self.view addSubview:myImage];

}
-(void) buttonApllyClicked:(UIButton*)sender
 {
      CGRect mainScreenFrame = [[UIScreen mainScreen] applicationFrame];   
      CGFloat Width = round(mainScreenFrame.size.width);
      CGFloat height = round(mainScreenFrame.size.height);
    NSLog(@"w %f:",Width );
    NSLog(@"w %f:",height );

         CGFloat Width1 = location.x/Width ;
         CGFloat height1 = location.y/height ;
    NSLog(@"w %f:",Width1 );
    NSLog(@"w %f:",height1 );
 
      [myImage removeFromSuperview];
//     [myImage1 removeFromSuperview];
      CGFloat value= slider.value ;
      [ImageFilter setScale:1.0];
      [ ImageFilter setCenter:CGPointMake(Width1, height1)];
      [ ImageFilter setRadius:value];

      FilteredImage = [ImageFilter imageByFilteringImage:inputImage];
       myImage.image = FilteredImage;
      [self.view addSubview:myImage];

 }

-(void) buttonCameraClicked:(UIButton*)sender
 {
    [myImage removeFromSuperview];
    [myImage1 removeFromSuperview];
     [self loadViewCamera];
    NSLog(@"كاميرا ");
 }
-(void) buttonImageClicked:(UIButton*)sender
 {
    [videoCamera stopCameraCapture];
     self.view=[self loadViewimage];
    NSLog(@"صورة ");
 }

-(void)sliderAction:(id)sender
{
 //   UISlider *slider = (UISlider*)sender;
    slider = (UISlider*)sender;
    [self change] ;
    NSLog(@"aaa %f", slider.value);
}
//---------------------------------------------------------------
 - (UIViewController*)loadView2
{
   return self ;
}

- (UIView*)loadViewimage
{
 
      [self.view addSubview:myImage1];
      inputImage =[[UIImage alloc] init];
      FilteredImage =[[UIImage alloc] init];
      inputImage = [UIImage imageNamed:@"me.png"];

      ImageFilter = [[GPUImageBulgeDistortionFilter alloc] init];
      [ImageFilter setScale:0.5];
      [ ImageFilter setCenter:CGPointMake(1.0, 1.0)];
      [ ImageFilter setRadius:2.0];

      FilteredImage = [ImageFilter imageByFilteringImage:inputImage];
       myImage.image = FilteredImage;


 //   [filter1 forceProcessingAtSize:view2.sizeInPixels];
    [self.view addSubview:myImage];
// for tuch-------------------

    [myImage setUserInteractionEnabled:YES];
    [myImage setMultipleTouchEnabled:YES];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerTap:)];

    [doubleTap setNumberOfTapsRequired:2];
    [twoFingerTap setNumberOfTouchesRequired:2];

    [myImage addGestureRecognizer:singleTap];
    [myImage addGestureRecognizer:doubleTap];
    [myImage addGestureRecognizer:twoFingerTap];

//------------------------------


    return self.view ;


}
- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer {
    location = [gestureRecognizer locationInView:[gestureRecognizer.view superview]];
      NSLog(@"aaa %f", location.x);
      NSLog(@"aaa %f", location.y);

}

- (void)handleDoubleTap:(UIGestureRecognizer *)gestureRecognizer {
    // double tap zooms in
 //   NSLog(@"beginning handleDoubleTap to zoom");
 //   float newScale = [imageScrollView zoomScale] * ZOOM_STEP;
 //   CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
}

- (void)handleTwoFingerTap:(UIGestureRecognizer *)gestureRecognizer {
    // two-finger tap zooms out
//    float newScale = [imageScrollView zoomScale] / ZOOM_STEP;
//    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
//    [imageScrollView zoomToRect:zoomRect animated:YES];
}


- (void)loadViewCamera
{   

 
   videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
    videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
    
     CGRect mainScreenFrame = [[UIScreen mainScreen] applicationFrame];   
   CGFloat halfWidth = round(mainScreenFrame.size.width / 2.0);
    CGFloat halfHeight = round(mainScreenFrame.size.height / 2.0);   
    view1 = [[GPUImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, halfWidth, halfHeight)];
    view2 = [[GPUImageView alloc] initWithFrame:CGRectMake(halfWidth, 0.0, halfWidth, halfHeight)];
    [self.view addSubview:view1];
    [self.view addSubview:view2];

    GPUImageBulgeDistortionFilter *filter1 = [[GPUImageBulgeDistortionFilter alloc] init];
     [filter1 setScale:0.5];
     [ filter1 setCenter:CGPointMake(1.0, 1.0)];
     [ filter1 setRadius:1.0];
    [filter1 forceProcessingAtSize:view2.sizeInPixels];

    [videoCamera addTarget:view1];
    [videoCamera addTarget:filter1];
    [filter1 addTarget:view2];

    [videoCamera startCameraCapture];
    if (YES==[videoCamera  isRunning])
    {
        NSLog(@"Camera  isRunning ");
    }


}

- (void)loadView
{   

    CGRect mainScreenFrame = [[UIScreen mainScreen] applicationFrame];   
    UIView *primaryView = [[UIView alloc] initWithFrame:mainScreenFrame] ;
    primaryView.backgroundColor = [UIColor blueColor];
    self.view = primaryView;

     [self loadslider] ;
    CGFloat halfWidth = round(mainScreenFrame.size.width / 2.0);
    CGFloat halfHeight = round(mainScreenFrame.size.height / 2.0);   
    view1 = [[GPUImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, halfWidth, halfHeight)];
    view2 = [[GPUImageView alloc] initWithFrame:CGRectMake(halfWidth, 0.0, halfWidth, halfHeight)];
    [self.view addSubview:view1];
    [self.view addSubview:view2];
    
     myImage1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 376, 260)];
      myImage1.image = [UIImage imageNamed:@"me.png"];
      myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 270, 376, 260)];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#End If
IMG_0229.PNG
IMG_0230.PNG
IMG_0231.PNG
IMG_0232.PNG

 

naifnas

Active Member
Licensed User
sorry i forget
this example
 

Attachments

  • Example-face1.zip
    229.3 KB · Views: 235
  • Example-GPU-face1.zip
    231.9 KB · Views: 260
Upvote 0

naifnas

Active Member
Licensed User
this Files GPUImageFramework
Note:
Files GPUImageFramework Copyright (c) 2012, Brad Larson, Ben Cochran, Hugues Lismonde, Keitaroh Kobayashi, Alaric Cole, Matthew Clark, Jacob Gundersen, Chris Williams.
All rights reserved.
 

Attachments

  • GPUImageFramework.zip
    325.6 KB · Views: 235
Upvote 0
Top