『OpenCV』从char* 数组中读取Mat

1. 从char* 构建Mat

1.1 直接读取文件的字符数组中读取

此时传入的 char* data 为直接读取图片文件的字符数组,可以使用以下代码进行Mat构建

	/**
	 * @brief Constructing Mat directly from file byte array.
	 * 
	 * @param data image file byte array
	 * @param size The size of image file byte array
	 * @param out  dst Mat
	 * @param gray Set to true if it is a grayscale image, otherwise false.
	 */
	void charArrayToMat(const uchar* data, size_t size, cv::Mat& out, bool gray=false);
  void charArrayToMat(const uchar* data, size_t size,cv::Mat& out,bool gray) {
    
    
      if (data == nullptr || size == 0) {
    
    
           throw std::invalid_argument("Invalid input data");
       }
       std::vector<uchar> image_bytes(data, data + size);
       if (gray) {
    
    
           cv::Mat image = cv::imdecode(image_bytes, cv::IMREAD_GRAYSCALE);
           out = image;
       } else {
    
    
           cv::Mat img_color = cv::imdecode(image_bytes, cv::IMREAD_COLOR);
           out = img_color;
       }
  }

2.2 从Mat 的 data数组 恢复Mat

	/**
	 * @brief Constructing Mat directly from other Mat data.
	 * 
	 * @param data Mat.data
	 * @param w The width of image
	 * @param h The Height of image
	 * @param out dst Mat
	 * @param gray Set to true if it is a grayscale image,otherwise keep false.
	 */
	void charArrayToMat(const uchar* data, int w, int h, cv::Mat& out, bool gray=false);


  void charArrayToMat(const uchar* data, int w, int h, cv::Mat& out, bool gray) {
    
    
       if (data == nullptr || w == 0 || h == 0) {
    
    
            throw std::invalid_argument("Invalid input data");
        }

        if (gray) {
    
    
            cv::Mat image(h, w, CV_8UC1, (void*)data);
            out = image.clone();
        } else {
    
    
            cv::Mat image(h, w, CV_8UC3, (void*)data);
            out = image.clone();
        }
   }

参考内容:

2. 解析后花屏

2.1 问题描述

在这里插入图片描述

将Mat 进行裁剪后,传入data后恢复Mat. 代码如下:

cv::Mat img = cv::imread(imgP);
REQUIRE_FALSE(img.empty());
cv::Mat subImg = img(cv::Rect(10, 10, img.cols - 10, img.rows-10));
cv::Mat rstImg;
CVUtils::charArrayToMat((uchar*)subImg.data, subImg.cols, subImg.rows, rstImg);
cv::imshow("TestCropMatParse", rstImg);
cv::waitKey(-1);

2.2 解决方式

将裁剪下的子图,clone 后传入。修改代码:

 // 使用clone 进行Mat 拷贝
// cv::Mat subImg = img(cv::Rect(10, 10, img.cols - 10, img.rows-10));
cv::Mat subImg = img(cv::Rect(10, 10, img.cols - 10, img.rows-10)).clone();

结果图:
在这里插入图片描述

//TODO 2.3 原因分析

猜你喜欢

转载自blog.csdn.net/qq_30340349/article/details/130364431