java 用遗传算法解决图像二值化问题 找阈值

本文介绍如何使用Java实现遗传算法来解决图像二值化的阈值选取问题,通过遗传算法寻找最佳阈值,达到良好的图像处理效果。

image类对图像处理



import java.awt.image.BufferedImage;
public class Image {
    public int h; //高
    public int w; //宽
    public int[] data; //像素
    public boolean gray; //是否为灰度图像

    public Image(BufferedImage img) {

        this.h = img.getHeight();
        this.w = img.getWidth();

        this.data = img.getRGB(0, 0, w, h, null, 0, w);
        this.gray = false;
        toGray(); //灰度化
    }

    public void toGray(){
        if(!gray){
            this.gray = true;
            for (int y = 0; y < h; y++) {
                for (int x = 0; x < w; x++) {
                    int c = this.data[x + y * w];
                    int R = (c >> 16) & 0xFF;
                    int G = (c >> 8) & 0xFF;
                    int B = (c >> 0) & 0xFF;
                    this.data[x + y * w] = (int)(0.3f*R + 0.59f*G + 0.11f*B); //to gray
                }
            }
        }
    }

    public int[] hist(){
        toGray();
        int[] hist = new int[256];
        int len = h*w;
        for(int i=0;i<len;i++)
            hist[data[i]]++;
        return hist;
    }
}


用遗传算法找阈值


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

public class OPRA {
    public Image image;
    public int gene_length = 8;//编码基因长度
    private String gene;

    public String getGene() {
        return gene;
    }

    public void setGene(String gene) {
        this.gene = gene;
    }
    public OPRA(){}

    //编码
    public String getcode(int n) {
        String str = Integer.toBinaryString(n);
        for (int i = str.length(); i <gene_length; i++) {
            str = "0" + str;
        }
        return str;
    }

    //解码
    public int decode(String gene) {
        int x = Integer.parseInt(gene, 2);
        return x;
    }

    //初始化种群
    public ArrayList<String> initgroup(int size) {
        ArrayList<String> list = new ArrayList();
        Random random = new Random();
        for (int i = 1; i <= size; i++) {
            int x = random.nextInt() % 256;
            x = x < 0 ? (-x) : x;
            list.add(getcode(x));
        }
        return list;
    }

    //计算适应度
    public double Otsu(int t) {
        double u0 = 0, u1 = 0, w0 = 0, w1 = 0, g = 0;
        double sum = 0, sum0 = 0, sum1 = 0;
        double temp0 = 0, temp1 = 0;
        int[] hist = image.hist();
        for (int i = 0; i < hist.length; i++) {
            if (i < t) {//背景
                sum0 += hist[i];
                temp0 += i * hist[i];
            } else {
                sum1 += hist[i];
                temp1 += i * hist[i];
            }
            sum += hist[i];
        }
        w0 = sum0 / sum;//前景占总数
        w1 = 1 - w0;
        u0 = temp0 / sum0;//平均灰度值
        u1 = temp1 / sum1;
        g = w0 * w1 * Math.abs(u0 - u1) * Math.abs(u0 - u1);
        return g;
    }

    //得到适应度函数最大的基因
    public String best(ArrayList<String> group) {
        String bestOne = group.get(0);
        for(String c : group) {
            if(Otsu(decode(c)) > Otsu(decode(bestOne)))
                bestOne = c;
        }
        return bestOne;
    }

    //选择
    public ArrayList<String> select(ArrayList<String> fathergroup, int songroupsize) {
        ArrayList<String> songroup = new ArrayList<String>();
        ArrayList<String> fathergroup1 =new ArrayList<>();
        for (String test : fathergroup) {
            fathergroup1.add(test);
        }
        for(int i=0;i<songroupsize;i++){
            String opra=best(fathergroup);
            songroup.add(opra);
            fathergroup.remove(opra);
        }
        double totalAdaptability = 0;//总适应度
        double[] adaptability = new double[fathergroup1.size()];//记录每个个体的适应度
        for (String test : fathergroup1) {
            totalAdaptability += Otsu(decode(test));
        }
        //计算每个个体的适应度
        int index = 0;
        for (String test : fathergroup1) {
            adaptability[index] = Otsu(decode(test)) / totalAdaptability;
            index++;
        }
        //计算累加适应度
        for (int i = 1; i < adaptability.length; i++) {
            adaptability[i] += adaptability[i - 1];
        }
        //轮盘赌选择
        for (int i = 0; i < songroupsize; i++) {
            Random random = new Random();
            double probability = random.nextDouble();
            int choose=0;
            for (int j = 0; j < adaptability.length; j++) {
                if (probability < adaptability[j]) {
                    choose=j;
                    break;
                }
            }
            songroup.add(fathergroup1.get(choose));
        }
        return songroup;
    }

