• Matlab底层源码实现图像动态二值化


    理论

    通常情况下,为了算法的稳定性,图像处理算法需要具有自适应调节阈值并进一步阈值分割,这里给出一种图像动态二值化的图像预处理算法,并在最后给出图像处理的效果。

    Matlab源代码

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %动态二值化
    %Author:Zhu
    %时间:2022.6
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    clc;
    image = imread("E:\\1.jpg");
    image_matrix=image(:,:,1);
    image_matrix=double(image_matrix);
    [height,width,channels]=size(image);
    
    %迭代阈值
    threshold1 = 127;
    threshold2 = 0;
    
    %临时变量
    temp1=0;
    temp2=0;
    temp3=0;
    temp4=0;
    
    %直方图统计
    gray_map = zeros(1,256);
     for i=1:height
          for j=1:width
               T = image_matrix(i,j)+1;
               %灰度统计计数
               gray_map(T)=gray_map(T)+1;
          end
     end
     
    while(1)
        %计算下一个迭代阈值
        for i=1:threshold1
            temp1=temp1+gray_map(i)*i;
            temp2=temp2+gray_map(i);
        end
        for i=threshold1:256
            temp3=temp1+gray_map(i)*i;
            temp4=temp2+gray_map(i);
        end
        
        threshold2 =(temp1/temp2+temp3/temp4)/2;
        threshold2=ceil(threshold2);
        %看迭代结果是否收敛
        if(threshold1==threshold2)
            threshold1=ceil(threshold1);
            break;
        else
            threshold1 = threshold2;
        end
    end
    
    %对各像素进行灰度转换
    for i =1:height
        for j=1:width
            currentPixel = image_matrix(i,j);
            if(currentPixel<threshold1)
                currentPixel = 0;
            else
                currentPixel = 255;
            end
            image_matrix(i,j)=currentPixel;
        end
    end
    
    %显示图
    image_out = uint8(image_matrix);
    subplot(1,2,1);
    imshow(image);
    subplot(1,2,2);
    imshow(image_out);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    实现效果

    在这里插入图片描述

  • 相关阅读:
    一本通1072;鸡尾酒疗法
    金融业信贷风控算法8-支持向量机
    LeetCode每日一题——813. 最大平均值和的分组
    小型气象站的分类和选型要点
    Map和Set知识点
    GD32_定时器输入捕获波形频率
    LD链接脚本
    ElK docker环境搭建
    中年程序员传 2 面试爽文
    [oeasy]教您玩转python - 0002 - 你好世界(hello world!)
  • 原文地址:https://blog.csdn.net/qq_43376782/article/details/125600528