char mat转为unsigned_openCV将1bit(1像素对应1bit)图像转为8bit(1像素对应8bit)

f13abce32f28499fc1ef565eae936145.png

前言

上篇文章讲述了如何将8bit(1像素对应8bit)图像保存为1bit(1像素对应1bit)参考我的文章https://zhuanlan.zhihu.com/p/263465009,今天完成将1bit(1像素对应1bit)图像转为8bit(1像素对应8bit)算法,也算是完成了1bit与8bit图像数据互转的功能。

代码实现

将1位图像数据转为8位Mat图像

int  binary_to_mat(int  line_byte, char * data, cv::Mat &img)
{
	int  width = img.cols;
	int  height = img.rows;
	size_t  line_size = line_byte * 8;
	size_t  bit_size = line_size * height;


	char  *p = data;  int  offset, v, v2; unsigned  char  temp;
	for (int row = height - 1; row >= 0; row--)
	{
		for (int col = 0; col < width; col++)
		{
			offset = col % 8;
			temp = 1;
			temp = temp << (8 - offset - 1);
			v = (*(p + col / 8) & temp);
			if (v == temp)
				img.data[row * width + col] = 255;
			else
				img.data[row * width + col] = 0;
		}
		p = p + line_byte;
	}
	return  0;
}

测试代码

void test()
{
        Mat img= imread(".test.bmp", 0);//加载图像 
        line_byte = (img.cols / 8 + 3) / 4 * 4;
	char* data = (char *)malloc(line_byte*img.rows);
        mat_to_binary(img, line_byte, data);
        cv::Mat dest(height, width, CV_8UC1, 255);
	binary_to_mat(line_byte, data, dest);
	imwrite("./result.bmp",dest);
	system("pause");
}

int _tmain(int argc, _TCHAR* argv[])
{
	test();
	return 0;
}

最后

如果觉得文章对您有帮助的话,别忘了给我个赞,谢谢!,顺便推荐OpenCV学习资料!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值