Load an image in hard disk using OpenCV and Qt - image

I am new using Qt and OpenCV.
I am trying to read an image in my HD and show it.
It is not a specific image, the program could read any image that user select.
My code:
QString Imagename = QFileDialog::getOpenFileName(
this,
tr("Open Images"),
"C://",
tr("Tiff Files (*.tif);; Raw file (*.raw)"));
if ( Imagename.isNull())
{
QMessageBox::warning(this,"Error!","Image not valid!");
}
cv::Mat src(filename);
Mat configuration is:
Mat imread(const string& filename, int flags=1 )
How can I solve this?

cv::Mat doesn't have a contructor that accepts a string. Use imread instead. Since imread accepts std::string, not QString, just do:
cv::Mat yourImage = cv::imread(filename.toStdString());

You cannot use cv::Mat variable as you used.To solve this problem you should use "imread" function.I think following code will help you about this issue. You have to include following libraries.
#include<QFileDialog>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
int main (){
// Gets file name with QFileDialog
QString file_name=QFileDialog::getOpenFileName(this,"Open Image File","C://","Image File (*.jpg *.tiff *.png *.bmp)");
// Read image with Color Image Parameter and store on image variable which type is cv::Mat
// You should convert file name from QString to StdString to use in imread function
cv::Mat image = cv::imread(file_name.toStdString(),CV_LOAD_IMAGE_COLOR);
if(!image.data){ // Checks whether the image was read successfully
qDebug()<< "Could not open or find the image";
return -1;
}
cv::namedWindow("Original Image",WINDOW_AUTOSIZE); // Creates a window which will display image
cv::imshow("Original Image",image); // Shows image on created window
cv::waitKey(0); // Waits for a keystroke in the window
return 0; // if you created console app in qt you should use return a.exec() instead of this.
}

Related

QPrinter + QPainter writes invalid PDF file

I am simply trying to draw a rectangle to a PDF file using QPrinter + QPainter:
#include <QtWidgets>
#include <QPrinter>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFileName("/Users/jason/Desktop/example.pdf");
printer.setOutputFormat(QPrinter::PdfFormat);
QPainter painter;
painter.begin(&printer);
int width = painter.viewport().width();
int height = painter.viewport().height();
painter.setPen(Qt::black);
painter.drawRect(0.25*width, 0.25*height, 0.5*width, 0.5*height);
painter.end();
}
Using MacOS 10.15.4 and Qt 5.15.2 this results in a blank/invalid PDF file. The same code without the QPrinter.setOutputFormat and QPrinter.setOutputFileName correctly prints a rectangle on paper.
How can I using QPrinter/QPdfWriter + QPainter to draw to a PDF file?
I am a fool. I thought the PDF was blank, but it turns out if I zoom in really really far, I can see a faint grey line. Apparently the resolution of a PDF is much higher than that of my printer!
Using painter.setPen(QPen(QBrush(Qt::red), 100.0)) shows a clear rectangle as expected.

libpng 1.6.35 : Unable to render image using image format as RGBA or BGRA

I am trying to use libpng1.6.35 library to decode image data from the given input buffer and return back the decode buffer to the renderer. I want the image with a transparent background.
Below is the image which I am trying to render:
#include "png.h"
#include <stdlib.h>
#include <stdio.h>
extern unsigned char g_image[0x00080000];
unsigned char * PngFileToRGBA(unsigned int *width,
unsigned int *height)
{
png_image image;
memset(&image, 0, (sizeof image));
image.version = PNG_IMAGE_VERSION;
png_image_begin_read_from_memory(&image,
png_const_voidp(g_image), sizeof(g_image)); /*g_image contains the
input image buffer to
decode*/
png_bytep buffer1; /*buffer1 is output
decoded image buffer.*/
image.format = PNG_FORMAT_BGRA;
buffer1 = (png_bytep)malloc(PNG_IMAGE_SIZE(image));
if (buffer1 != NULL &&
png_image_finish_read(&image, NULL/*background*/, buffer1,
0/*row_stride*/, NULL/*colormap*/) != 0)
{
return buffer1;
}
}
If I use image format as BGR, I get the correct output image using buffer1, but with image format as BGRA, the output image is washed out. Please guide what I am missing here.
Output rendered images with BGR and BGR format:
with image format as BGRA:
It behaves the same even if I use image format as RGB/RGBA.

Get Pixmap out of Xlib

