// Sobel edge detector on a 3x3 window. // Gx = (right column) - (left column), weights 1 2 1 // Gy = (bottom row) - (top row), weights 1 2 1 // Magnitude approximated as |Gx| + |Gy|. For 8-bit pixels it is at most // 1530 (11 bits); mag is that value divided by 8, at most 191, so it fits // in 8 bits without saturating. // edge is 1 where |Gx| + |Gy| >= THRESH. Border windows (win_ok = 0) give 0. // Latency: 2 clocks. `timescale 1ns / 1ps module sobel #( parameter int THRESH = 400 ) ( input logic clk, input logic rst, input logic win_valid, input logic win_sof, input logic win_ok, input logic [2:0][2:0][7:0] win, output logic out_valid, output logic out_sof, output logic [7:0] mag, output logic edge_out ); function automatic logic signed [11:0] px(input logic [7:0] p); px = 12'(p); // zero-extend to a positive signed value endfunction logic signed [11:0] gx, gy; logic ok1, v1, sof1; // Stage 1: the two gradients. always_ff @(posedge clk) begin gx <= (px(win[0][2]) + 2 * px(win[1][2]) + px(win[2][2])) - (px(win[0][0]) + 2 * px(win[1][0]) + px(win[2][0])); gy <= (px(win[2][0]) + 2 * px(win[2][1]) + px(win[2][2])) - (px(win[0][0]) + 2 * px(win[0][1]) + px(win[0][2])); ok1 <= win_ok; sof1 <= win_sof; if (rst) v1 <= 1'b0; else v1 <= win_valid; end // Stage 2: |Gx| + |Gy|, scaling and threshold. logic [11:0] abs_gx, abs_gy, sum; assign abs_gx = gx[11] ? 12'(-gx) : 12'(gx); assign abs_gy = gy[11] ? 12'(-gy) : 12'(gy); assign sum = abs_gx + abs_gy; always_ff @(posedge clk) begin mag <= ok1 ? sum[10:3] : 8'd0; edge_out <= ok1 && (sum >= 12'(THRESH)); out_sof <= sof1; if (rst) out_valid <= 1'b0; else out_valid <= v1; end endmodule