Ex2:用CImg重写、封装给定的Canny代码,并测试(Code0)
github地址:https://github.com/linjiafengyang/ComputerVision
代码文件
用CImg重写Code0文件夹中的canny.c和canny.h为canny.cpp和canny.h,并增加一个main.cpp文件作为图像数据输入并测试。
重写过程:首先替换原来的图像输入为CImg图像输入,以及对像素点的for循环更改为CImg版本cimg_forXY(),最后把原来的C语言struct结构体改成C++类。
canny.h文件
#ifndef canny_h
#define canny_h
#include "CImg.h"
using namespace cimg_library;
class Canny
{
public:
CImg<unsigned char> canny(CImg<unsigned char> grey, int width, int height);
CImg<unsigned char> cannyparam(CImg<unsigned char> grey, int width, int height,
float lowthreshold, float highthreshold,
float gaussiankernelradius, int gaussiankernelwidth,
int contrastnormalised);
Canny *allocatebuffers(const CImg<unsigned char> & grey, int width, int height);
void killbuffers(Canny *can);
int computeGradients(Canny *can, float kernelRadius, int kernelWidth);
void performHysteresis(Canny *can, int low, int high);
void follow(Canny *can, int x1, int y1, int i1, int threshold);
void normalizeContrast(CImg<unsigned char> & data, int width, int height);
float hypotenuse(float x, float y);
float gaussian(float x, float sigma);
private:
CImg<unsigned char> data; /* input image */
int width;
int height;
int *idata; /* output for edges */
int *magnitude; /* edge magnitude as detected by Gaussians */
float *xConv; /* temporary for convolution in x direction */
float *yConv; /* temporary for convolution in y direction */
float *xGradient; /* gradients in x direction, as detected by Gaussians */
float *yGradient; /* gradients in x direction,a s detected by Gaussians */
};
#endif
canny.cpp文件
#include "canny.h"
#include <math.h>
#define ffabs(x) ( (x) >= 0 ? (x) : -(x) )
#define GAUSSIAN_CUT_OFF 0.005f
#define MAGNITUDE_SCALE 100.0f
#define MAGNITUDE_LIMIT 1000.0f
#define MAGNITUDE_MAX ((int) (MAGNITUDE_SCALE * MAGNITUDE_LIMIT))
/*
Canny edge detection with default parameters
Params: grey - the greyscale image
width, height - image width and height
Returns: binary image with edges as set pixels
*/
CImg<unsigned char> Canny::canny(CImg<unsigned char> grey, int width, int height)
{
return cannyparam(grey, width, height, 2.5f, 7.5f, 2.0f, 16, 0);
}
/*
Canny edge detection with parameters passed in by user
Params: grey - the greyscale image
width, height - image dimensions
lowthreshold - default 2.5
highthreshold - default 7.5
gaussiankernelradius - radius of edge detection Gaussian, in standard deviations
(default 2.0)
gaussiankernelwidth - width of Gaussian kernel, in pixels (default 16)
contrastnormalised - flag to normalise image before edge detection (defualt 0)
Returns: binary image with set pixels as edges
*/
CImg<unsigned char> Canny::cannyparam(CImg<unsigned char> grey, int width, int height,
float lowthreshold, float highthreshold,
float gaussiankernelradius, int gaussiankernelwidth,
int contrastnormalised)
{
Canny *can = 0;
CImg<unsigned