I've been trying to find a way of grabbing video directly from an X window and got pointed to Xlib and the compositing extension.
So far, I've been able to listen to change events and grab a Pixmap with this code:
#include <X11/Intrinsic.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xdamage.h>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char ** argv) {
int br, base;
Window win = 0x3400003;
Display *dsp = XOpenDisplay(0);
XCompositeQueryExtension(dsp, &base, &br);
XDamageQueryExtension(dsp,&base, &br);
cout << base << endl;
Damage damage = XDamageCreate(dsp, win, XDamageReportRawRectangles);
XCompositeRedirectWindow(dsp, win, CompositeRedirectAutomatic);
XEvent ev;
while(true) {
XNextEvent(dsp, &ev);
if(ev.type == base + XDamageNotify) {
Pixmap pm = XCompositeNameWindowPixmap(dsp, win);
XWindowAttributes attr;
XGetWindowAttributes(dsp, win, &attr);
XWriteBitmapFile(dsp, "test.bmp", pm, attr.width, attr.height, -1, -1);
return 0;
}
}
XCompositeUnredirectWindow(dsp, win, CompositeRedirectAutomatic);
XDamageDestroy(dsp, damage);
return 0;
}
The problem here is that the resulting bmp (created by XWriteBitmapFile) is black&white horribleness. Disregarding the fact that I don't want to write the data to file anyway, I am apparently doing something wrong in reading it.
I would love to convert the Pixmap to either a framebuffer in opengl or a binary blob in ram.
Thanks in advance for any help you can give me on this.
Best regards.
"Bitmaps" in X world refer to two-colored images. I guess XWriteBitmapFile does internally GetImage request and transforms server pixmap to a bitmap. Note that file format is it's own 'X11 bitmap', not windows bitmap.
Use XGetImage function If you actually need image's binary blob.

OpenCV cannot load image

While I was working on a project, I noticed that I am not able to load images. Here is the simple code that I used to check:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
if( argc != 2)
{
cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
return -1;
}
Mat image;
image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // Read the file
if(! image.data ) // Check for invalid input
{
cout << "Could not open or find the image" << std::endl ;
return -1;
}
Mat gray_image;
cv::cvtColor(image, gray_image, CV_RGB2GRAY);
imwrite("Gray_Image.jpg",gray_image);
return 0;
}
Here is its output when I execute it:
root#beaglebone:~# ./tryit lena.jpg
Could not open or find the image
I tried to directly use the address of the image ("/home/root/lena.jpg") instead of argv[1] but nothing changed.
What can be the problem?
ps: I am cross-compiling this OpenCV program and then running it on my BeagleBone which has Angstrom Linux installed on it. Can this problem related to it?
I solved my problem by deleting existing OpenCV libraries on my angstrom image and replacing them with the working ones.
Try saving the image with a png extension and then opening it. For some reason, files with a png extension work better than other extensions like jpg/gif.

Resizing a cell's height and Witdth and loading an image in QTableWidget

I want to make a 8*8 table with square cells ( a chess board ). Now I have the code to make the table but don't know how to resize the cells to be square shaped.
I also want to put pictures of pieces into the cells. How should I do these?
here is the code i have:
#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QHBoxLayout>
#include <QTableWidget>
class Table : public QWidget
{
public:
Table(QWidget *parent = 0);
};
Table::Table(QWidget *parent)
: QWidget(parent)
{
QHBoxLayout *hbox = new QHBoxLayout(this);
QTableWidget *table = new QTableWidget(8 , 8 , this);
hbox->addWidget(table);
setLayout(hbox);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Table t;
t.show();
return a.exec();
}
EDIT:
If anyone can help me with loading an image as the background of cell too, it would be very appreciated!
I use this code and compiler does not generate an error but program fails to run. I think the problem is with the table->item(0,0). Should I initialize it first?
QString fileName = "1.bmp";
QPixmap pic (fileName);
QIcon icon (pic);
table->item(0,0)->setIcon(icon);
To make the cells square shaped do something like this:
// set the default size, here i've set it to 20px by 20x
table->horizontalHeader()->setDefaultSectionSize(20);
table->verticalHeader()->setDefaultSectionSize(20);
// set the resize mode to fixed, so the user cannot change the height/width
table->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
table->verticalHeader()->setResizeMode(QHeaderView::Fixed);
Edit: To set the images, set the icon attribute on your QTableWidgetItems
after searching and searching and searching.... I finally got the answer. I should first make a QBrush object and set it as a background of a QtableWidgetItem and then use table->setItem !!!
QString fileName = "/1.bmp";
QPixmap pic (fileName);
QBrush brush(pic);
QTableWidgetItem* item = new QTableWidgetItem();
item->setBackground(brush);
table->setItem(0,0,item);

Resources