Segmentation fault on QPixmap::load - qt

This is the code:
void MainWindow::setPic(QString loc, int panel)
{
if(panel == 1)
{
loc1 = loc;
QPixmap pmap;
facedetect(loc1.toStdString(), 1, "CAND1.jpg");
qDebug() << "Loading : " << loc1;
pmap.load(loc1); // I'm getting the segfault error in this line
qDebug() << "Loaded : " << loc1;
ui->PicView1->setPixmap(pmap);
}
}
How could I resolve this error?
BTW, I'm using Qt 4.8 with the latest Qt Creator, on Ubuntu 12.04.
I tried it with wallpapers, it crashes. I tried it with my 1x1 id pic, crashed (how rude...), I tried it with a strip of my examination schedule (cropped from a different image), it said it loaded, but the QLabel PicView1 doesn't display anything.
I tried declaring the QPixmap as global variable, got segfault.

Don't fill you image with white before loading...
Use QPixmap hence :
QString loc;
// fill loc with a path to your image file.
QPixmap pmap;
pmap.load(loc);
Be carefull, all image type can't be read with QT. Look here QtImageReading to see the datatype supported by QT.

Related

QPixmap::load() crash - trying to avoid it

I am working on a project, using Qt 4.8.3 for an ARM platform. In my project, I use QGraphicsItems... one of which is a subclass of QGraphicsPixmapItem.
The code was tested with a 32 bit bitmap image - and it crashes.
The crash occurs not just when running on the ARM, but also in QVFB.
QPixmap p;
if (!p.load(filename)) // crashes here
return false;
I have tried to surround this with a try...catch, but it did not help.
I seem unable to step in the Qt code for this version... but the crash occurs inside QImageReader::read(QImage*).
The stack trace:
QImageReader::read(QImage*)
QImageReader::read()
QPixmapData::fromFile(QString const&*, QFlags<QT::ImageConversionFlag>)
QPixmap::load(QString const&, char const*, QFlags<QT::ImageConversionFlag>)
QPixmapItem::loadItemFromFile // mine, the code above
Any other type of image works... and the same 32 bit bitmap loads properly in windows, same Qt version. It fails to load (returning false) in the same Qt version, for Desktop.
I would be happy to exclude this type of file - but I don't know how.
Is there any way to check for the image type without loading the image and avoiding the crash ?
Is there a way to perhaps load the image header only, and verify its type ?
Since you want to exclude 32-bit BMP images, you have to read a BMP header. First two bytes are the characters "BM" and bytes 28, 29 contain bits per pixel.
Here is a small example where we read a file into QByteArray, check its format and load it to QPixmap if OK.
#include <QtCore>
#include <QtGui>
int main(int argc,char** argv)
{
QApplication app(argc,argv);
QFile file("./plot.bmp");
if (!file.open(QIODevice::ReadOnly)) return 1;
QByteArray ba=file.readAll();
if(ba[0]=='B' && ba[1]=='M' && ba[28] == 32) {
qDebug() << "Wrong format!";
return 1;
}
QPixmap pixmap;
pixmap.loadFromData(ba);
qDebug()<<"OK!";
return 0;
}
Or if you don't want to read everything into memory, you can open a file using QFile, ifstream etc, check these bytes and then close it.

how to connect ITK to VTK with c++?

