Skip to content

Commit

Permalink
Update face alignment example to use Image.crop
Browse files Browse the repository at this point in the history
  • Loading branch information
arrufat committed Apr 19, 2024
1 parent 0776105 commit 98517ad
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 22 deletions.
4 changes: 2 additions & 2 deletions examples/build.zig.zon
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

.dependencies = .{
.zignal = .{
.url = "https://github.com/bfactory-ai/zignal/archive/7cd7e70415dec093eb1b096218d2286d9f829360.tar.gz",
.hash = "1220140e8744befa3cfe2c844d73e62376425eb6dd54140787218b4a480001219433",
.url = "https://github.com/bfactory-ai/zignal/archive/0776105d88325fbeb42f11e6a99371ace421e20b.tar.gz",
.hash = "12204c77931cfeaa780324506f738baf97c2a95f8c4fccf30a3e1fa8fdbe0f87bb27",
},
},

Expand Down
26 changes: 6 additions & 20 deletions examples/src/face_alignment.zig
Original file line number Diff line number Diff line change
Expand Up @@ -43,38 +43,24 @@ pub fn extractAlignedFace(
assert(from_points.len == to_points.len);
assert(out.cols == out.rows);
assert(out.cols > 0);
const size: f32 = @floatFromInt(out.cols);
const side: f32 = @floatFromInt(out.cols);
for (&from_points) |*p| {
p.x = (padding + p.x) / (2 * padding + 1) * size;
p.y = (padding + p.y) / (2 * padding + 1) * size;
p.x = (padding + p.x) / (2 * padding + 1) * side;
p.y = (padding + p.y) / (2 * padding + 1) * side;
}
const transform = SimilarityTransform.find(&from_points, &to_points);
var p = transform.project(.{ .x = 1, .y = 0 });
p.x -= transform.bias.at(0, 0);
p.y -= transform.bias.at(1, 0);
const angle = std.math.atan2(p.y, p.x);
const scale = @sqrt(p.x * p.x + p.y * p.y);
const center = transform.project(.{ .x = size / 2, .y = size / 2 });
const center = transform.project(.{ .x = side / 2, .y = side / 2 });
var rotated = try image.rotateFrom(allocator, center.x, center.y, angle);
defer rotated.deinit(allocator);

const rect = Rectangle.initCenter(center.x, center.y, size * scale, size * scale);
const crop_top: isize = @intFromFloat(@round(rect.t));
const crop_left: isize = @intFromFloat(@round(rect.l));
const crop_rows: usize = @intFromFloat(@round(rect.height()));
const crop_cols: usize = @intFromFloat(@round(rect.width()));
var crop = try Image(T).initAlloc(allocator, crop_rows, crop_cols);
const rect = Rectangle.initCenter(center.x, center.y, side * scale, side * scale);
var crop = try rotated.crop(allocator, rect);
defer crop.deinit(allocator);
for (0..crop_rows) |r| {
const ir: isize = @intCast(r);
for (0..crop_cols) |c| {
const ic: isize = @intCast(c);
crop.data[r * crop_cols + c] = if (rotated.at(@intCast(ir + crop_top), @intCast(ic + crop_left))) |val|
val.*
else
.{ .r = 0, .g = 0, .b = 0, .a = 0 };
}
}
crop.resize(out);
}

Expand Down

0 comments on commit 98517ad

Please sign in to comment.