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);
}

猜你喜欢

转载自blog.csdn.net/hhhhhhhhhhwwwwwwwwww/article/details/124903880