很遗憾,标准C不提供图像操作功能。如果要用C语言来做的巧改饥话需要选用其他的函数库来配套使用。
上面的MATLAB程序其实是对源图像卷积操作(如果不知道什么是卷积操作,应该先弄清楚概念再来写程序),3x3卷积核分别是{-1,-1,-1,0,0,0,1,1,1}(对应im_x)和{-1,0,1,-1,0,1,-1,0,1}(对应im_y),im_xy是im_x和im_y的平方和开根而已。
因为matlab帮你把很多底层的细节,例如下面提到的图片读取、解码、显示和操作都封装的非常简单了,所以你只需要操作歼并操作图片矩阵就可以了。在C下面你需要其他函数库的帮助。
OpenCV是针对图像和视频处理的一个函数库,可以提供MATLAB下提供的一些图像操作功能。OpenCV支持使用C或者C++。(没用过OpenCV或者没自配置过函数库的同学,需要花半天到一天的时间学习怎么安装,配置编译环境等等)
我水平也不是很好,写了一个上面程序的翻译版。代码如下。
#include <highgui.h>
#include <cv.h>
#include <math.h>
/* Get value at [row, col] in matrix img */
int getPixelValue8(IplImage* img, int row, int col) {
return (img->imageData + (img->widthStep)*row)[col];
}
/* Set value at [row, col] in matrix img */
void setPixelValue8(IplImage* img, int row, int col, int val) {
(img->imageData + (img->widthStep)*row)[col] = val;
}
int main(int argc, char** argv) {
int i, j;
double val1, val2, squareRoot;
//source image path
char* path = ".\\lena.jpg";
//load source image, convert to gray scale
IplImage* src = cvLoadImage(path, CV_LOAD_IMAGE_GRAYSCALE);
//allocate space for the 3 destination image
IplImage* dstHorizontal = cvCreateImage(cvSize(src->width, src->height), IPL_DEPTH_8U, 1);
IplImage* dstVertical = cvCreateImage(cvSize(src->width, src->height), IPL_DEPTH_8U, 1);
IplImage* dstCombined = cvCreateImage(cvSize(src->width, src->height), IPL_DEPTH_8U, 1);
//define convolution kernel
double horiWeight[] = {-1.0, -1.0, -1.0, 0, 0, 0, 1.0, 1.0, 1.0};
double vertWeight[] = {-1.0, 0, 1.0, -1.0, 0, 1.0, -1.0, 0, 1.0};
CvMat horiKernel = cvMat(3, 3, CV_64FC1, horiWeight);
CvMat vertKernel = cvMat(3, 3, 孝返CV_64FC1, vertWeight);
//perform convolution
cvFilter2D(src, dstHorizontal, &horiKernel, cvPoint(-1,-1));
cvFilter2D(src, dstVertical, &vertKernel, cvPoint(-1,-1));
for(i = 1; i < src->height-1; i++){
for(j =1; j < src->width - 1; j++){
val1 = getPixelValue8(dstHorizontal, i, j);
val2 = getPixelValue8(dstVertical, i, j);
squareRoot = sqrt(val1*val1 + val2*val2);
squareRoot = squareRoot < 255 ? squareRoot : squareRoot - 255;
setPixelValue8(dstCombined, i, j, (int)(squareRoot));
}
}
//show results
cvNamedWindow("Horizontal", CV_WINDOW_AUTOSIZE);
cvShowImage("Horizontal", dstHorizontal);
cvNamedWindow("Vertical", CV_WINDOW_AUTOSIZE);
cvShowImage("Vertical", dstVertical);
cvNamedWindow("Combined", CV_WINDOW_AUTOSIZE);
cvShowImage("Combined", dstCombined);
cvWaitKey(0);
//release resources
cvReleaseImage(&dstHorizontal);
cvReleaseImage(&dstVertical);
cvReleaseImage(&dstCombined);
cvReleaseImage(&src);
cvDestroyAllWindows();
return 0;
}
原图和输出的三张结果如下所示