You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合代码实现仅保存拉普拉斯方差>200的非模糊人脸照片?

Solution: Save Only Non-Blurry Face Images

Got it, let's put this together properly. The core idea is to add the blur detection check right before saving each cropped face—only save it if the Laplacian variance is over 200. I also fixed a missing piece in your original code (initializing the face cascade classifier) since that's required for face detection to work.

Full Integrated Code

import cv2

# Initialize the face cascade classifier (critical for face detection)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)  # Assuming you're using the default webcam
sampleN = 0

while True:
    ret, img = cap.read()
    if not ret:
        break  # Exit if we can't read a frame
    
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.2, 8)
    
    for x, y, w, h in faces:
        # Crop the detected face from the grayscale image
        cropped_face = gray[y:y+h, x:x+w]
        
        # Calculate Laplacian variance to check blur
        blur_score = cv2.Laplacian(cropped_face, cv2.CV_64F).var()
        
        # Only save if the face is NOT blurry (variance > 200)
        if blur_score > 200:
            sampleN += 1
            cv2.imwrite(f"./facesData/ID.{sampleN}.jpg", cropped_face)
            print(f"Saved clear face {sampleN} (blur score: {blur_score:.2f})")
            
            # Draw rectangle around the saved face
            cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
        else:
            # Optional: Draw a red rectangle for blurry faces (visual feedback)
            cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 2)
    
    cv2.imshow('user', img)
    
    # Exit early if user presses 'q'
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
    # Stop once we have 20 clear faces
    if sampleN > 20:
        break

cap.release()
cv2.destroyAllWindows()

Key Changes Explained

  • Face Detector Initialization: Added the line to load OpenCV's pre-trained face cascade—without this, detectMultiScale would throw an error.
  • Blur Check Integration: For every detected face, we compute the Laplacian variance directly on the cropped face region (no need to read the saved image later, which is more efficient).
  • Conditional Saving: We only increment sampleN and save the image if the blur score exceeds 200. This ensures we don't count blurry faces toward our 20-sample goal.
  • Visual Feedback: Added colored rectangles—green for saved clear faces, red for blurry ones—to help you see what's happening in real-time.
  • Frame Check: Added a check for ret to handle cases where the webcam fails to capture a frame.

内容的提问来源于stack exchange,提问作者QueensMMAgrad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:40:23