android.graphics实现图像形态学操作

1:转为灰度图像

//图像灰度处理
    public static Bitmap bitmap2gray(Bitmap bmsrc){
        //得到图片的长和宽
        int width = bmsrc.getWidth();
        int height =bmsrc.getHeight();
        //创建目标灰度图像
        Bitmap bmpgray=null;
        bmpgray = Bitmap.createBitmap(width,height,Bitmap.Config.RGB_565);
        //创建画布
        Canvas c=new Canvas(bmpgray);
        Paint paint=new Paint();
        ColorMatrix cm=new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f=new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmsrc,0,0,paint);
        return bmpgray;
    }

2:图像二值处理

//图像二值处理
    //该函数实现对图像进行二值化处理
    public static Bitmap gray2binary(Bitmap graymap,int gray1){
        //得到图形的宽度和长度
        int width=graymap.getWidth();
        int height=graymap.getHeight();
        //创建二值化图像
        Bitmap binarymap=null;
        binarymap=graymap.copy(Bitmap.Config.ARGB_8888,true);
        //依次循环,对图像的像素进行处理
        for(int i=0;i>16;
                int green=(col&0x0000ff00)>>8;
                int blue=(col&0x000000ff);
                //用公式x=0.3×r+0.59×g+0.11×b计算出x代替原来的rgb
                int gray=(int)((float)red*0.3+(float)green*0.59+(float)blue*0.11);
                //对图像进行二值化处理 95:临界值
                int standrad=(gray1==0)?90 : gray1;
                if(gray<=standrad){
                    gray=0;
                }else{
                    gray=255;
                }
                //新的argb
                int newcolor=alpha|(gray);
                binarymap.setPixel(i,j,newcolor);
            }
        }
        return binarymap;
    }

3:膨胀,腐蚀实现

膨胀,腐蚀的原理:

通过卷积核,这里用的3*3的

0 1 0
1 1 1
0 1 0
1 0 1
0 0 0
1 0 1

这个是膨胀的和腐蚀的卷积核

255 0 255 0 255
0 255 255 255 255
0 0 0 255 255
255 255 255 255 255
0 0 0 0 255
255 255 0 0 0

经过二值化处理过后的图像应该是这样的,膨胀原理就是通过卷积核从起始坐标不断移动,遍历整个图像,膨胀图像只关心跟1重合的像素的值,如果原图重合区域有一个像素点为255(白色),那就把中心点重合的颜色调整为白色。、

腐蚀的话就是如果卷积核0值跟原图位置重合的数值有0的话就把中心点颜色设置为0(黑色)

 //膨胀/腐蚀算法实现 flag标志:0:膨胀 1:腐蚀
    public static Bitmap gray2Feature(Bitmap graymap,int flag){
        //得到图形的宽度和长度
        //卷积核
        //int[][] center = {{0,1,0},{1,1,1},{0,1,0}};
        int width=graymap.getWidth();
        int height=graymap.getHeight();
        //创建二值化图像
        Bitmap binarymap=graymap.copy(Bitmap.Config.ARGB_8888,true);
        Bitmap binarymap1=graymap.copy(Bitmap.Config.ARGB_8888,true);
        //依次循环,对图像的像素进行处理
        for(int i=0;i

你可能感兴趣的:(android,计算机视觉,图像处理)