1 理論
基本概念
灰度質心法(Gray-scale Centroid Method)是一種基于圖像灰度分布的加權平均位置計算方法。它將圖像的灰度值作為質量權重,計算圖像的"質量中心"。
數學原理
1. 離散圖像的計算公式
對于離散的數字圖像,灰度質心的計算公式為:

其中:
2. 連續情況下的推廣
對于連續圖像,公式可寫為:

其中 f(x,y)是圖像的灰度分布函數。
物理意義
類比物理學中的質心概念
2 matlab 實現灰度質心法
% 讀取圖像并轉換為灰度圖
I = imread('your_image.jpg');
if size(I, 3)==3
I = rgb2gray(I);
end
% 將圖像數據轉換為double類型
I = double(I);
% 獲取圖像尺寸
[rows, cols]= size(I);
% 創建坐標網格
[x, y]= meshgrid(1:cols, 1:rows);
% 計算總灰度值
total_intensity = sum(I(:));
% 計算灰度質心坐標
centroid_x = sum(sum(I .* x)) / total_intensity;
centroid_y = sum(sum(I .* y)) / total_intensity;
% 顯示結果
fprintf('灰度質心坐標: (%.2f, %.2f)\n', centroid_x, centroid_y);
% 可視化顯示
figure;
imshow(uint8(I));
hold on;
plot(centroid_x, centroid_y, 'r+', 'MarkerSize', 15, 'LineWidth', 2);
title('圖像灰度質心');
3 FPGA 實現灰度質心法求取質心
`timescale 1ns/1psmodule totalmass( input pixelclk, input reset_n, input [11:0] hcount, input [11:0] vcount, input [7:0] i_gray, input i_hsync, input i_vsync, input i_de, output reg [31:0] centerx, output reg [31:0] centery, output reg out_flag );parameter IDLE =2'd0, TOTAL=2'd1, CALC =2'd2, OUT =2'd3;reg [31:0] totalgray;reg [31:0] totalcenterx;reg [31:0] totalcentery;reg [1:0] state;always @(posedge pixelclk or negedge reset_n) begin if(!reset_n) begin totalgray <= 32'd0; centerx<= 32'd0; centery<= 32'd0; out_flag <= 1'b0; totalcenterx<= 32'd0; totalcentery<= 32'd0; state<=IDLE; end else begin case(state) IDLE:begin if(i_vsync==1'b1) begin state <= TOTAL; end else begin totalgray <= 32'd0; totalcenterx<= 32'd0; totalcentery<= 32'd0; end end TOTAL:begin if(i_vsync==1'b0) begin state <= CALC; end else if(i_de==1'b1) begin totalgray <= totalgray + i_gray; totalcenterx <= totalcenterx + hcount*i_gray; totalcentery <= totalcentery + vcount*i_gray; end end CALC:begin if(totalgray!=0) begin centerx <= totalcenterx/totalgray; centery <= totalcentery/totalgray; out_flag <= 1'b1; state <= OUT; end else begin out_flag <= 1'b0; state <= IDLE; end end OUT:begin out_flag <= 1'b0; state <= IDLE; end endcase end endendmodule
