             if features.count > 0 {
                 print("found \(features.count) faces")
                 let imgSize = CGSize(width: Double(image.cgImage!.width), height: (Double(image.cgImage!.height)))
-                self.applyFaceDetection(for: features, size: imgSize, cgImage: image.cgImage!)
+                self.applyFaceDetection(for: features, size: imgSize, image: image)
             } else {
                 print("No faces found")
-                DispatchQueue.main.async {
-                    self.imageLayer().removeFromSuperlayer()
-                }
-            }
-            DispatchQueue.main.sync {
-                self.image = image
+                self.removeImageLayer(image: image)
             }
         }
     }
     
-    private func applyFaceDetection(for features: [AnyObject], size: CGSize, cgImage: CGImage) {
+    private func applyFaceDetection(for features: [AnyObject], size: CGSize, image: UIImage) {
         var rect = features[0].bounds!
         rect.origin.y = size.height - rect.origin.y - rect.size.height
         var rightBorder = Double(rect.origin.x + rect.size.width)

    
    public func set(image: UIImage?, focusOnFaces: Bool) {
        guard focusOnFaces == true else {
            self.image = image
            return
        }
        setImageAndFocusOnFaces(image: image)

            offset.y = -offset.y
        }
        
        var newImage: UIImage
        if self.debugFaceAware {
            // Draw rectangles around detected faces
            let rawImage = UIImage(cgImage: image.cgImage!)
            UIGraphicsBeginImageContext(size)
            rawImage.draw(at: CGPoint.zero)
            
            let context = UIGraphicsGetCurrentContext()
            context!.setStrokeColor(UIColor.red.cgColor)
            context!.setLineWidth(3)
            
            for feature in features[0..<features.count] {
                var faceViewBounds = feature.bounds!
                faceViewBounds.origin.y = size.height - faceViewBounds.origin.y - faceViewBounds.size.height
                
                context!.addRect(faceViewBounds)
                context!.drawPath(using: .stroke)
            }
            
            newImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
        } else {
            newImage = image
        }

        DispatchQueue.main.sync {
            self.image = newImage
            
            let layer = self.imageLayer()
            layer.contents = newImage.cgImage
            layer.frame = CGRect(x: offset.x, y: offset.y, width: finalSize.width, height: finalSize.height)
        }
    }
    
