首先在Matlab中,我们可以用自带的图像处理函数,实现这种简单灰度的提取功能,也可以自己实现。下面贴出代码。
clear all;clc;
str = pwd;
index_dir = findstr( str, '\' );
str_temp = str( 1 : index_dir(end) );
filename = strcat( str_temp, '3_自制图片库\lena.bmp');
img = imread(filename);
imshow(img);
disp('------------调用matlab库函数--------------------');
%求最大灰度值
Max = max(max(img));
%求最小灰度值
Min = min(min(img));
%求平均灰度值
Avg = mean(mean(img));
fprintf('Max = %d\nMin = %d\nAvg = %f\n', Max, Min, Avg);
disp('--------------以下自己实现----------------------');
%%下面程序速度慢很多
[m, n] = size(img);
ma = 0;
mi = 255;
av = 0;
sum = 0; % matlab中默认为double类型
for i = 1 : m
for j = 1 : n
if img(i, j) > ma
ma = img(i, j);
end
if img(i, j) < mi
mi = img(i, j);
end
sum = sum + double( img(i, j) ); % 注意这里:matlab中 double + uint8 = uint8 所以不做转换的话,数据会溢出
end
end
av = sum / (m * n);
fprintf('Max = %d\nMin = %d\nAvg = %f\n', ma, mi, av);
程序所用灰度图片:
下面是运行结果
------------调用matlab库函数--------------------
Max = 245
Min = 25
Avg = 124.042511
Time = 0.007000
--------------以下自己实现----------------------
Max = 245
Min = 25
Avg = 124.042511
Time = 3.539000
从时间运行上来看,自己实现的函数会慢很多,因为没有用到matlab语言的向量化编程,所以推荐使用第一种调用库函数的方法。
—————————————————————————————————————————————————————————————————–
下面简单用Opencv实现一下,也很简单:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char **argv)
{
Mat img = imread("lena.bmp");
if( img.empty() )
{
cout<< "找不到图像文件"<< endl;
return -1;
}
if( img.channels() == 3 )
cvtColor(img, img, CV_RGB2GRAY );
int max = 0;
int min = 255;
double sum = 0;
double avg = 0;
double t = (double)getTickCount(); //计时开始
for( int i = 0; i < img.rows; i++ )
{
for( int j = 0; j < img.cols; j++ )
{
//img.at<Vec3b>(i,j)[0]= 255;
//img.at<Vec3b>(i,j)[1]= 255;
//img.at<Vec3b>(i,j)[2]= 255;
if ( img.at<uchar>(i, j) > max )
max = img.at<uchar>(i, j);
if ( img.at<uchar>(i, j) < min )
min = img.at<uchar>(i, j);
sum += img.at<uchar>(i, j);
}
}
avg = sum / ( ( img.rows) * (img.cols) );
t = ((double)getTickCount() - t)/getTickFrequency(); //计时结束
cout<< "Max = "<< max<< endl;
cout<< "Min = "<< min<< endl;
cout<< "Avg = "<< avg<< endl;
cout << "Times passed in seconds: " << t << endl;
imshow("lena", img);
waitKey();
return 0;
}
运行结果:
Max = 245
Min = 25
Avg = 124.043
Times passed in seconds: 0.104919
从运行结果看:opencv必Matlab库函数也是慢很多。不过这里opencv中好像没有库函数来直接实现。有待发现。
版权声明:本文为hh555800原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。