1. 程式人生 > >視窗分析(以平均值為例)| 裁剪

視窗分析(以平均值為例)| 裁剪

#include<stdio.h>
#include<stdlib.h>

typedef struct{
	double x0,y0; //左下角點的座標值
	int dx,dy; //柵格單元大小
	int ycount,xcount; //行列號
	double **M; //矩陣
}DEM;

DEM* CreateDEM(int xcount,int ycount); //建立DEM
int InitDEM(DEM *pDEM); //初始化DEM
void PrintDEM(DEM dem); //輸出

DEM* SubDEM(DEM dem, int row, int col, int
nrow, int ncol); //裁剪 DEM* WindowAnalysis_Mean(DEM dem, int size); //視窗分析 /*測試資料 5 5 1 3 5 2 0 4 3 8 3 4 8 5 0 6 3 2 1 3 5 6 9 7 2 4 1 */ int main() { DEM *pDEM, *pMean; int xcount,ycount; printf("輸入行列數:\n>>> "); scanf("%d%d", &xcount, &ycount); pDEM = CreateDEM(xcount, ycount); //建立DEM
InitDEM(pDEM); //初始化 PrintDEM(*pDEM); //輸出 printf("\n"); pMean = WindowAnalysis_Mean(*pDEM, 3); //3x3視窗分析求平均值 PrintDEM(*pMean); return 0; } DEM* CreateDEM(int xcount, int ycount) { DEM *p; int i; p = (DEM *)malloc(sizeof(DEM)); if (!p) exit(0); p->xcount=xcount;p->ycount=ycount; p->M =
(double **)malloc(sizeof(double *)*xcount); if (!p->M) exit(0); for (i=0; i<xcount; i++) { p->M[i] = (double *)malloc(sizeof(double)*ycount); if (!p->M[i]) exit(0); } return p; } int InitDEM(DEM *pDEM) { int i,j; printf("以矩陣的形式輸入DEM的值:\n"); for (i=0; i<pDEM->xcount; i++) { for (j=0; j<pDEM->ycount; j++) { scanf("%lf", &pDEM->M[i][j]); } } return 1; } DEM* SubDEM(DEM dem, int row, int col, int nrow, int ncol) { DEM *sub; int i,j; if (row+nrow>dem.xcount || col+ncol>dem.ycount || row>dem.xcount || col>dem.ycount) return NULL; sub = CreateDEM(nrow, ncol); for (i=0; i<nrow; i++) { for (j=0; j<ncol; j++) { sub->M[i][j] = dem.M[i+row][j+col]; } } return sub; } void PrintDEM(DEM dem) { int i,j; for (i=0; i<dem.xcount; i++) { for (j=0; j<dem.ycount; j++) { printf("%lf\t", dem.M[i][j]); } printf("\n"); } } DEM* WindowAnalysis_Mean(DEM dem, int size) { // size:視窗大小 // 例如:3X3的視窗 size=3 DEM *mean; int i,j; int x,y; int step; int x_step, y_step; int flag; double sum; mean = CreateDEM(dem.xcount, dem.ycount); for (i=0; i<mean->xcount; i++) { for (j=0; j<mean->ycount; j++) { sum = 0; //視窗的總和 step = size/2; //位移量 flag = 0; //是否越界 // 計算視窗的sum for (x_step=-step; x_step<=step && !flag; x_step++) { for (y_step=-step; y_step<=step && !flag; y_step++) { x = i+x_step; y = j+y_step; if (x<0 || y<0 || x>=mean->xcount || y>=mean->ycount) { //越界 flag = 1; //越界 } else { //沒有越界 sum += dem.M[x][y]; } } } //賦值 if (flag) { //越界了 mean->M[i][j] = dem.M[i][j]; } else { //沒有越界 mean->M[i][j] = sum/(size*size); } } } return mean; }