如何用matlab计算二值化图中白色区域的像素点个数

Python010

如何用matlab计算二值化图中白色区域的像素点个数,第1张

计算原理如下:

假设一副二值图片,其背景是黑色的,而边缘是白色的,而且白色边缘中不包含黑色的点,就如附件中的那个图像。

程序源码如下:

%% step 1

clear all

clc

I=imread('test.bmp')%读入图片

bwI=im2bw(I,0.5)%转化为二值图像

L=bwlabel(bwI,4)%将四连通区域进行标记

[r,c]=find(L==1)%查找其中的白色区域,r是白点的所在行组成的向量,c是白点所在的列组成的向量

%% step 2 %去除r中重复的数

new_r=[]

for i=1:length(r)

nn=find(new_r==r(i))

if isempty(nn),new_r=[new_r r(i)]end

end

%% step 3

sum_zeros=0%轮廓中总的点的个数

for i=1:length(new_r)

n=find(bwI(new_r(i),:)==1)%查找有白点的行中白点所在的位置

if length(n)==1,continueend%如果该行中只有一个白点,则返回

num_zeros=n(end)-n(1)+1-length(n)%否则计算夹在白点之间的黑点的个数

sum_zeros=sum_zeros+num_zeros

end

二值化图实例如下(即黑白两色):

扩展资料:

C语言实现源码:

#include "opencv2/highgui/highgui.hpp"

#include "opencv2/imgproc/imgproc.hpp"

#include "opencv2/core/core.hpp"

#include <opencv\ml.h>

#include <iostream>

#include "cv.h"

#include "highgui.h"

#include <vector>

#include <math.h>

#include <string.h>

#include <fstream>

using namespace std

using namespace cv

//统计一幅图片中白色像素点和黑色像素点占整幅图的比例

int bSums(Mat src)

{

int counter = 0

int black = 0

int n = 0

//迭代器访问像素点

Mat_<uchar>::iterator it = src.begin<uchar>()

Mat_<uchar>::iterator itend = src.end<uchar>()

for (it != itend++it)

{

n++

if ((*it) >0)

{

counter += 1//二值化后,像素点是0或者255

}

else {

black += 1

}

}

double biliB = counter * 1.0 / n * 1.0 * 100 * 1.0

double biliH = black * 1.0 / n * 1.0 * 100 * 1.0

cout <<"counter:" <<counter <<endl

cout <<"black:" <<black <<endl

cout <<"n:" <<n <<endl

cout <<"biliB:" <<biliB <<endl

cout <<"biliH:" <<biliH <<endl

return counter

}

int main(int agrc, char** agrv)

{

Mat imgPath = imread("D://XR//811416.jpg")//读取源图

//namedWindow("原图", 0)

//resizeWindow("原图", 500, 500)

imshow("原图", imgPath)

Mat a1

cvtColor(imgPath, a1, COLOR_BGR2GRAY)//转灰度

//namedWindow("灰度", 0)

//resizeWindow("灰度", 500, 500)

imshow("灰度", a1)

Mat a2

threshold(a1, a2, 0, 255, THRESH_BINARY | THRESH_OTSU)//二值化

//namedWindow("灰度", 0)

//resizeWindow("灰度", 500, 500)

imshow("灰度", a2)

int a = bSums(a2)//调用函数bSums

imshow("A", a2)

//cout <<"A:" <<a

waitKey()

return 0

}

bwlabel只是对对象进行标记而已,不能对对象进行旋转一定的角度的操作,而之后的步骤要用regionprops来完成,它是对标记对象的描述,它里边的参数有很多,有一个参数好像是orientation的是关于角度问题的,利用它才能完成旋转的操作。