I am a beginner in ITK, VTK and Qt. I use visual studio 9.
I am trying to read a DICOM series with ITK and display with VTK in QVTKWidget (Qt). I based on this code http://www.itk.org/Wiki/VTK/Examples/Cxx/IO/ReadDICOMSeries and I modified according to my needs.
when I read the series DICOM with VTK and display it in QVTKWidget it works, but when I want to read this series with ITK and display with VTK in QVTKWidget, the program displays the first image of series and when I go to the next image with the mouse wheel, the program crashes.
when I debugged, I got this error:
void VTKImageExportBase::UpdateInformationCallbackFunction(void *userData)
{
static_cast< VTKImageExportBase * >
( userData )->UpdateInformationCallback();//the error is here
}
I tried ausssi ImageToVTKImageFilter class but with the same problem.
here is my code:
void essaieAppQtVTK::drawDCMSeries(std::string folderDCM)
{
typedef unsigned short PixelType;
const unsigned int Dimension = 3;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::VTKImageExport<ImageType> ImageExportType;
typedef itk::ImageSeriesReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
typedef itk::GDCMImageIO ImageIOType;
ImageIOType::Pointer dicomIO = ImageIOType::New();
reader->SetImageIO( dicomIO );
typedef itk::GDCMSeriesFileNames NamesGeneratorType;
NamesGeneratorType::Pointer nameGenerator = NamesGeneratorType::New();
nameGenerator->SetUseSeriesDetails( true );
nameGenerator->AddSeriesRestriction("0008|0021" );
nameGenerator->SetDirectory( folderDCM);
typedef std::vector< std::string > SeriesIdContainer;
const SeriesIdContainer & seriesUID = nameGenerator->GetSeriesUIDs();
std::cout << seriesUID.size() << std::endl;
SeriesIdContainer::const_iterator seriesItr = seriesUID.begin();
SeriesIdContainer::const_iterator seriesEnd = seriesUID.end();
while( seriesItr != seriesEnd )
{
std::cout << seriesItr->c_str() << std::endl;
seriesItr++;
}
std::string seriesIdentifier;
seriesIdentifier = seriesUID.begin()->c_str();
std::cout << seriesIdentifier.c_str() << std::endl;
typedef std::vector< std::string > FileNamesContainer;
FileNamesContainer fileNames;
fileNames = nameGenerator->GetFileNames( seriesIdentifier );
reader->SetFileNames( fileNames );
try
{
reader->Update();
}
catch (itk::ExceptionObject &ex)
{
std::cout << ex << std::endl;
}
//------------------------------------------------------------------------
// ITK to VTK pipeline connection.
//------------------------------------------------------------------------
// Create the itk::VTKImageExport instance and connect it to the
// itk::CurvatureFlowImageFilter.
ImageExportType::Pointer exporter = ImageExportType::New();
exporter->SetInput(reader->GetOutput());
// Create the vtkImageImport and connect it to the
// itk::VTKImageExport instance.
vtkImageImport* importer = vtkImageImport::New();
ConnectPipelines(exporter, importer);
//------------------------------------------------------------------------
// VTK pipeline.
//------------------------------------------------------------------------
this->imageViewer= vtkImageViewer2::New();
imageViewer->SetInput(importer->GetOutput());
// slice status message
//******same code *****//
// usage hint message
//******same code *****//
// create an interactor with our own style (inherit from vtkInteractorStyleImage)
// in order to catch mousewheel and key events
//******same code *****//
// add slice status message and usage hint message to the renderer
//******same code *****//
//to display the result:
ui.qvtkWidget->SetRenderWindow(imageViewer->GetRenderWindow());
ui.qvtkWidget->GetRenderWindow()->GetInteractor()- >SetInteractorStyle(myInteractorStyle);
imageViewer->Render();
ui.qvtkWidget->update();
}
Optional: My exporter and importer are as given below:
template <typename ITK_Exporter, typename VTK_Importer>
void ConnectPipelines(ITK_Exporter exporter, VTK_Importer* importer)
{
importer->SetUpdateInformationCallback(exporter->GetUpdateInformationCallback());
importer->SetPipelineModifiedCallback(exporter->GetPipelineModifiedCallback());
importer->SetWholeExtentCallback(exporter->GetWholeExtentCallback());
importer->SetSpacingCallback(exporter->GetSpacingCallback());
importer->SetOriginCallback(exporter->GetOriginCallback());
importer->SetScalarTypeCallback(exporter->GetScalarTypeCallback());
importer->SetNumberOfComponentsCallback(exporter->GetNumberOfComponentsCallback());
importer->SetPropagateUpdateExtentCallback(exporter- >GetPropagateUpdateExtentCallback());
importer->SetUpdateDataCallback(exporter->GetUpdateDataCallback());
importer->SetDataExtentCallback(exporter->GetDataExtentCallback());
importer->SetBufferPointerCallback(exporter->GetBufferPointerCallback());
importer->SetCallbackUserData(exporter->GetCallbackUserData());
}
/**
* This function will connect the given vtkImageExport filter to
* the given itk::VTKImageImport filter.
*/
template <typename VTK_Exporter, typename ITK_Importer>
void ConnectPipelines(VTK_Exporter* exporter, ITK_Importer importer)
{
importer->SetUpdateInformationCallback(exporter->GetUpdateInformationCallback());
importer->SetPipelineModifiedCallback(exporter->GetPipelineModifiedCallback());
importer->SetWholeExtentCallback(exporter->GetWholeExtentCallback());
importer->SetSpacingCallback(exporter->GetSpacingCallback());
importer->SetOriginCallback(exporter->GetOriginCallback());
importer->SetScalarTypeCallback(exporter->GetScalarTypeCallback());
importer->SetNumberOfComponentsCallback(exporter->GetNumberOfComponentsCallback());
importer->SetPropagateUpdateExtentCallback(exporter->GetPropagateUpdateExtentCallback());
importer->SetUpdateDataCallback(exporter->GetUpdateDataCallback());
importer->SetDataExtentCallback(exporter->GetDataExtentCallback());
importer->SetBufferPointerCallback(exporter->GetBufferPointerCallback());
importer->SetCallbackUserData(exporter->GetCallbackUserData());
}
Maybe there is a fault at the Pipline between ITK and VTK, please please can help me to find a solution for this problem, I spent two weeks looking for a solution but all methods have failed, maybe there has another method to bind ITK and VTK apart ImageToVTKImageFilter class. I count on your help. thank you in advance.
I faced same error at the same point you showed inside void VTKImageExportBase::UpdateInformationCallbackFunction function I was using ImageToVTKImageFilter for conversion. What I was missing is update of ITK pipeline before connecting it to VTK viewer. In ITK to VTK pipeline connection part your code is also missing same thing. So use:
exporter->SetInput(reader->GetOutput());
exporter->Update();
then go for further.

