基本信息
源码名称:opencv计算信息熵(c++代码)
源码大小:3.02KB
文件格式:.cpp
开发语言:C/C++
更新时间:2020-03-25
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 1 元×
微信扫码支付:1 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
// first.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <opencv2/opencv.hpp>
using namespace cv;
double Entropy(Mat img);
int _tmain(int argc, _TCHAR* argv[])
{
String name = "chair_0022_Area01_001.png";
Mat src_color = imread("picture/1/" name);//读取原彩色图
/*int c = src_color.cols ;
int r = src_color.rows ;
int tt = src_color.channels();*/
Mat src_gray;//彩色图像转化成灰度图
cvtColor(src_color, src_gray, COLOR_BGR2GRAY);
imwrite("picture/Gray/Gray_" name, src_gray);//保存图像文件
//Mat img = imread("gray.png");
double x = Entropy(src_color);
std::cout << x << std::endl;
std::cout << src_color.cols << std::endl;
std::cout << src_color.rows << std::endl;
std::cout << src_color.channels() << std::endl;
double x1 = Entropy(src_gray);
std::cout << x1 << std::endl;
std::cout << src_gray.cols << std::endl;
std::cout << src_gray.rows << std::endl;
std::cout << src_gray.channels() << std::endl;
system("pause");
return 0;
}
double Entropy(Mat img)
{
//将输入的矩阵为图像
double temp[256];
/*清零*/
for (int i = 0; i < 256; i )
{
temp[i] = 0.0;
}
/*计算每个像素的累积值*/
for (int m = 0; m < img.rows; m )
{
const uchar* t = img.ptr<uchar>(m);
for (int n = 0; n < img.cols; n )
{
int i = t[n];
temp[i] = temp[i] 1;
}
}
/*计算每个像素的概率*/
for (int i = 0; i < 256; i )
{
temp[i] = temp[i] / (img.rows*img.cols);
}
double result = 0;
/*根据定义计算图像熵*/
for (int i = 0; i < 256; i )
{
if (temp[i] == 0.0)
result = result;
else
result = result - temp[i] * (log(temp[i]) / log(2.0));
}
return result;
}
void calc_2D_entropy(cv::Mat &input, cv::Mat &output){
int height = input.rows;
int width = input.cols;
cv::Mat out = cv::Mat::zeros(height, width, CV_32FC1);
//template size
int w = 3;
for (int i = w; i < height - w; i )
{
float *data = out.ptr<float>(i);
for (int j = w; j < width - w; j )
{
//cv::Mat Hist = cv::Mat::zeros(1, 256, CV_32F);
float Hist[256] = { 0 };
for (int p = i - w; p < i w 1; p )
{
uchar *t = input.ptr<uchar>(p);
for (int q = j - w; q < j w 1; q )
{
int tmp = t[q];
//cout << "tmp:" << tmp << endl;
Hist[tmp] = Hist[tmp] 1;
}
}
float sumHist = 0;
for (int ii = 0; ii < 256; ii )
{
sumHist = Hist[ii];
}
//get the probality
for (int ii = 0; ii < 256; ii )
{
Hist[ii] = Hist[ii] / sumHist;
//if (Hist[ii] != 0)
// cout << ii << ":" << Hist[ii] << endl;
}
//calculate the entropy
for (int k = 0; k < 256; k )
{
float v = Hist[k];
float z = data[j];
//cout << "z:" << z << endl;
if (v != 0)
{
double H = v * (log(v) / (float)log(2.0));
//H = H * 80.5 - 1;
data[j] = data[j] - H;
//data[j] = data[j] v * log(1 / v);
//cout << j << ":" << data[j] << endl;
}
}
}
}
normalize(out, output);
output = output * 255;
}