基本原理:java
膨脹是圖像形態學的兩個基本操做之一,另一個是腐蝕操做。最典型的應用是在二值圖像ide
中使用這兩個基本操做,是不少識別技術中重要的中間處理步驟。在灰度圖像中根據閾值同this
樣能夠完成膨脹與腐蝕操做。對一幅二值圖像f(x,y)完成膨脹操做,與對圖像的卷積操做類url
似,要有個操做數矩陣,最多見的爲3X3的矩陣,與卷積操做不一樣的,是若是矩陣中的像素spa
點有任意一個點的值是前景色,則設置中心像素點爲前景色,不然不變。.net
程序效果:(上爲源圖,下爲膨脹之後效果)orm

程序原理:blog
首先把一幅彩色圖像轉換爲灰度圖像,轉換方法參見這裏ip
http://blog.csdn.net/jia20003/article/details/7392325ci
然根據像素平均值做爲閾值,轉換爲二值圖像,轉換方法參見這裏
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);
- 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.顯示相減之後的圖像,即獲得邊緣。