[英]How to convert Grayscale/binary Mat to QImage?
我已經開始學習Qt並且正在嘗試制作一個簡單的視頻播放器,它將加載視頻並播放它。 它工作得非常好。 現在添加了閾值功能。 閾值將從spinBox獲得。 代碼以這樣的方式編寫,即除了值0(顯示正常視頻)之外,將對spinBox中的值進行閾值處理操作。 所以這是我的功能:
void Player::run()
{
while(!stop )
{
if(!capture.read(frame))
stop = true;
// convert RGB to gray
if(frame.channels() == 3)
{
if(thresh == 0)
{
cvtColor(frame, RGBframe, CV_BGR2RGB);
img = QImage((const unsigned char*)(RGBframe.data),
RGBframe.cols,RGBframe.rows,QImage::Format_RGB888);
}
else
{
Mat temp;
cvtColor(frame, temp, CV_BGR2GRAY);
threshold(temp, binary, thresh, 255, 0);
img = QImage((const unsigned char*)(binary.data),
binary.cols, binary.rows, QImage::Format_Indexed8);
bool save = img.save("/home/user/binary.png");
cout<<"threshold value = "<<thresh<<endl;
//imshow("Binary", binary);
}
}
else
{
if(thresh == 0) // original Image
{
img = QImage((const unsigned char*)(frame.data),
frame.cols,frame.rows,QImage::Format_Indexed8);
}
else // convert to Binary Image
{
threshold(frame, binary, thresh, 255, 0);
img = QImage((const unsigned char*)(binary.data),
binary.cols, binary.rows, QImage::Format_Indexed8);
}
}
emit processedImage(img);
this->msleep(delay);
}
}
對於spinBox值等於0它運行正常但是當spinBox值遞增時我只得到黑屏。 我試過imshow(cv:: Mat binary)
,它顯示正確的二進制圖像但是當我嘗試保存QImage img
它是一些隨機的黑白像素(盡管原始幀的大小相同)。
您似乎缺少索引圖像的顏色表。 您需要添加一個顏色表(在while循環之前):
QVector<QRgb> sColorTable(256);
for (int i = 0; i < 256; ++i){ sColorTable[i] = qRgb(i, i, i); }
並且從二進制Mat
創建QImage
后,您需要添加
img.setColorTable(sColorTable);
或者,正如@KubaOber所指出的,從Qt 5.5開始,你也可以使用格式QImage::Format_Grayscale8
:
// From Qt 5.5
QImage image(inMat.data, inMat.cols, inMat.rows,
static_cast<int>(inMat.step),
QImage::Format_Grayscale8);
通常,您可以在函數中包裝所有Mat
到QImage
轉換。 下面是最初在此處找到的cvMatToQImage
的錯誤更正和更新版本。
然后,您可以從代碼中刪除所有到QImage
的轉換,並使用此函數。
QImage cvMatToQImage(const cv::Mat &inMat)
{
switch (inMat.type())
{
// 8-bit, 4 channel
case CV_8UC4:
{
QImage image(inMat.data,
inMat.cols, inMat.rows,
static_cast<int>(inMat.step),
QImage::Format_ARGB32);
return image;
}
// 8-bit, 3 channel
case CV_8UC3:
{
QImage image(inMat.data,
inMat.cols, inMat.rows,
static_cast<int>(inMat.step),
QImage::Format_RGB888);
return image.rgbSwapped();
}
// 8-bit, 1 channel
case CV_8UC1:
{
#if QT_VERSION >= 0x050500
// From Qt 5.5
QImage image(inMat.data, inMat.cols, inMat.rows,
static_cast<int>(inMat.step),
QImage::Format_Grayscale8);
#else
static QVector<QRgb> sColorTable;
// only create our color table the first time
if (sColorTable.isEmpty())
{
sColorTable.resize(256);
for (int i = 0; i < 256; ++i)
{
sColorTable[i] = qRgb(i, i, i);
}
}
QImage image(inMat.data,
inMat.cols, inMat.rows,
static_cast<int>(inMat.step),
QImage::Format_Indexed8);
image.setColorTable(sColorTable);
#endif
}
default:
qWarning() << "cvMatToQImage() - cv::Mat image type not handled in switch:" << inMat.type();
break;
}
return QImage();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.