Read exif metadata of images in Qt

In my Qt app I want to read exif data of images. QImage or QPixmap don't seem to provide such hooks.
Is there any API in Qt that allows reading exif without using external libraries like libexif?
EDIT: This is a duplicate of this
For me, the best choice was easyexif by Mayank Lahiri. You only need to add two files exif.cpp and exif.h to your project.
int main(int argc, char *argv[])
{
for (int i=1; i<argc; ++i){
QFile file(argv[i]);
if (file.open(QIODevice::ReadOnly)){
QByteArray data = file.readAll();
easyexif::EXIFInfo info;
if (int code = info.parseFrom((unsigned char *)data.data(), data.size())){
qDebug() << "Error parsing EXIF: code " << code;
continue;
}
qDebug() << "Camera model : " << info.Model.c_str();
qDebug() << "Original date/time : " << info.DateTimeOriginal.c_str();
} else
qDebug() << "Can't open file:" << argv[i];
}
return 0;
}
Try QExifImageHeader from qt extended framework. qtextended.org is not available for me? but you may search for other download mirrows.
QImageReader has a method named transformation() which is introduced in version 5.5, first you should try that.
You can also check the following link to see how it's done using Windows GDI in Qt, http://amin-ahmadi.com/2015/12/17/how-to-read-image-orientation-in-qt-using-stored-exif/

QDesktopServices::openUrl with selecting specified file in explorer

In most coding programs, you can right click on the item and click show in explorer and it shows the file in explorer with the item selected. How would you do that in Qt with QDesktopServices? (or any way to do it in QT)
you can use this method to select file on Windows or MacOS ,if you want select on linux you can find a way in QtCreator sources.
void select(const QString& path){
#if defined(Q_OS_WIN)
const QString explorer = "explorer";
QStringList param;
if (!QFileInfo(path).isDir())
param << QLatin1String("/select,");
param << QDir::toNativeSeparators(path);
QProcess::startDetached(explorer, param);
#elif defined(Q_OS_MAC)
QStringList scriptArgs;
scriptArgs << QLatin1String("-e")
<< QString::fromLatin1("tell application \"Finder\" to reveal POSIX file \"%1\"")
.arg(path);
QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs);
scriptArgs.clear();
scriptArgs << QLatin1String("-e")
<< QLatin1String("tell application \"Finder\" to activate");
QProcess::execute("/usr/bin/osascript", scriptArgs);
Have you tried using the file:/// syntax? The following is taken from a code base I'm working with:
PyQt4.QtGui.QDesktopServices.openUrl(PyQt4.QtCore.QUrl('file:///%s' % dirname))

Problem with QT save() function for QImage

I have a problem which I have been trying to figure out for few days now. I am using OpenCV to get frames from a camera and then I am converting it to QImage and trying to save the frame on a disk. The problem I am facing is that if I compile/run the code in release/debug mode in visual studio then it works fine. If I run the executable created by visual studio for debug mode then it runs fine. But if I run the executable created by visual studio in release mode, the gui works well except that the QImage save() function doesn't work anymore. If I use OpenCV function for saving the frame then it works well in all modes. The QImage that I am trying to save is notNull because my comments text box displays the line I print inside but the save function returns false. I would really appreciate help.
Here is a little code:
Code for conversion between IplImage and QImage (I have also used another code, with the same result)
QImage A::IplImage2QImage(const IplImage *iplImage)
{
int height = iplImage->height;
int width = iplImage->width;
if (iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 3) {
const uchar *qImageBuffer = (const uchar*)iplImage->imageData;
QImage img(qImageBuffer, width, height, QImage::Format_RGB888);
return img.rgbSwapped();
}
else {
// qWarning() << "Image cannot be converted.";
return QImage();
}
}
void A::getFrame()
{
commentsTextBox->setText("getFrame");
if (VI.isFrameNew(device1)) {
VI.getPixels(device1, (unsigned char *)frame->imageData, false, true);
}
QImage qimg2 = IplImage2QImage(frame);
m_Label->setPixmap(QPixmap::fromImage(qimg2));
if (!qimg2.isNull()) {
x = qimg2.save("C:\\Data\\test.jpg");
commentsTextBox->append("notEmpty33");
}
}
I had the same problem to QImage::load(). I will post a copy of the solution pointed out in the link of alexisdm, in order to make it clearer.
Under windows the qjpeg4.dll must in a imageformats directory under
the application's directory by default.
Thank you!
Try something like this,
// Prepare the url,
QUrl url("file:///home/ubuntu/Desktop/image.jpg");
// Get the path,
QString path = url.path();
// Save the image,
myQimage.save(path);

Resources