![f13abce32f28499fc1ef565eae936145.png](https://img-blog.csdnimg.cn/img_convert/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学习资料!!!