CNN-卷积核的可视化c++实现-Day 1

头文件包含内容(部分):

typedef unsigned char u8;
typedef signed   char s8;
typedef unsigned int  u32;
typedef int           s32;
typedef float         f32;

typedef struct
{
	u8* data;
	s32 width;
	s32 height;
	s32 step;
}img_u8;

typedef struct
{
	f32* data;
	s32 width;
	s32 height;
	s32 step;
}img_f32;

#define random(x) (rand()%x)


实现部分:

卷积核初始化函数,产生0-1浮点数

void convInit(img_f32 * filterBox)
{
	srand((unsigned)time(NULL));
	s32 winSize = filterBox->height * filterBox->width;

	for (s32 i = 0; i < winSize; i++)
	{
		f32 s = random(100) / 100.f;
		filterBox->data[i] = s;
	}
}

为了可视化,需要将f32转换成u8,并利用opencv显示:

void imgf2u(img_f32 * src, img_u8* dst)
{   
	s32 dataSize = src->width * src->height;
	f32 maxVal = 0.f;

	for (s32 i = 0; i < dataSize; i++)
	{
		maxVal = src->data[i] > maxVal ? src->data[i] : maxVal;
	}

	f32 factor = 255 / (maxVal + 0.001);

	for (s32 i = 0; i < dataSize; i++)
	{
		u8 tmp = static_cast<u8>(src->data[i] * factor);
		dst->data[i] = tmp;
	}
}


void showGrayImg(img_u8* src, string winName)
{
	Mat imgShow(src->height, src->width, CV_8UC1);
	imgShow.data = src->data;
	namedWindow(winName, 0);
	imshow(winName, imgShow);
	CV_WAIT;
}

结果如下:

猜你喜欢

转载自blog.csdn.net/myzhouwang/article/details/85085184