影象形態S+P變換的OpenCV程式碼
// _MWT_H_
#pragma once
#include "cv.h"
#include "highgui.h"
using namespace cv;
Mat MWT(Mat img,int nlevs)
{
int ih = img.rows;
int iw = img.cols;
int ih_h = ih/2;
int iw_h = iw/2;
img.convertTo(img,CV_64F);
Mat temp = Mat(img.rows,img.cols,CV_64F,Scalar::all(0));
for(int n=nlevs;n>0;n--)
{
// rows-transformation
for(int i=0;i<ih;i++)
{
for(int j=0;j<iw_h;j++)
{
double x11 = img.at<double>(i,2*j);
double x12 = img.at<double>(i,2*j+1);
double m = (x11+x12)/2;
double d = x11-x12;
temp.at<double>(i,j) = m;
temp.at<double>(i,j+iw_h) = d;
}
}
// cols-transformation
Mat tmp = temp.clone();
for(int j=0;j<iw;j++)
{
for(int i=0;i<ih_h;i++)
{
double x11 = tmp.at<double>(2*i,j);
double x12 = tmp.at<double>(2*i+1,j);
double m = (x11+x12)/2;
double d = x11-x12;
temp.at<double>(i,j) = m;
temp.at<double>(i+ih_h,j) = d;
}
}
img = temp.clone();
iw = iw/2;
ih = ih/2;
ih_h = ih_h/2;
iw_h = iw_h/2;
}
return temp;
}
// _IMWT_H_
#pragma once
#include "cv.h"
#include "highgui.h"
using namespace cv;
// 功能計演算法x的n次方
template <class T>
T power( T x, int m)
{
int i; //迴圈次數
T p=1; //存放結果
for (i=1;i<=m;i++)
p=p*x;
return p;
}
Mat IMWT(Mat img,int nlevs)
{
// 臨時矩陣,用於儲存矩陣資料
Mat temp = Mat(img.rows,img.cols,CV_64F,Scalar::all(0));
int p = power(2,nlevs);
int iw = img.cols/p;
int ih = img.rows/p;
for(int n= nlevs;n>0;n--)
{
// colums transformation
for(int j=0;j<iw*2;j++)
{
for(int i=0;i<ih;i++)
{
double m = img.at<double>(i,j);
double d = img.at<double>(i+ih,j);
double rm = d/2;
double rd = -d/2;
temp.at<double>(2*i,j) = m+rm;
temp.at<double>(2*i+1,j) = m+rd;
}
}
// rows transformation
Mat tmp = temp.clone();
for(int i=0;i<ih*2;i++)
{
for(int j=0;j<iw;j++)
{
double m = tmp.at<double>(i,j);
double d = tmp.at<double>(i,j+iw);
double rm = d/2;
double rd = -d/2;
temp.at<double>(i,2*j) = m+rm;
temp.at<double>(i,2*j+1) = m+rd;
}
}
iw = iw*2;
ih = ih*2;
for(int i=0;i<iw;i++)
{
for(int j=0;j<ih;j++)
{
img.at<double>(i,j) = temp.at<double>(i,j);
}
}
}
temp.convertTo(temp,CV_8U,1.0,0.0);
return temp;
}
#include "cv.h"
#include "highgui.h"
#include <iostream>
#include "MWT.h"
#include "IMWT.h"
using namespace cv;
using namespace std;
int main(int argc,char** argv[])
{
cout<<"Please Input Decomposition level:"<<endl;
int nlev;
cin>>nlev;
Mat img = imread("zoneplate.png",0);
namedWindow("lena",1);
imshow("lena",img);
Mat imgdec = Mat(img.rows,img.cols,CV_64F,Scalar::all(0));
imgdec = MWT(img,nlev);
Mat tmp(imgdec);
tmp.convertTo(tmp,CV_8U);
namedWindow("imgdec",1);
imshow("imgdec",tmp);
Mat imgrec = Mat(img.rows,img.cols,CV_8U,Scalar::all(0));
imgrec = IMWT(imgdec,nlev);
namedWindow("imgrec",1);
imshow("imgrec",imgrec);
waitKey();
return 0;
}