I need to convert between OpenCV Mat image and Leptonica Pix image formats in C++. This is being used for binarization of 8bit gray images.
I know that i'm about 4 years late and nobody cares, but this task has frustrated me a lot 'cause leptonica's documentation is just awful.
The problem with @loot's answer is that it does not work with colored images, so here is my (maybe crude) modification of his pix8ToMat
:
cv::Mat pixToMat(Pix *pix) {
int width = pixGetWidth(pix);
int height = pixGetHeight(pix);
int depth = pixGetDepth(pix);
cv::Mat mat(cv::Size(width, height), depth == 1 ? CV_8UC1 : CV_8UC3);
for (uint32_t y = 0; y < height; ++y) {
for (uint32_t x = 0; x < width; ++x) {
if (depth == 1) {
l_uint32 val;
pixGetPixel(pix, x, y, &val);
mat.at(cv::Point(x, y)) = static_cast(255 * val);
} else {
l_int32 r, g, b;
pixGetRGBPixel(pix, x, y, &r, &g, &b);
cv::Vec3b color(b, g, r);
mat.at(cv::Point(x, y)) = color;
}
}
}
return mat;
}