Вернуться к разделу "Реализация проекта BookScanLib".
Бинаризация Tsai Moment Preserving Thresholding из проекта gamera применяется для преобразования серой (8-битной) растровой картинки в чёрно-белую (1-битная).
Алгоритм Tsai Moment Preserving Thresholding анализирует обрабатываемую картинку и автоматически вычисляет порог бинаризации - единый для всей картинки (т.е это глобальная бинаризация). Найденный порог подаётся на вход обыкновенной пороговой бинаризации (например, в библиотеке FreeImage для этого есть функция FreeImage_Threshold).
Я написал простейшую консольную программу для демонстрации работы Tsai Moment Preserving Thresholding. На входе она принимает следующие параметры:
tsai_thres <input_file> <shift (int)>
shift - задаваемый пользователем сдвиг найденного значения порога. (я установил -92).
На выходе программа выдаёт этот же файл, обработанный этим алгоритмом.
Программа работает только с серыми изображениями.
Всё необходимое для тестирования этой программы (компиляционный проект, готовый экзешник, файл-пример и bat-файлы для тестирования программы) я оформил в небольшой пакет:
Скачать пакет tsai_thres (40 КБ)
(Для работы программы требуется FreeImage dll-библиотека из пакета FreeImage DLL v3.9.2 - см. статью 1. Знакомство с FreeImage).
Рассмотрим исходные коды этой программы:
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// http://www.gnu.org/copyleft/gpl.html
/*
Finds a threshold point using the Tsai Moment Preserving threshold
algorithm. Reference:
W.H. Tsai: *Moment-Preserving Thresholding: A New Approach.*
Computer Vision Graphics and Image Processing (29), pp. 377-393
(1985)
*/
// This algorithm was taken from the gamera.sf.net sourcecodes
// and adopted for the FreeImage library
//
// Copyright (C) 2007-2008:
// monday2000 monday2000@yandex.ru
#include "FreeImage.h"
#include "Utilities.h"
////////////////////////////////////////////////////////////////////////////////
inline void SetPixel(BYTE *bits, unsigned x, BYTE* value)
{ // this function is simplified from FreeImage_SetPixelIndex
*value ? bits[x >> 3] |= (0x80 >> (x & 0x7)) : bits[x >> 3] &= (0xFF7F >> (x & 0x7));
}
////////////////////////////////////////////////////////////////////////////////
FIBITMAP* ProcessFilter(FIBITMAP* src_dib, int shift)
{
// get source image size
unsigned width = FreeImage_GetWidth(src_dib);
unsigned height = FreeImage_GetHeight(src_dib);
unsigned src_pitch = FreeImage_GetPitch(src_dib);
unsigned bpp = FreeImage_GetBPP(src_dib);
unsigned btpp = bpp/8;
FIBITMAP* dst_dib = FreeImage_Allocate(width, height, 1);
// Build a monochrome palette
RGBQUAD *pal = FreeImage_GetPalette(dst_dib);
pal[0].rgbRed = pal[0].rgbGreen = pal[0].rgbBlue = 0;
pal[1].rgbRed = pal[1].rgbGreen = pal[1].rgbBlue = 255;
unsigned dst_pitch = FreeImage_GetPitch(dst_dib);
BYTE* src_bits = (BYTE*)FreeImage_GetBits(src_dib); // The image raster
BYTE* dst_bits = (BYTE*)FreeImage_GetBits(dst_dib); // The image raster
BYTE* lines, *lined;
int i, threshold;
int histogram[256] = {0};
// build histogram first
// for each line
for ( unsigned y = 0; y < height; y++ )
{
lines = src_bits + y * src_pitch;
// for each pixel
for ( unsigned x = 0; x < width; x++)
{
histogram[lines[x]]++;
}
}
double criterion = 0.0;
double m1, m2, m3;
double cd, c0, c1, z0, z1, pd, p0, p1;
// calculate first 3 moments
m1 = m2 = m3 = 0.0;
for (i = 0; i < 256; i++)
{
m1 += i * (double)histogram[i];
m2 += i * i * (double)histogram[i];
m3 += i * i * i * (double)histogram[i];
}
// moment preserving bilevel thresholding calculations
cd = m2 - m1 * m1;
c0 = (-m2 * m2 + m1 * m3) / cd;
c1 = (-m3 + m2 * m1) / cd;
z0 = 0.5 * (-c1 - sqrt(c1 * c1 - 4.0 * c0));
z1 = 0.5 * (-c1 + sqrt(c1 * c1 - 4.0 * c0));
pd = z1 - z0;
p0 = (z1 - m1) / pd;
p1 = 1.0 - p0;
// find threshold
for (threshold = 0; threshold < 256; threshold++)
{
criterion += (double)histogram[threshold];
if (criterion > p1)
break;
}
if(threshold == 255)
threshold = 0;
threshold += shift;
printf("threshold=%d\n", threshold);
BYTE val;
// for each line
for ( y = 0; y < height; y++ )
{
lined = dst_bits + y * dst_pitch;
lines = src_bits + y * src_pitch;
// for all pixels
for ( unsigned x = 0; x < width; x++)
{
val = (BYTE) ( ( lines[x] >= threshold ) ? 255 : 0 );
SetPixel(lined, x, &val);
}
}
// Copying the DPI...
FreeImage_SetDotsPerMeterX(dst_dib, FreeImage_GetDotsPerMeterX(src_dib));
FreeImage_SetDotsPerMeterY(dst_dib, FreeImage_GetDotsPerMeterY(src_dib));
return dst_dib;
}
////////////////////////////////////////////////////////////////////////////////
/**
FreeImage error handler
@param fif Format / Plugin responsible for the error
@param message Error message
*/
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message) {
printf("\n*** ");
printf("%s Format\n", FreeImage_GetFormatFromFIF(fif));
printf(message);
printf(" ***\n");
}
////////////////////////////////////////////////////////////////////////////////
/** Generic image loader
@param lpszPathName Pointer to the full file name
@param flag Optional load flag constant
@return Returns the loaded dib if successful, returns NULL otherwise
*/
FIBITMAP* GenericLoader(const char* lpszPathName, int flag)
{
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
// check the file signature and deduce its format
// (the second argument is currently not used by FreeImage)
fif = FreeImage_GetFileType(lpszPathName, 0);
FIBITMAP* dib;
if(fif == FIF_UNKNOWN)
{
// no signature ?
// try to guess the file format from the file extension
fif = FreeImage_GetFIFFromFilename(lpszPathName);
}
// check that the plugin has reading capabilities ...
if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif))
{
// ok, let's load the file
dib = FreeImage_Load(fif, lpszPathName, flag);
// unless a bad file format, we are done !
if (!dib)
{
printf("%s%s%s\n","File \"", lpszPathName, "\" not found.");
return NULL;
}
}
return dib;
}
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[]) {
// call this ONLY when linking with FreeImage as a static library
#ifdef FREEIMAGE_LIB
FreeImage_Initialise();
#endif // FREEIMAGE_LIB
// initialize your own FreeImage error handler
FreeImage_SetOutputMessage(FreeImageErrorHandler);
if(argc != 3) {
printf("Usage : tsai_thres <input_file> <shift> (int)\n");
return 0;
}
FIBITMAP *dib = GenericLoader(argv[1], 0);
int shift = atoi(argv[2]);
if (dib)
{
// bitmap is successfully loaded!
if (FreeImage_GetImageType(dib) == FIT_BITMAP)
{
if (FreeImage_GetBPP(dib) == 8)
{
FIBITMAP* dst_dib = ProcessFilter(dib, shift);
if (dst_dib)
{
// save the filtered bitmap
const char *output_filename = "filtered.tif";
// first, check the output format from the file name or file extension
FREE_IMAGE_FORMAT out_fif = FreeImage_GetFIFFromFilename(output_filename);
if(out_fif != FIF_UNKNOWN)
{
// then save the file
FreeImage_Save(out_fif, dst_dib, output_filename, 0);
}
// free the loaded FIBITMAP
FreeImage_Unload(dst_dib);
}
}
else
printf("%s\n", "Unsupported color mode.");
}
else // non-FIT_BITMAP images are not supported.
printf("%s\n", "Unsupported color mode.");
FreeImage_Unload(dib);
}
// call this ONLY when linking with FreeImage as a static library
#ifdef FREEIMAGE_LIB
FreeImage_DeInitialise();
#endif // FREEIMAGE_LIB
return 0;
|
Строим гистограмму. По формулам высчитываем разнообразные коэффициенты - на основе гистограммы. Находим некий пороговый коэффициент.
Проходим в цикле по гистограмме и на каждом шаге считаем её кумулятивную сумму. Как только она превысит ранее найденный пороговый коэффициент - то текущий номер шага принимаем за найденное значение глобального порога.
Я добавил в этот алгоритм ещё и задаваемый пользователем сдвиг значения найденного порога. Значение сдвига подобрал, ориентируясь на Otsu Thresholding. Без этой меры алгоритм работает некорректно - т.е. найденный порог довольно "неправильный".
По этой причине данный алгоритм представляется мне довольно бесперспективным.