-
Notifications
You must be signed in to change notification settings - Fork 0
refactor(face-embedding): fix BGR/RGB bug and improve embedding pipeline #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+223
−74
Closed
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3622fad
refactor(face-embedding): fix BGR/RGB bug, concurrent enrollment, cle…
merakleee 9dffd3c
feat(filters): add BlurFilter and BrightnessFilter with auto-correction
merakleee f8abbe5
chore: resolve merge conflict in face embedding imports
merakleee 3502dff
fix: replace ValueError with AppException in image filters
merakleee a8b3d37
Merge branch 'main' into fix/improve_embedding
merakleee b0b603d
Remove duplicate import statement
merakleee e5fbf0e
Add type hints to BaseFilter methods
merakleee File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| from abc import ABC, abstractmethod | ||
| import numpy as np | ||
|
|
||
|
|
||
| class BaseFilter(ABC): | ||
|
|
||
| @abstractmethod | ||
| def verify_image(self, image: np.ndarray) -> bool: | ||
| pass | ||
|
|
||
| @abstractmethod | ||
| def process_image(self, image: np.ndarray) -> np.ndarray: | ||
| pass | ||
|
|
||
|
|
||
| class FilterFactory: | ||
| def __init__(self) -> None: | ||
| from app.service.filters import BlurFilter, BrightnessFilter | ||
|
|
||
| self.filters = { | ||
| "blur_filter": BlurFilter, | ||
| "brightness_filter": BrightnessFilter, | ||
| } | ||
|
|
||
| def get_filter(self, filter_type: str) -> BaseFilter: | ||
| if filter_type in self.filters: | ||
| return self.filters[filter_type]() | ||
| else: | ||
| raise ValueError(f"Invalid filter type: '{filter_type}'") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| import cv2 | ||
| import numpy as np | ||
| from app.service.data_processor import BaseFilter | ||
| from app.core.exceptions import AppException | ||
|
|
||
|
|
||
| class BlurFilter(BaseFilter): | ||
| """ | ||
| Detects if an image is too blurry. | ||
| Uses Laplacian variance — sharp images have high variance, | ||
| blurry images have low variance. | ||
| Blur cannot be fully fixed, but we attempt a sharpening pass once. | ||
| """ | ||
|
|
||
| BLUR_THRESHOLD = 15.0 | ||
|
|
||
| def _measure_blur(self, image: np.ndarray) -> float: | ||
| """Returns the Laplacian variance score. Higher = sharper.""" | ||
| gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | ||
| return cv2.Laplacian(gray, cv2.CV_64F).var() | ||
|
|
||
| def _sharpen(self, image: np.ndarray) -> np.ndarray: | ||
| """Applies an unsharp mask to try to recover some sharpness.""" | ||
| kernel = np.array([ | ||
| [0, -1, 0], | ||
| [-1, 5, -1], | ||
| [0, -1, 0] | ||
| ]) | ||
| return cv2.filter2D(image, -1, kernel) | ||
|
|
||
| def verify_image(self, image: np.ndarray) -> bool: | ||
| score = self._measure_blur(image) | ||
| print( | ||
| f"[BlurFilter] Blur score: {score:.2f} (threshold: {self.BLUR_THRESHOLD})") | ||
| return score >= self.BLUR_THRESHOLD | ||
|
|
||
| def process_image(self, image: np.ndarray) -> np.ndarray: | ||
| # Step 1 — test | ||
| if self.verify_image(image): | ||
| print("[BlurFilter] PASS — image is sharp enough.") | ||
| return image | ||
|
|
||
| print("[BlurFilter] FAIL — image is blurry. Attempting sharpening fix...") | ||
|
|
||
| # Step 2 — fix | ||
| fixed = self._sharpen(image) | ||
|
|
||
| # Step 3 — retest | ||
| if self.verify_image(fixed): | ||
| print("[BlurFilter] PASS after fix — sharpening worked.") | ||
| return fixed | ||
|
|
||
| # Step 4 — reject | ||
| raise AppException.image_blur_error( | ||
| f"Image is too blurry (score: {self._measure_blur(image):.2f}, threshold: {self.BLUR_THRESHOLD}) and could not be recovered." | ||
| ) | ||
|
|
||
|
|
||
| class BrightnessFilter(BaseFilter): | ||
| """ | ||
| Detects if an image is too dark or too bright. | ||
| Uses the mean pixel value of the grayscale image. | ||
| Attempts gamma correction as a fix. | ||
| """ | ||
|
|
||
| MIN_BRIGHTNESS = 70 # below this = too dark | ||
| MAX_BRIGHTNESS = 220 # above this = too bright | ||
|
|
||
| def _measure_brightness(self, image: np.ndarray) -> float: | ||
| """Returns mean brightness (0-255). 0 = black, 255 = white.""" | ||
| gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | ||
| return float(np.mean(gray)) | ||
|
|
||
| def _gamma_correction(self, image: np.ndarray, gamma: float) -> np.ndarray: | ||
| """ | ||
| Gamma < 1 = darken, Gamma > 1 = brighten. | ||
| Builds a lookup table for fast per-pixel correction. | ||
| """ | ||
| inv_gamma = 1.0 / gamma | ||
| table = np.array([ | ||
| ((i / 255.0) ** inv_gamma) * 255 | ||
| for i in range(256) | ||
| ], dtype=np.uint8) | ||
| return cv2.LUT(image, table) | ||
|
|
||
| def verify_image(self, image: np.ndarray) -> bool: | ||
| brightness = self._measure_brightness(image) | ||
| print( | ||
| f"[BrightnessFilter] Brightness: {brightness:.2f} (range: {self.MIN_BRIGHTNESS}-{self.MAX_BRIGHTNESS})") | ||
| return self.MIN_BRIGHTNESS <= brightness <= self.MAX_BRIGHTNESS | ||
|
|
||
| def process_image(self, image: np.ndarray) -> np.ndarray: | ||
merakleee marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # Step 1 — test | ||
| if self.verify_image(image): | ||
| return image | ||
|
|
||
| brightness = self._measure_brightness(image) | ||
|
|
||
| # Step 2 — fix | ||
| gamma = 2.0 if brightness < self.MIN_BRIGHTNESS else 0.5 | ||
| fixed = self._gamma_correction(image, gamma) | ||
|
|
||
| # Step 3 — retest | ||
| if self.verify_image(fixed): | ||
| return fixed | ||
|
|
||
| # Step 4 — reject | ||
| raise AppException.bad_request( | ||
| f"Image brightness {brightness:.2f} is out of acceptable range " | ||
| f"({self.MIN_BRIGHTNESS}–{self.MAX_BRIGHTNESS}) and could not be corrected." | ||
| ) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.