3

In OpenCV, when I need to create a cv::Mat, I will need to do something along the line of

cv::Mat new_mat(width, height, CV_32FC3)

What happens if I only know that I need the elements to be either float or double + whether I need 1/2/3 channels in runtime?

In other words, given the element type (float) and number of channel (int), how can I construct the term: CV_32FC3?

1 Answer 1

6

Read the source for cxtypes.h. It contains lines like the following:

#define CV_32FC1 CV_MAKETYPE(CV_32F,1)
#define CV_32FC2 CV_MAKETYPE(CV_32F,2)
#define CV_32FC3 CV_MAKETYPE(CV_32F,3)
#define CV_32FC4 CV_MAKETYPE(CV_32F,4)
#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n))

#define CV_64FC1 CV_MAKETYPE(CV_64F,1)
#define CV_64FC2 CV_MAKETYPE(CV_64F,2)
#define CV_64FC3 CV_MAKETYPE(CV_64F,3)
#define CV_64FC4 CV_MAKETYPE(CV_64F,4)
#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n))

CV_MAKETYPE is defined as:

#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT))

This suggests the following code:

bool isdouble;
int nchannels;
// ...
if (isdouble) typeflag = CV_64FC(nchannels);
else typeflag = CV_32FC(nchannels);

I haven't tested this; let me know if it works. Also: I hate opencv's terrible type safety.

Sign up to request clarification or add additional context in comments.

2 Comments

I use CV_MAKETYPE directly instead of the short-hand. Your solution works.
@Dat Chu: How do you find out the depth having only the typename of each element? (I'm trying to compute the type in a template method).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.