Skip to content

Commit 9491acf

Browse files
authored
example: annotated related arg for extract_faces() (#785)
* example: annotated related arg for `extract_faces()` * example: update rect field names * migrate: update field name accordingly * chore: bump `cocoindex` dependency version
1 parent dccf195 commit 9491acf

File tree

2 files changed

+17
-12
lines changed

2 files changed

+17
-12
lines changed

examples/face_recognition/main.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@
1111

1212
@dataclasses.dataclass
1313
class ImageRect:
14-
top: int
15-
left: int
16-
bottom: int
17-
right: int
14+
min_x: int
15+
min_y: int
16+
max_x: int
17+
max_y: int
1818

1919

2020
@dataclasses.dataclass
@@ -28,7 +28,12 @@ class FaceBase:
2828
MAX_IMAGE_WIDTH = 1280
2929

3030

31-
@cocoindex.op.function(cache=True, behavior_version=1, gpu=True)
31+
@cocoindex.op.function(
32+
cache=True,
33+
behavior_version=1,
34+
gpu=True,
35+
arg_relationship=(cocoindex.op.ArgRelationship.RECTS_BASE_IMAGE, "content"),
36+
)
3237
def extract_faces(content: bytes) -> list[FaceBase]:
3338
"""Extract the first pages of a PDF."""
3439
orig_img = Image.open(io.BytesIO(content)).convert("RGB")
@@ -48,17 +53,17 @@ def extract_faces(content: bytes) -> list[FaceBase]:
4853
locs = face_recognition.face_locations(np.array(img), model="cnn")
4954

5055
faces: list[FaceBase] = []
51-
for top, right, bottom, left in locs:
56+
for min_y, max_x, max_y, min_x in locs:
5257
rect = ImageRect(
53-
left=int(left * ratio),
54-
top=int(top * ratio),
55-
right=int(right * ratio),
56-
bottom=int(bottom * ratio),
58+
min_x=int(min_x * ratio),
59+
min_y=int(min_y * ratio),
60+
max_x=int(max_x * ratio),
61+
max_y=int(max_y * ratio),
5762
)
5863

5964
# Crop the face and save it as a PNG.
6065
buf = io.BytesIO()
61-
orig_img.crop((rect.left, rect.top, rect.right, rect.bottom)).save(
66+
orig_img.crop((rect.min_x, rect.min_y, rect.max_x, rect.max_y)).save(
6267
buf, format="PNG"
6368
)
6469
face = buf.getvalue()

examples/face_recognition/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ version = "0.1.0"
44
description = "Build index for papers with both metadata and content embeddings"
55
requires-python = ">=3.11"
66
dependencies = [
7-
"cocoindex>=0.1.67",
7+
"cocoindex>=0.1.71",
88
"face-recognition>=1.3.0",
99
"pillow>=10.0.0",
1010
"numpy>=1.26.0",

0 commit comments

Comments
 (0)