1 #include <opencv2/opencv.hpp> 2 3 using namespace std; 4 using namespace cv; 5 6 /**将Mat类型的数据转换为uchar类型*/ 7 uchar* matToUchar(Mat img) 8 { 9 int img_width = img.cols; 10 int img_height = img.rows; 11 uchar *p1 = (uchar*)malloc(sizeof(uchar)*img_height*img_width * 3); 12 for (int i = 0; i < img_width * img_height * 3; i++) 13 { 14 p1[i] = (uchar)img.at<Vec3b>(i / (img_width * 3), (i % (img_width * 3)) / 3)[i % 3]; 15 } 16 return p1; 17 } 18 19 /**将uchar类型的数据转换为Mat类型*/ 20 Mat ucharToMat(uchar *p2, int img_width, int img_height) 21 { 22 Mat img(Size(img_width, img_height), CV_8UC3); 23 for (int i = 0; i < img_width * img_height * 3; i++) 24 { 25 img.at<Vec3b>(i / (img_width * 3), (i % (img_width * 3)) / 3)[i % 3] = p2[i]; 26 } 27 return img; 28 } 29 30 int main() 31 { 32 Mat img = imread("D:\\1.jpg", 1); 33 uchar* img_p = matToUchar(img); 34 int img_width = img.cols; 35 int img_height = img.rows; 36 Mat view = ucharToMat(img_p, img_width, img_height); 37 imshow("Image view", view); 38 cvWaitKey(0); 39 cvDestroyWindow("Image view"); 40 }