簡體   English   中英

如何計算圖像的中心矩?

[英]How do I calculate the central moment in an image?

我需要找到圖像的中心時刻。 中心矩由下式給出:

其中xy是空間圖像坐標, 是平均值xy (或質心)坐標, pq是整數, f(x,y)是圖像。

另外,我想了解如何處理f(x,y)因為它將保存所有像素值。

使用bsxfun

sz = size( img ); %// assuming image is gray scale - 2D array
x = ( 1:sz(2) );
y = ( 1:sz(1) ).'; %'
x = x - mean(x);
y = y - mean(y);
Mpq = sum( reshape( bsxfun( @times, bsxfun( @times, img, x.^p ), y.^q ), [], 1 ) ); %// computing the p-q moment

基准測試:

disp('Solution of rayryeng')
tic
[rows, cols] = size(img);
[X, Y] = meshgrid(1:cols, 1:rows);
X = X(:);
Y = Y(:);
Mpq = sum((X - mean(X)).^p .* (Y - mean(Y)).^q .* img(:));
toc

disp('rayryeng with dot product');
tic
[rows, cols] = size(img);
[X, Y] = meshgrid(1:cols, 1:rows);
X = X(:);
Y = Y(:);
Mpq = ((X.' - mean(X)).^p )* ((Y - mean(Y)).^q .* img(:));
toc

disp('this solution - using bsxfun');
tic
sz = size( img ); %// assuming image is gray scale - 2D array
x = ( 1:sz(2) );
y = ( 1:sz(1) ).'; %'
x = x - mean(x);
y = y - mean(y);
Mpq = sum( reshape( bsxfun( @times, bsxfun( @times, img, x.^p ), y.^q ), [], 1 ) );
toc

結果與

Solution of rayryeng
Elapsed time is 0.009426 seconds.
rayryeng with dot product
Elapsed time is 0.008374 seconds.
this solution - using bsxfun
Elapsed time is 0.001404 seconds.

如您所見, bsxfun比基於meshgrid的解決方案要快得多。 而且,使用點積代替帶sum的elemwise積更快。

f(x,y)只是您在每個列位置y和每個行位置x處的圖像強度。 如果要計算圖像的pq矩,則可以按照Shai的建議執行 ,這可能會更快。 但是,如果您想要不使用更具可讀性的東西,則可以簡單地假設您的圖像是灰度圖像並存儲在im

[rows, cols] = size(im);
im = double(im); %// For precision
[X, Y] = meshgrid(1:cols, 1:rows);
X = X(:);
Y = Y(:);
Mpq = sum((X - mean(X)).^p .* (Y - mean(Y)).^q .* im(:));

首先,我們將圖像轉換為double以確保獲得最佳精度。 您的圖片可能是uint8類型的,計算出的任何超過255的值都將被裁剪。 您可能會獲得超出此范圍的值,因此建議強制轉換為double 然后,我們使用meshgrid生成與圖像大小相同的空間坐標網格,然后將坐標展開為單個矢量。 這將使計算力矩變得更加容易。 最后一行代碼最終根據方程式計算了我們的力矩。 我們還需要以相同的方式展開圖像,以便元素正確對齊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM