导出RGB图像各分量并且计算概率分布和熵

本程序可以导出一个256*256的RGB文件的三个分量并且输出相应的概率分布和熵值,运用图像如下:
导出RGB图像各分量并且计算概率分布和熵_第1张图片
程序如下:

#include"iostream"
#include"stdio.h"
#include"math.h"
int W;
int H;
int imgsize;
using namespace std;
void outandcalcu(unsigned char* A, FILE* saveA){
     
    int i=0;
    double freq[256];
    int j=0;
    int frecount=0;
    double entropy=0;
    for(i; i<256; i++){
     
        j=0;
        frecount=0;
        for(j; j<imgsize/3; j++){
     
            if((int)A[j]==i){
     
                frecount++;
            }
        }
        freq[i]=((double)frecount/((double)imgsize/3));
        if(freq[i]!=0){
     
            entropy+=(-freq[i])*log(freq[i])/log(2);
        }
    }
    fprintf(saveA,"Symbol\tFrequency\n");
 for(i=0; i<256; i++)
 {
     
  fprintf(saveA, "%-3d\t%-8.2e\n", i, freq[i]);
 }
 fprintf(saveA, "%.4lf", entropy);
}
int main(){
     
    const char* origimg="E:\\数据压缩奇怪的作业们\\down.rgb";
    const char* rimg="E:\\数据压缩奇怪的作业们\\R_sat.txt";
    const char* gimg="E:\\数据压缩奇怪的作业们\\G_sat.txt";
    const char* bimg="E:\\数据压缩奇怪的作业们\\B_sat.txt";
    W=256;
    H=256;
    imgsize=W*H*3;
    int i=0;
    unsigned char* img=new unsigned char[imgsize];
    unsigned char* R=new unsigned char[imgsize/3];
    unsigned char* G=new unsigned char[imgsize/3];
    unsigned char* B=new unsigned char[imgsize/3];
    
    FILE* openimg=fopen(origimg, "rb");
    FILE* saveR=fopen(rimg,"w");
    FILE* saveG=fopen(gimg,"w");
    FILE* saveB=fopen(bimg,"w");
    if(openimg==NULL){
     cout<<"图片读失败了"<<endl;}
    
    fread(img, sizeof(unsigned char), imgsize, openimg);
    for(i; i<imgsize/3; i++){
     
        B[i]=img[3*i];
        G[i]=img[3*i+1];
        R[i]=img[3*i+2];
    }
    outandcalcu(R,saveR);
    outandcalcu(G,saveG);
    outandcalcu(B,saveB);
    cout<<"完事了"<<endl;
}

本程序中函数outandcalcu是用来计算数据概率密度以及熵值并且输出的。

转入excel表格后统计输出结果如下:
导出RGB图像各分量并且计算概率分布和熵_第2张图片

你可能感兴趣的:(小程序)