图像处理之二值膨胀及应用
基本原理:
膨胀是图像形态学的两个基本操作之一,另外一个是腐蚀操作。最典型的应用是在二值图像
中使用这两个基本操作,是很多识别技术中重要的中间处理步骤。在灰度图像中根据阈值同
样可以完成膨胀与腐蚀操作。对一幅二值图像f(x,y)完成膨胀操作,与对图像的卷积操作类
似,要有个操作数矩阵,最常见的为3X3的矩阵,与卷积操作不同的,是如果矩阵中的像素
点有任意一个点的值是前景色,则设置中心像素点为前景色,否则不变。
关于卷积参考这里:http://blog.csdn.net/jia20003/article/details/7038938
程序效果:(上为源图,下为膨胀以后效果)
程序原理:
首先把一幅彩色图像转换为灰度图像,转换方法参见这里
http://blog.csdn.net/jia20003/article/details/7392325
然根据像素平均值作为阈值,转换为二值图像,转换方法参见这里
http://blog.csdn.net/jia20003/article/details/7392325
最后在二值图像上使用膨胀操作,输出处理以后图像
源代码:
package com.gloomyfish.morphology; import java.awt.Color; import java.awt.image.BufferedImage; public class DilateFilter extends BinaryFilter { public DilateFilter() { forgeColor = Color.WHITE; } private Color forgeColor; public Color getForgeColor() { return forgeColor; } public void setForgeColor(Color forgeColor) { this.forgeColor = forgeColor; } @Override public BufferedImage filter(BufferedImage src, BufferedImage dest) { int width = src.getWidth(); int height = src.getHeight(); if ( dest == null ) dest = createCompatibleDestImage( src, null ); int[] inPixels = new int[width*height]; int[] outPixels = new int[width*height]; src = super.filter(src, null); // we need to create new one getRGB( src, 0, 0, width, height, inPixels ); int index = 0, index1 = 0, newRow = 0, newCol = 0; int ta1 = 0, tr1 = 0, tg1 = 0, tb1 = 0; for(int row=0; row<height; row++) { int ta = 0, tr = 0, tg = 0, tb = 0; for(int col=0; col<width; col++) { index = row * width + col; ta = (inPixels[index] >> 24) & 0xff; tr = (inPixels[index] >> 16) & 0xff; tg = (inPixels[index] >> 8) & 0xff; tb = inPixels[index] & 0xff; boolean dilation = false; for(int offsetY=-1; offsetY<=1; offsetY++) { for(int offsetX=-1; offsetX<=1; offsetX++) { if(offsetY==0 && offsetX==0) { continue; } newRow = row + offsetY; newCol = col + offsetX; if(newRow <0 || newRow >=height) { newRow = 0; } if(newCol < 0 || newCol >=width) { newCol = 0; } index1 = newRow * width + newCol; ta1 = (inPixels[index1] >> 24) & 0xff; tr1 = (inPixels[index1] >> 16) & 0xff; tg1= (inPixels[index1] >> 8) & 0xff; tb1 = inPixels[index1] & 0xff; if(tr1 == forgeColor.getRed() && tg1 == tb1) { dilation = true; break; } } if(dilation){ break; } } if(dilation) { tr = tg = tb = forgeColor.getRed(); } else { tr = tg = tb = 255 - forgeColor.getRed(); } outPixels[index] = (ta << 24) | (tr << 16) | (tg << 8) | tb; } } setRGB( dest, 0, 0, width, height, outPixels ); return dest; } }
其实,膨胀还可以被用来进行对二值图像完成边缘提取,其基本做法如下:
1. 对一副黑白的图像完成膨胀操作
2.将膨胀以后的图像与原来的图像在每个像素位上相减
3.显示相减以后的图像,即得到边缘。
sorry,没有源代码!