c++ - converting QImage to cv::Mat by using raw data -
i want convert svg graphic opencv mat object. therefore svg graphic loaded qsvgrenderer object , afterwards converted qimage object use raw data create final mat object:
void scalesvg(const cv::mat &in, qsvgrenderer &svg, cv::mat &out) { if (!svg.isvalid()) { return; } qimage image(in.cols, in.rows, qimage::format_argb32); // qpainter paints image qpainter painter(&image); svg.render(&painter); std::cout << "image byte count: " << image.bytecount() << std::endl; std::cout << "image bits: " << (int*)image.constbits() << std::endl; std::cout << "image depth: " << image.depth() << std::endl; uchar *data = new uchar[image.bytecount()]; memcpy(data, image.constbits(), image.bytecount()); out = cv::mat(image.height(), image.width(), cv_8uc4, data, cv_autostep); std::cout << "new byte count: " << out.size() << std::endl; std::cout << "new depth: " << out.depth() << std::endl; std::cout << "first bit: " << out.data[0] << std::endl; }
unfortunately, "memory access violation" error when writing resulting object file:
std::cout << (int*)out.data << std::endl; // pointer can still accessed without errors cv::imwrite("scaled.png", out); // memory access error
the file being written gets to size of 33 bytes not more (header data only??). on internet there explanation of pointer ownership in cv::mat , thought released after last reference release should not case since "out" reference. btw. way convert svg cv::mat welcome. opencv seem not support svgs looked simple way done.
as constbits indeed not work , not safe assume number of bytes per line same (it causes segfault me). found following suggestion in stereomatching's anwser:
cv::mat(img.height(), img.width(), cv_8uc4, img.bits(), img.bytesperline()).clone()
baradé's concern using bits valid, because clone result mat copy data bits, not issue.
Comments
Post a Comment