Адаптивный порог
Я пытаюсь реализовать следующий метод в Matlab: порог минимальной ошибки - Дж. Киттлер и Дж. Иллингворт
Вы можете взглянуть на PDF:
- http://liama.ia.ac.cn/wiki/_media/projects:pal:kittler1986.pdf?id=projects%3Apal%3Areadinggroup&cache=cache
- http://docs.google.com/viewer?a=v&q=cache:XBuTPelQ3pMJ:www.ee.umanitoba.ca/~thomas/cp/Minimum%2520Error%2520Thresholding.pdf+J.+Kittler+and+J.+Illingworth,+%E2%80%98%E2%80%98Minimum+error+thresholding,%E2%80%99%E2%80%99&hl=en&pid=bl&srcid=ADGEESiXO4bpSsGomAjurUJLSzpmCyuCVxd-WnqMsKppKIMkvETt2xW6SowFxslmntlybz-z_YAea0oaCzVfBdkqiJczfVt3ll8hTDDkMg80xaO6vwl5yCLZg5b-FoWWl0gqfaYr81Bh&sig=AHIEtbQUj2nniDzc0Yj1dbBJ1mty5foZog (На конец).
Мой код:
function [ Level ] = MET( IMG )
%Maximum Error Thresholding By Kittler
% Finding the Min of a cost function J in any possible thresholding. The
% function output is the Optimal Thresholding.
for t = 0:255 % Assuming 8 bit image
I1 = IMG;
I1 = I1(I1 <= t);
q1 = sum(hist(I1, 256));
I2 = IMG;
I2 = I2(I2 > t);
q2 = sum(hist(I2, 256));
% J is proportional to the Overlapping Area of the 2 assumed Gaussians
J(t + 1) = 1 + 2 * (q1 * log(std(I1, 1)) + q2 * log(std(I2, 1)))...
-2 * (q1 * log(q1) + q2 * log(q2));
end
[~, Level] = min(J);
%Level = (IMG <= Level);
end
Я попробовал это на следующем изображении: http://i45.tinypic.com/xmvr52.jpg
Оригинальное изображение размера.
Цель состоит в том, чтобы извлечь двоичное изображение букв (букв иврита). Я применил код к подблокам изображения (40 х 40). Тем не менее, я получил результаты, которые уступают методу K-Means Clusters.
Я что-то пропустил? У кого-нибудь есть идея получше?
Благодарю.
PS Кто-нибудь добавил бы "Adaptive-Thresholding" к предметным тегам (не могу, так как я новичок).
2 ответа
Я думаю, что ваш код не совсем правильный. Вы используете абсолютную гистограмму изображения вместо относительной гистограммы, которая используется в статье. Кроме того, ваш код довольно неэффективен, так как он вычисляет две гистограммы для каждого возможного порога. Я сам реализовал алгоритм. Может быть, кто-то может использовать это:
function [ optimalThreshold, J ] = kittlerMinimimErrorThresholding( img )
%KITTLERMINIMIMERRORTHRESHOLDING Compute an optimal image threshold.
% Computes the Minimum Error Threshold as described in
%
% 'J. Kittler and J. Illingworth, "Minimum Error Thresholding," Pattern
% Recognition 19, 41-47 (1986)'.
%
% The image 'img' is expected to have integer values from 0 to 255.
% 'optimalThreshold' holds the found threshold. 'J' holds the values of
% the criterion function.
%Initialize the criterion function
J = Inf * ones(255, 1);
%Compute the relative histogram
histogram = double(histc(img(:), 0:255)) / size(img(:), 1);
%Walk through every possible threshold. However, T is interpreted
%differently than in the paper. It is interpreted as the lower boundary of
%the second class of pixels rather than the upper boundary of the first
%class. That is, an intensity of value T is treated as being in the same
%class as higher intensities rather than lower intensities.
for T = 1:255
%Split the hostogram at the threshold T.
histogram1 = histogram(1:T);
histogram2 = histogram((T+1):end);
%Compute the number of pixels in the two classes.
P1 = sum(histogram1);
P2 = sum(histogram2);
%Only continue if both classes contain at least one pixel.
if (P1 > 0) && (P2 > 0)
%Compute the standard deviations of the classes.
mean1 = sum(histogram1 .* (1:T)') / P1;
mean2 = sum(histogram2 .* (1:(256-T))') / P2;
sigma1 = sqrt(sum(histogram1 .* (((1:T)' - mean1) .^2) ) / P1);
sigma2 = sqrt(sum(histogram2 .* (((1:(256-T))' - mean2) .^2) ) / P2);
%Only compute the criterion function if both classes contain at
%least two intensity values.
if (sigma1 > 0) && (sigma2 > 0)
%Compute the criterion function.
J(T) = 1 + 2 * (P1 * log(sigma1) + P2 * log(sigma2)) ...
- 2 * (P1 * log(P1) + P2 * log(P2));
end
end
end
%Find the minimum of J.
[~, optimalThreshold] = min(J);
optimalThreshold = optimalThreshold - 0.5;
Thresholding - довольно сложный бизнес. В течение многих лет, когда я получал пороговые изображения, я не нашел ни одной методики, которая всегда работает хорошо, и я пришел к недоверию к заявлениям о всеобщей превосходной работе в журналах CS.
Метод порогового значения максимальной ошибки работает только на хорошо бимодальной гистограмме (но он хорошо работает и на тех). Ваше изображение выглядит как сигнал и фон, возможно, недостаточно четко отделены для работы этого метода пороговой обработки.
Если вы хотите убедиться, что код работает нормально, вы можете создать тестовую программу, подобную этой, и проверить, получаете ли вы хорошую начальную сегментацию, а также на каком уровне "бимодальности" код разбивается.