这里的输入图像是.png类型的原图像,3通道图像,亲测无误。
#include "pch.h"
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
using namespace std;
using namespace cv;
/** 图像的宽度*/
const int img_width=60;
/**图像的高度*/
const int img_height = 60;
/**数组,存放图片大小*/
uchar p1[img_width * img_height * 3];
/**定义一个数组存放matToUchar的返回值*/
uchar *p = new uchar[img_width * img_height * 3];
/**将uchar类型的转换为Mat类型*/
Mat ucharToMat(uchar *p2)
{
Mat img(Size(img_width, img_height),CV_8UC3);
for (int i = 0; i < img_width * img_height * 3; i++)
{
img.at<Vec3b>(i / (img_width * 3), (i % (img_width * 3)) / 3)[i % 3] = p2[i];
}
return img;
}
/**将Mat类型的数据转换为uchar类型*/
uchar* matToUchar(Mat img)
{
for (int i = 0; i < img_width * img_height * 3; i++)
{
p1[i]= (uchar)img.at<Vec3b>(i / (img_width * 3), (i % (img_width * 3)) / 3)[i % 3];
}
return p1;
}
int main()
{
/**读入的原图像*/
Mat img2 = imread("d:/test/new/70.png");
p=matToUchar(img2);
/**下面这两行代码目的是输出Mat转化为uchar的值是否正确
@(int)目的是将uchar类型的数据转换为int可以直观的看到,
uchar的数据输出的是乱码
*/
for (int i = 0; i < img_width * img_height * 3; i++)
cout << (int)p[i] << endl;
Mat img = ucharToMat(p);
imshow("img",img);
waitKey(0);
return 0;
}
注:#include "pch.h"这个头文件在不同的VS版本中是不同的