我这里有一段代码。 这是一个使用 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());
}
}
最初“边缘”显示为绿色背景的红色。然后切换为蓝色背景。这种切换是随机发生的。 如何以稳定的方式在黑色背景中显示白色边缘。
最佳答案
简而言之,在 //display on label
注释之前添加 img.setColorTable(colorTable);
。
有关更多详细信息,您可以在代码开头创建图像并影响颜色表:
QImage img;
img.setColorTable(colorTable);
然后在无限循环中,您正在执行以下操作:
img = QImage((const unsigned char*)(edges.data), image.cols, image.rows, QImage::Format_Indexed8);
发生的情况是您破坏了在代码开头创建的图像,未设置此新图像的颜色图,因此使用默认值导致彩色输出。
关于image - Qt-OpenCV :How to display grayscale images(opencv) in Qt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7606133/