码迷,mamicode.com
首页 > 其他好文 > 详细

OpenCV Mat和Uchar互转

时间:2020-06-12 12:52:53      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:mes   tom   sizeof   for   bsp   char   clu   pac   height   

 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 }

 

OpenCV Mat和Uchar互转

标签:mes   tom   sizeof   for   bsp   char   clu   pac   height   

原文地址:https://www.cnblogs.com/ybqjymy/p/13098603.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!