Вернуться к разделу "Реализация проекта BookScanLib".
Бинаризация Otsu Thresholding (Оцу-бинаризация) применяется для преобразования серой (8-битной) растровой картинки в чёрно-белую (1-битная).
Алгоритм Otsu Thresholding анализирует обрабатываемую картинку и автоматически вычисляет порог бинаризации - единый для всей картинки (т.е это глобальная бинаризация). Найденный порог подаётся на вход обыкновенной пороговой бинаризации (например, в библиотеке FreeImage для этого есть функция FreeImage_Threshold).
Я написал простейшую консольную программу для демонстрации работы Otsu Thresholding. На входе она принимает следующие параметры:
otsu_thres <input_file>
На выходе программа выдаёт этот же файл, обработанный этим алгоритмом.
Программа работает только с серыми изображениями.
Всё необходимое для тестирования этой программы (компиляционный проект, готовый экзешник, файл-пример и bat-файлы для тестирования программы) я оформил в небольшой пакет:
Скачать пакет otsu_thres (39 КБ)
(Для работы программы требуется 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
// This algorithm was taken from the C++ Augmented Reality Toolkit sourcecodes
// http://www.dandiggins.co.uk/arlib-1.html
// and adopted for the FreeImage library
//
// Copyright (C) 2007-2008:
// monday2000 monday2000@yandex.ru
#include "FreeImage.h"
#include <stdio.h>
#define MAXVAL 256
// Otsu thresholding.
//
// The code implements Otsu thresholding, which is described in
// N. Otsu, "A threshold selection method from gray-level pdfs", IEEE Trans. Systems,
// Man and Cybernetics 9(1), pp. 62-66, 1979.
// This implementation instead of minimizing the weighted within-class variance
// does maximization of between-class variance, what gives the same result.
// The approach is described in this presentation:
// http://sampl.ece.ohio-state.edu/EE863/2004/ECE863-G-segclust2.ppt.
////////////////////////////////////////////////////////////////////////////////
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)
{
// 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 size = width * height;
int minlevel = 256;
int maxlevel = 0;
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 w = 0; // first order cumulative
double u = 0; // second order cumulative
double uT = 0; // total mean level
int threshold = 0; // optimal threshold value
double histNormalized[256]; // normalized histogram values
double work1, work2; // working variables
double work3 = 0.0;
for (int i=1; i<=MAXVAL; i++)
{
// Create normalised histogram values
histNormalized[i-1] = histogram[i-1]/(double)(width * height);
// Calculate total mean level
uT+=(i*histNormalized[i-1]);
}
// Find optimal threshold value
for (i=1; i<MAXVAL; i++)
{
w+=histNormalized[i-1];
u+=(i*histNormalized[i-1]);
work1 = (uT * w - u);
work2 = (work1 * work1) / ( w * (1.0f-w) );
if (work2>work3)
{
work3=work2;
threshold = i;
}
}
threshold -= 1; // empirical offset
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 != 2) {
printf("Usage : otsu_thres <input_file>\n");
return 0;
}
FIBITMAP *dib = GenericLoader(argv[1], 0);
if (dib)
{
// bitmap is successfully loaded!
if (FreeImage_GetImageType(dib) == FIT_BITMAP)
{
if (FreeImage_GetBPP(dib) == 8)
{
FIBITMAP* dst_dib = ProcessFilter(dib);
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;
|
Реализация данного алгоритма позаимствована из программной графической библиотеки ARLib. Эта реализация даёт точно такой же результат, как и "контрольная" (т.е. заведомо правильная) реализация Otsu Thresholding из проекта OCRopus (но если там она идёт под Apache License - то данная - под GPL).
Строим гистограмму. Строим вероятностную гистограмму. Находим общее среднее.
Проходя в цикле по всей длине гистограмм, для каждого цвета находим его вероятность и среднее, а также вероятность и среднее смежного ему (противоположно-вероятного) пикселя. Находим взвешенный по среднему квадрат разницы вероятностей между текущим и смежным ему пикселями - и если эта разница больше её же с предыдущего шага цикла, то запоминаем текущий номер шага как найденный порог (и так продолжаем цикл до конца).
Найденное значение порога подаём на вход обычной пороговой бинаризации.