react-native-vision-camera-spoof-detector
v1.1.24
Published
High-performance face anti-spoofing and liveness detection module for React Native Vision Camera. Uses TensorFlow Lite with GPU acceleration and optimized YUV processing.
Maintainers
Readme
react-native-vision-camera-spoof-detector
High-performance face anti-spoofing and liveness detection module for React Native Vision Camera. Features TensorFlow Lite with GPU acceleration, optimized YUV processing, and real-time blink detection for robust liveness verification.
🎯 Features
- 🚀 Real-time Performance: GPU-accelerated TensorFlow Lite processing for smooth 60fps detection
- 🎯 High Accuracy: Advanced ML models for distinguishing live faces from spoofing attempts
- 👁️ Blink Detection: Native blink detection for enhanced liveness verification
- 📱 Optimized YUV Processing: Efficient image data handling for React Native
- 🔧 Easy Integration: Seamlessly integrates with
react-native-vision-camera - ⚡ Face Stability Tracking: Automatic stable face detection with customizable thresholds
- 🛡️ Face Centering: Intelligent face positioning validation in frame
- 📊 Anti-spoofing Confidence: Detailed confidence scores with multiple detection models
- 🔄 Batched Updates: Optimized state management with minimal re-renders
📋 Requirements
- React Native >= 0.76.0
- React Native Vision Camera
^5.0.0 react-native-vision-camera-worklets^5.0.0- iOS 11.0 or later
react-native-vision-camera-face-detector(required for the face-gated example below)
📦 Installation
Step 1: Install the package
npm install react-native-vision-camera-spoof-detector
# or
yarn add react-native-vision-camera-spoof-detectorStep 2: Install peer dependencies
npm install react-native-vision-camera react-native-reanimated react-native-worklets react-native-vision-camera-worklets react-native-vision-camera-face-detector
# or
yarn add react-native-vision-camera react-native-reanimated react-native-worklets react-native-vision-camera-worklets react-native-vision-camera-face-detectorStep 3: Configure iOS
Install the CocoaPods dependencies from the iOS directory:
cd ios
pod install
cd ..Add a camera usage description to ios/<YourApp>/Info.plist:
<key>NSCameraUsageDescription</key>
<string>This app uses the camera for face liveness verification.</string>Open the generated .xcworkspace in Xcode, or run the app with the React Native CLI. The package pod bundles FaceAntiSpoofing.tflite and declares its TensorFlowLiteSwift and VisionCamera dependencies automatically. No manual model copy is required.
Step 4: Configure Android (if not auto-linked)
Add to android/app/build.gradle:
dependencies {
implementation project(':react-native-vision-camera-spoof-detector')
}Step 5: Link native module (for React Native < 0.60)
react-native link react-native-vision-camera-spoof-detector🚀 Quick Start
Vision Camera 5 uses camera outputs for this package. The anti-spoof output can be combined with the face detector output and enabled only while a face is visible.
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, useWindowDimensions, View } from 'react-native';
import {
Camera,
useCameraDevice,
useCameraPermission,
} from 'react-native-vision-camera';
import { useFaceDetectorOutput } from 'react-native-vision-camera-face-detector';
import { useFaceAntiSpoofFrameOutput } from 'react-native-vision-camera-spoof-detector';
const CameraScreen = () => {
const device = useCameraDevice('front');
const { hasPermission, requestPermission } = useCameraPermission();
const { width: windowWidth, height: windowHeight } = useWindowDimensions();
const [faces, setFaces] = useState([]);
const [detectionError, setDetectionError] = useState(null);
const [spoofResult, setSpoofResult] = useState(null);
useEffect(() => {
if (!hasPermission) requestPermission();
}, [hasPermission, requestPermission]);
const faceDetectorOutput = useFaceDetectorOutput({
cameraFacing: 'front',
autoMode: true,
windowWidth,
windowHeight,
performanceMode: 'fast',
trackingEnabled: true,
onFacesDetected(detectedFaces) {
setDetectionError(null);
setFaces(detectedFaces);
if (detectedFaces.length === 0) setSpoofResult(null);
},
onError(error) {
setDetectionError(error.message);
},
});
const antiSpoofOutput = useFaceAntiSpoofFrameOutput({
onResult(result) {
setSpoofResult(result);
},
});
const outputs = faces.length > 0
? [faceDetectorOutput, antiSpoofOutput]
: [faceDetectorOutput];
if (!hasPermission) return <Message text="Camera permission is required." />;
if (!device) return <Message text="No front camera is available." />;
return (
<View style={styles.container}>
<Camera
style={StyleSheet.absoluteFill}
device={device}
isActive
outputs={outputs}
/>
<View style={styles.statusContainer}>
<Text style={styles.statusText}>
{detectionError ?? `${faces.length} face${faces.length === 1 ? '' : 's'} detected`}
</Text>
<Text style={styles.statusText}>
{faces.length === 0
? 'Waiting for face...'
: spoofResult
? JSON.stringify(spoofResult)
: 'Anti-spoof processing...'}
</Text>
</View>
</View>
);
};
const Message = ({ text }) => (
<View style={styles.messageContainer}>
<Text style={styles.messageText}>{text}</Text>
</View>
);
const styles = StyleSheet.create({
container: { flex: 1 },
messageContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: 24,
},
messageText: { fontSize: 16, textAlign: 'center' },
statusContainer: {
position: 'absolute',
top: 56,
alignSelf: 'center',
paddingHorizontal: 14,
paddingVertical: 8,
borderRadius: 16,
backgroundColor: 'rgba(0, 0, 0, 0.65)',
},
statusText: { color: '#ffffff', fontSize: 14, marginVertical: 2 },
});
export default CameraScreen;The anti-spoof output callback receives a result after native inference. No manual runOnJS, frame processor, or explicit initialization call is required for this output API. The output may be omitted until a face is detected, as shown above.
📚 API Reference
useFaceAntiSpoofFrameOutput(options?)
Creates a Vision Camera 5 camera output for native anti-spoofing inference.
const antiSpoofOutput = useFaceAntiSpoofFrameOutput({
onResult(result) {
console.log(result);
},
onError(error) {
console.error(error);
},
});Pass the returned output in the Camera component's outputs array. The callback runs on the React Native runtime after native inference.
Options: onResult(result) and optional onError(error).
initializeFaceAntiSpoof()
Initializes the native module when an application needs an explicit startup check or model-loading diagnostics. It is not required when using useFaceAntiSpoofFrameOutput().
const success = await initializeFaceAntiSpoof();Returns: Promise<boolean> - True if successful
isFaceAntiSpoofAvailable()
Checks if the module is available on the device.
const available = isFaceAntiSpoofAvailable();Returns: boolean
FaceAntiSpoofingResult
interface FaceAntiSpoofingResult {
isLive: boolean; // Real face (true) or spoof (false)
label: string; // Usually "live", "spoof", or "error"
neuralNetworkScore: number; // 0.0-1.0 confidence
laplacianScore: number; // Image quality score
combinedScore: number; // Weighted average
error?: string; // Error message if any
}🔧 Configuration
// Anti-spoofing sensitivity (0.0-1.0, lower = more lenient)
const antispooflevel = 0.35;
// Liveness verification mode
// 0: Anti-spoofing only
// 1: Anti-spoofing + blink detection
const livenessLevel = 1;
// Customizable thresholds
const FACE_STABILITY_THRESHOLD = 3; // Frames for stable face
const FACE_MOVEMENT_THRESHOLD = 15; // Max pixel movement
const BLINK_THRESHOLD = 0.3; // Eye closure probability
const REQUIRED_BLINKS = 3; // Blinks for liveness
const REQUIRED_CONSECUTIVE_LIVE_FRAMES = 3; // Consecutive live frames
const REAL_LAPLACIAN_THRESHOLD = 3500; // Image quality threshold
const FACE_CENTER_THRESHOLD_X = 0.2; // X-axis tolerance
const FACE_CENTER_THRESHOLD_Y = 0.15; // Y-axis tolerance🎮 Complete Examples
The Quick Start above shows the basic frame-processor integration. For the complete capture flow, face detection, liveness, and UI patterns, see the project wiki.
🔍 Attack Detection Capabilities
The module detects and prevents:
- ✅ Print attacks (photos)
- ✅ Display attacks (screens/tablets)
- ✅ Mask attacks (with blink detection)
- ✅ Replay attacks (videos)
Performance depends on:
- Image quality
- Lighting conditions
- Face angle and positioning
- Device camera specs
⚙️ Performance Tips
- Use
performanceMode: 'fast'in Face Detector - Module automatically batches state updates
- Adjust
FRAME_PROCESSOR_MIN_INTERVAL_MSas needed - GPU acceleration is used automatically when available
- Proper frame release prevents memory leaks
📱 Platform Support
| Platform | Status | GPU | Notes | |----------|--------|-----|-------| | Android | ✅ Supported | Yes | TensorFlow Lite model bundled in the AAR | | iOS | ✅ Supported | CPU | Requires CocoaPods and iOS 11+ | | Web | ❌ No | N/A | Not applicable |
🐛 Troubleshooting
Module won't initialize
const available = isFaceAntiSpoofAvailable();
if (!available) {
console.log('Not available on this device');
}- iOS: run
pod installfrom theiosdirectory and rebuild the app from the generated workspace. - iOS: verify
NSCameraUsageDescriptionexists in the app'sInfo.plist. - Check the initialization promise result and inspect the native logs for model-loading errors.
Low accuracy
- Check lighting conditions
- Ensure face is centered
- Adjust
antispooflevelparameter - Verify the
FaceAntiSpoofing.tflitemodel is bundled (the package does this automatically on iOS)
Performance issues
- Reduce frame processing frequency
- Use lower camera resolution
- Enable fast performance mode
- Check device temperature
Face detection fails
- Ensure clear face visibility
- Check camera permissions
- Verify sufficient lighting
- Check minimum face size threshold
📖 Documentation
🤝 Contributing
Contributions welcome! See CONTRIBUTING.md for guidelines.
📄 License
JESCON TECHNOLOGIES PVT LTD License - see LICENSE file for details.
👨💼 Author
PRAFULDAS M M
- Company: JESCON TECHNOLOGIES PVT LTD
- Location: Thrissur, Kerala, India
- Email: [email protected]
🔗 Quick Links
📞 Support & Community
- 🐛 Report Issues
- 💬 GitHub Discussions
- 📧 Email: [email protected]
🙏 Acknowledgments
Built with:
Made with ❤️ by JESCON TECHNOLOGIES PVT LTD
