Python单图多脸识别方法及基于Kivy开发安卓识别APP入门指导
Hey there! Let's break down your two questions step by step—first tackling multi-face detection in Python, then walking through the Kivy Android app setup for your first project.
In Python, two go-to tools for multi-face detection are OpenCV's Haar Cascade Classifier (lightweight and fast) and MTCNN (more accurate for complex scenarios like angled or partially obscured faces). Here's how to implement both:
Method 1: Using OpenCV Haar Cascade
- First, install OpenCV:
pip install opencv-python
- Write the detection code:
import cv2 # Load pre-trained face detection model (included with OpenCV) face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # Read the target image img = cv2.imread('your_image.jpg') # Convert to grayscale (required for Haar Cascade) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect faces: returns list of (x, y, width, height) coordinates faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) # Draw bounding boxes around detected faces for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) # Display or save the result cv2.imshow('Multi-Face Detection', img) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite('detected_faces.jpg', img)
- Quick parameter explanation:
scaleFactoradjusts image scaling for detection,minNeighborsfilters false positives, andminSizesets the smallest face to detect. Tweak these based on your image's resolution.
Method 2: Using MTCNN (More Accurate)
MTCNN is a deep learning-based detector that handles tricky cases better:
- Install the MTCNN library:
pip install mtcnn
- Implement the detection:
from mtcnn import MTCNN import cv2 # Initialize the detector detector = MTCNN() # Read image and convert to RGB (MTCNN requires RGB input) img = cv2.imread('your_image.jpg') rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Detect faces: returns details like bounding boxes and facial landmarks results = detector.detect_faces(rgb_img) # Draw bounding boxes for result in results: x, y, w, h = result['box'] cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) # Display or save the result cv2.imshow('MTCNN Multi-Face Detection', img) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite('mtcnn_detected.jpg', img)
Since this is your first small project, let's take it slow and steady with four clear phases:
Phase 1: Set Up the Development Environment
First, get your tools ready for Kivy and Android packaging:
- Ensure you have Python 3.7-3.10 installed (Kivy has better stability with these versions)
- Install Kivy and Buildozer (the Android packaging tool):
pip install kivy buildozer
- Environment notes:
- Windows users: Use WSL2 (Ubuntu subsystem) for packaging—Buildozer works better here than native Windows.
- Ubuntu users: Install system dependencies first:
sudo apt-get install -y git zip unzip openjdk-11-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev - Mac users: Install Xcode and Homebrew dependencies (like
openjdk@11) before proceeding.
Phase 2: Build a Basic Kivy Interface
Start with a simple UI that has a "Select Image" button and an area to display images:
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.image import Image from kivy.uix.button import Button class FaceDetectionApp(App): def build(self): layout = BoxLayout(orientation='vertical') # Widget to display images self.image_widget = Image() # Button to trigger image selection self.select_btn = Button(text='选择图片', size_hint=(1, 0.1)) self.select_btn.bind(on_press=self.select_image) layout.add_widget(self.image_widget) layout.add_widget(self.select_btn) return layout def select_image(self, instance): # We'll add image selection and detection logic here later pass if __name__ == '__main__': FaceDetectionApp().run()
Run this code to confirm the basic UI works on your desktop first.
Phase 3: Integrate Face Detection
Combine the face detection code with the Kivy UI, and add image selection functionality:
- Install Plyer to access Android's file picker (works on desktop too):
pip install plyer
- Update the code:
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.image import Image from kivy.uix.button import Button from kivy.graphics.texture import Texture from plyer import filechooser import cv2 from mtcnn import MTCNN class FaceDetectionApp(App): def build(self): # Initialize MTCNN detector once at app start self.detector = MTCNN() layout = BoxLayout(orientation='vertical') self.image_widget = Image() self.select_btn = Button(text='选择图片', size_hint=(1, 0.1)) self.select_btn.bind(on_press=self.select_image) layout.add_widget(self.image_widget) layout.add_widget(self.select_btn) return layout def select_image(self, instance): # Open file picker filechooser.open_file(on_selection=self.on_file_selected) def on_file_selected(self, selection): if not selection: return img_path = selection[0] # Read image and detect faces img = cv2.imread(img_path) rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) results = self.detector.detect_faces(rgb_img) # Draw bounding boxes for result in results: x, y, w, h = result['box'] cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) # Convert OpenCV image to Kivy texture for display buf = cv2.flip(img, 0).tostring() texture = Texture.create(size=(img.shape[1], img.shape[0]), colorfmt='bgr') texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') self.image_widget.texture = texture if __name__ == '__main__': FaceDetectionApp().run()
Test this on your desktop—click the button, select an image, and you'll see the detected faces displayed.
Phase 4: Package into Android APK
- Initialize the Buildozer config file in your project directory:
buildozer init
- Open the generated
buildozer.specfile and modify these key settings:title = FaceDetectionApp(your app's name)package.name = facedetection(lowercase, no spaces)package.domain = org.yourname(e.g.,org.rishabh)requirements = python3,kivy,opencv-python,mtcnn,plyer(list all dependencies)android.permissions = READ_EXTERNAL_STORAGE(add storage access permission)
- Start the packaging process:
buildozer android debug deploy run
The first build will take time (it downloads Android SDK/NDK dependencies). Once done, you'll find the APK in the bin folder—install it on your Android device to test!
内容的提问来源于stack exchange,提问作者RISHABH RAI

