简体   繁体   English

Qt-OpenCV:如何在Qt中显示灰度图像(opencv)

[英]Qt-OpenCV:How to display grayscale images(opencv) in Qt

I have a piece of code here. 我这里有一段代码。 This is a camera capture application using OpenCV and Qt(for GUI). 这是一个使用OpenCV和Qt(用于GUI)的相机捕获应用程序。

void MainWindow::on_pushButton_clicked()
{

    cv::VideoCapture cap(0);

    if(!cap.isOpened()) return;

    //namedWindow("edges",1);
    QVector<QRgb> colorTable;
    for (int i = 0; i < 256; i++) colorTable.push_back(qRgb(i, i, i));

    QImage img;
    img.setColorTable(colorTable);

    for(;;)
    {
        cap >> image;
        cvtColor(image, edges, CV_BGR2GRAY);
        GaussianBlur(edges, edges, cv::Size(7,7), 1.5, 1.5);
        Canny(edges, edges, 0, 30, 3);
        //imshow("edges", edges);
        if(cv::waitKey(30) >= 0) break;

    // change color channel ordering
    //cv::cvtColor(image,image,CV_BGR2RGB);

    img =  QImage((const unsigned char*)(edges.data),
    image.cols,image.rows,QImage::Format_Indexed8);

    // display on label
    ui->label->setPixmap(QPixmap::fromImage(img,Qt::AutoColor));
    // resize the label to fit the image
    ui->label->resize(ui->label->pixmap()->size());   

    }
}

Initially "edges" is displayed in red with green background.Then it switches to blue background. 最初,“边缘”以红色显示,带有绿色背景。然后切换为蓝色背景。 This switching is happening randomly. 这种切换是随机发生的。 How can I display white edges in a black background in a stable manner. 如何稳定地在黑色背景中显示白色边缘。

In short, add the img.setColorTable(colorTable); 简而言之,添加img.setColorTable(colorTable); just before the // display on label comment. // display on label注释// display on label之前。

For more details, you create your image and affect the color table at the begining of your code: 有关更多详细信息,请在代码开始时创建图像并影响颜色表:

QImage img;
img.setColorTable(colorTable);

Then in the infinite loop, you are doing the following: 然后在无限循环中,您将执行以下操作:

img =  QImage((const unsigned char*)(edges.data), image.cols, image.rows, QImage::Format_Indexed8);

What happens is that you destroy the image created at the begining of your code, the color map for this new image is not set and thus uses the default resulting in a colored output. 发生的情况是,您破坏了在代码开始时创建的图像,未设置此新图像的颜色图,因此使用默认结果,从而产生彩色输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM