1

我这里有一段代码。这是一个使用 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());   

    }
}

最初“边缘”以绿色背景显示为红色。然后切换为蓝色背景。这种切换是随机发生的。如何以稳定的方式在黑色背景中显示白色边缘。

4

1 回答 1

3

简而言之,在评论img.setColorTable(colorTable);之前添加。// display on label

有关更多详细信息,请在代码开头创建图像并影响颜色表:

QImage img;
img.setColorTable(colorTable);

然后在无限循环中,您正在执行以下操作:

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

发生的情况是您破坏了在代码开头创建的图像,未设置此新图像的颜色图,因此使用默认值导致彩色输出。

于 2011-09-30T13:16:14.170 回答