cv::mat与unsigned char*相互转化之间的转换

Posted AI浩

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cv::mat与unsigned char*相互转化之间的转换相关的知识,希望对你有一定的参考价值。


#include<iostream> 
#include <opencv2/core/core.hpp> 
#include <opencv2/highgui/highgui.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
using namespace cv;
//nBandNum表示图像buffer是几通道的,例如四通道的rgba,三通道的rgb;
//nBPB表示图像的位深是8位还是16位的,默认为8位;
cv::Mat bufferToMat(unsigned char* pBuffer, int nWidth, int nHeight, int nBandNum)

	cv::Mat mDst;
	if (nBandNum == 4)
	
		mDst = cv::Mat::zeros(cv::Size(nWidth, nHeight), CV_8UC4);
	
	else if (nBandNum == 3)
	
		mDst = cv::Mat::zeros(cv::Size(nWidth, nHeight), CV_8UC3);
	
	else if (nBandNum == 1)
	
		mDst = cv::Mat::zeros(cv::Size(nWidth, nHeight), CV_8UC1);
	

	for (int j = 0; j < nHeight; ++j)
	
		unsigned char* data = mDst.ptr<unsigned char>(j);
		unsigned char* pSubBuffer = pBuffer + (j + 1) * nWidth  * nBandNum;
		memcpy(data, pSubBuffer, nWidth * nBandNum);
	
	return mDst;


int main()

	Mat orig_img = imread("D:\\\\515.jpg");

	//cv::Mat img = orig_img.clone();
	//if (orig_img.cols != 224 || orig_img.rows != 224) 
		// printf("resize %d %d to %d %d\\n", orig_img.cols, orig_img.rows, MODEL_IN_WIDTH, MODEL_IN_HEIGHT);
	//	cv::resize(orig_img, img, cv::Size(224, 224), (0, 0), (0, 0), cv::INTER_LINEAR);
	//
	//cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
	unsigned char *img_data = orig_img.data;
	Mat img_changed = bufferToMat(img_data, 1024, 768, 3);
	namedWindow("test_opencv");
	imshow("test_opencv", img_changed);
	waitKey(-1);

以上是关于cv::mat与unsigned char*相互转化之间的转换的主要内容,如果未能解决你的问题,请参考以下文章

unsigned char ** 到 opencv mat

opencv 中的 Mat_<unsigned char> - Mat 数据类型

C语言 unsigned short 如何相互转 signed char

QString类型和unsigned char data怎样相互转换

error:Assertion failed ((unsigned)i0 < (unsigned)size.p[0]) in cv::Mat::at

QImage 与 cv::Mat 之间的相互转换