首页 > 解决方案 > 在使用 opencv 的 C++ 中,我有一个转换为灰度图像的 uint 数组,只显示灰屏没有图像

问题描述

我想知道是否有人可以帮助我解决这个问题。我有一个数组(单暗淡),它包含足够的 uint 值来填充大小为 120x160 的屏幕。我想将数组加载到垫子中并将其显示为灰度图像。我没看到有人能帮忙吗??提前致谢。

myarray[39360];
//..
//Code populates values between 0 and 255 to the array
// I have printed the array and the values are all 0 to 255
//..
Mat img,img1;

// load the array into a mat
img(120,160,CV_8UC1,myarray);

// convert the mat to a grayscale image, 3 channel instead of the current 1
img.convertTo(img1,CV_8UC3);
namedWindow("test",WINDOW_AUTOSIZE);
imshow("test",img1);
waitKey(0);

// windows pops up but just shows a gray blank page about mid tone :-(

标签: c++arraysopencvgrayscale

解决方案


如果您想要灰度图像,不确定为什么要使用具有 3 个通道的 Mat(CV_8UC3 表示每个像素 8 个字节,无符号,3 个通道),这是您尝试执行的操作的完整示例:

#include "opencv2/highgui.hpp"
#include <vector>
#include <iostream>
#include <ctype.h>
#include <cstdlib>

int main()
{
    //  create a uint8_t array, can be unsigned char too
    uint8_t myArray[120*160];

    //  fill values
    srand(time(0));
    for (int i = 0; i < 120*160; ++i)
    {
        myArray[i] = (rand() % 255) + 1;
    }

    //  create grayscale image
    cv::Mat imgGray(120, 160, CV_8UC1, myArray);

    cv::namedWindow("test", cv::WINDOW_AUTOSIZE);
    cv::imshow("test", imgGray);
    cv::waitKey(0);

    return 0;
}

示例输出图像: 在此处输入图像描述


推荐阅读