    //交叉
    public ArrayList<String> cross(ArrayList<String> fathergrouop, double probability) {
        ArrayList<String> songroup = new ArrayList<String>();
        songroup.addAll(fathergrouop);
        Random random = new Random();
        for (int i = 0; i < fathergrouop.size() / 2; i++) {
            if (probability > random.nextDouble()) {
                int j = 0, k = 0;
                //随机配对,从种群中随机选择两个个体,单点交叉
                do {
                    j = random.nextInt(fathergrouop.size());
                    k = random.nextInt(fathergrouop.size());
                } while (j == k);
                int position = random.nextInt(gene_length);
                String parent1 = fathergrouop.get(j);
                String parent2 = fathergrouop.get(k);
                String son1 = parent1.substring(0, position) + parent2.substring(position);
                String son2 = parent2.substring(0, position) + parent1.substring(position);
                songroup.add(son1);
                songroup.add(son2);
            }
        }
        return songroup;
    }

    //变异
    public void selfMutation(String newgene) {
        this.gene = newgene;
    }

    public void mutation(ArrayList<String> fatherGroup, double probability) {
        Random random = new Random();
        for (String c : fatherGroup) {
            String newGene = c;
            for (int i = 0; i < newGene.length(); i++) {
                if (probability > random.nextDouble()) {
                    String newChar = newGene.charAt(i) == '0' ? "1" : "0";
                    newGene = newGene.substring(0, i) + newChar + newGene.substring(i + 1);
                }
            }
            selfMutation(newGene);
        }
    }

    public BufferedImage grayImage(double t){
        //图像二值化
        for (int y = 0; y < image.h; y++) {
            for (int x = 0; x < image.w; x++) {
                if (image.data[x + y * image.w] < t) {
                    image.data[x + y * image.w] = 0;

                } else {
                    image.data[x + y * image.w] = 255;
                }
            }
        }
        BufferedImage bufferedImage = new BufferedImage(image.w, image.h, BufferedImage.TYPE_INT_ARGB);
        System.out.println();
        int[] d= new int[image.w*image.h];
            for(int i=0;i<image.h;i++){
                for(int j=0;j<image.w;j++){
                    if(image.gray){
                        d[j+i*image.w] = (255<<24)|(image.data[j+i*image.w]<<16)|(image.data[j+i*image.w]<<8)|(image.data[j+i*image.w]);
                    }else{
                        d[j+i*image.w] = image.data[j+i*image.w];
                    }
                }
            }
            bufferedImage.setRGB( 0, 0, image.w, image.h, d, 0, image.w );
            return bufferedImage;
    }

    public  void  operate() throws IOException {
        File file = new File("D:\\idea\\workspace\\src\\qwx\\rengongzhineng\\image.jpg");
        BufferedImage img = ImageIO.read(file);
        image=new Image(img);
        int group_size= 50;
        ArrayList<String> group = initgroup(group_size);
        System.out.println(group);
        double cross = 0.6;//交叉的概率
        double muta = 0.01;//变异的概率
        int count=0;
        do{
            count++;
            group = select(group, group_size);
            group = cross(group, cross);
            mutation(group, muta);
        }while(count<10);
        String opra=best(group);
        int x=decode(opra);
        File newFile = new File("D:\\idea\\workspace\\src\\qwx\\rengongzhineng\\get3.png");
        ImageIO.write(grayImage(x), "png", newFile);
        System.out.println("阈值:"+x);
    }

    public static void main(String[] args) throws IOException {
        OPRA o = new OPRA();
        o.operate();
    }
}

实验结果
在这里插入图片描述在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值