Skip to content

Commit ee244f9

Browse files
committed
Add (optional) OpenCV wrapper for imshow()
1 parent 711763d commit ee244f9

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

matplotlibcpp.h

+36-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@
1717
#ifndef WITHOUT_NUMPY
1818
# define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
1919
# include <numpy/arrayobject.h>
20+
21+
# ifdef WITH_OPENCV
22+
# include <opencv2/opencv.hpp>
23+
# endif // WITH_OPENCV
2024
#endif // WITHOUT_NUMPY
2125

2226
#if PY_MAJOR_VERSION >= 3
@@ -472,7 +476,7 @@ bool hist(const std::vector<Numeric>& y, long bins=10,std::string color="b", dou
472476
// construct args
473477
npy_intp dims[3] = { rows, columns, colors };
474478
PyObject *args = PyTuple_New(1);
475-
PyTuple_SetItem(args, 0, PyArray_SimpleNewFromData(3, dims, type, ptr));
479+
PyTuple_SetItem(args, 0, PyArray_SimpleNewFromData(colors == 1 ? 2 : 3, dims, type, ptr));
476480

477481
// construct keyword args
478482
PyObject* kwargs = PyDict_New();
@@ -499,6 +503,37 @@ bool hist(const std::vector<Numeric>& y, long bins=10,std::string color="b", dou
499503
{
500504
internal::imshow((void *) ptr, NPY_FLOAT, rows, columns, colors, keywords);
501505
}
506+
507+
#ifdef WITH_OPENCV
508+
void imshow(const cv::Mat &image, const std::map<std::string, std::string> &keywords = {})
509+
{
510+
// Convert underlying type of matrix, if needed
511+
cv::Mat image2;
512+
NPY_TYPES npy_type = NPY_UINT8;
513+
switch (image.type() & CV_MAT_DEPTH_MASK) {
514+
case CV_8U:
515+
image2 = image;
516+
break;
517+
case CV_32F:
518+
image2 = image;
519+
npy_type = NPY_FLOAT;
520+
break;
521+
default:
522+
image.convertTo(image2, CV_MAKETYPE(CV_8U, image.channels()));
523+
}
524+
525+
// If color image, convert from BGR to RGB
526+
switch (image2.channels()) {
527+
case 3:
528+
cv::cvtColor(image2, image2, CV_BGR2RGB);
529+
break;
530+
case 4:
531+
cv::cvtColor(image2, image2, CV_BGRA2RGBA);
532+
}
533+
534+
internal::imshow(image2.data, npy_type, image2.rows, image2.cols, image2.channels(), keywords);
535+
}
536+
#endif
502537
#endif
503538

504539
template< typename Numeric>

0 commit comments

Comments
 (0)