图像的二值化的基本原理
图像的二值化处理就是将图像上的点的灰度置为0或255,也就是将整个图像呈现出明显的黑白效果。即将256个亮度等级的灰度图像通过适当的阈值选取而获得仍然可以反映图像整体和局部特征的二值化图像。在数字图像处理中,二值图像占有非常重要的地位,特别是在实用的图像处理中,以二值图像处理实现而构成的系统是很多的,要进行二值图像的处理与分析,首先要把灰度图像二值化,得到二值化图像,这样子有利于在对图像做进一步处理时,图像的集合性质只与像素值为0或255的点的位置有关,不再涉及像素的多级值,使处理变得简单,而且数据的处理和压缩量小。为了得到理想的二值图像,一般采用封闭、连通的边界定义不交叠的区域。所有灰度大于或等于阈值的像素被判定为属于特定物体,其灰度值为255表示,否则这些像素点被排除在物体区域以外,灰度值为0,表示背景或者例外的物体区域。如果某特定物体在内部有均匀一致的灰度值,并且其处在一个具有其他等级灰度值的均匀背景下,使用阈值法就可以得到比较的分割效果。如果物体同背景的差别表现不在灰度值上(比如纹理不同),可以将这个差别特征转换为灰度的差别,然后利用阈值选取技术来分割该图像。动态调节阈值实现图像的二值化可动态观察其分割图像的具体结果。
void GrayTrans::BinaryImage(int threshold){
if (m_nBitCount == 8){
if(m_pImgDataOut != NULL){
delete []m_pImgDataOut ;
m_pImgDataOut = NULL ;
}
if (m_lpColorTableOut != NULL){
delete []m_lpColorTableOut ;
m_lpColorTableOut = NULL ;
}
m_nBitCountOut = m_nBitCount ;
m_nColorTableLengthOut = ComputeColorTabalLength(m_nBitCountOut) ;
m_lpColorTableOut = new RGBQUAD[m_nColorTableLengthOut] ;
memcpy(m_lpColorTableOut , m_lpColorTable , sizeof(RGBQUAD) * m_nColorTableLengthOut) ;
m_imgHeightOut = m_imgHeight ;
m_imgWidthOut = m_imgWidth ;
int lineByte = (m_imgWidthOut * m_nBitCountOut / 8 + 3) / 4 * 4 ;
m_pImgDataOut = new unsigned char[lineByte * m_imgHeightOut] ;
for(int i = 0 ; i < m_imgHeightOut ; i++){
for(int j = 0 ; j < m_imgWidthOut ; j++){
if(* (m_pImgData + i * lineByte + j) < threshold)
*(m_pImgDataOut + i * lineByte + j) = 0 ;
else *(m_pImgDataOut + i * lineByte + j) = 255 ;
}
}
}
else{
if(m_pImgDataOut != NULL){
delete []m_pImgDataOut ;
m_pImgDataOut = NULL ;
}
if(m_lpColorTableOut != NULL){
delete []m_lpColorTableOut ;
m_lpColorTableOut = NULL ;
}
m_nBitCountOut = 8 ;
m_nColorTableLengthOut = ComputeColorTabalLength(m_nBitCountOut) ;
if(m_nColorTableLengthOut != 0){
m_lpColorTableOut = new RGBQUAD[m_nColorTableLengthOut] ;
for(int i = 0 ; i < m_nColorTableLengthOut ; i++){
m_lpColorTableOut[i].rgbBlue = i ;
m_lpColorTableOut[i].rgbGreen = i ;
m_lpColorTableOut[i].rgbRed = i ;
m_lpColorTableOut[i].rgbReserved = 0 ;
}
}
m_imgWidthOut = m_imgWidth ;
m_imgHeightOut = m_imgHeight ;
int lineByteIn = (m_imgWidth * 3 + 3) / 4 * 4 ;
int lineByteOut = (m_imgWidth * m_nBitCountOut/8 + 3)/4*4 ;
m_pImgDataOut = new unsigned char[m_imgHeightOut * lineByteOut] ;
for(int i = 0 ; i < m_imgHeightOut ; i++){
for(int j = 0 ; j < m_imgWidthOut ; j++){
*(m_pImgDataOut + i * lineByteOut + j) =
0.11 * *(m_pImgData + i*lineByteIn + 3 * j + 0)
+ 0.59 * *(m_pImgData + i*lineByteIn + 3 * j + 1)
+ 0.30 * *(m_pImgData + i*lineByteIn + 3 * j + 2) + 0.5 ;
}
}
for(int i = 0 ; i < m_imgHeightOut ; i++){
for(int j = 0 ; j < m_imgWidthOut ; j++){
if(* (m_pImgDataOut + i * lineByteOut + j) < threshold)
*(m_pImgDataOut + i * lineByteOut + j) = 0 ;
else *(m_pImgDataOut + i * lineByteOut + j) = 255 ;
}
}
}
}