In OpenCV library, Vec4f is defined to be a 4-tuple floating point, similar to this:
struct Vec4f {
float data[4];
/* here we may have some methods for this struct */
inline float operator [] (int i) { return data[i]; }
};
Sometimes it is used to represent a line: data[0-1] represents a unit directional vector of that line, while data[2-3] represents a point on that line.
In many cases, I need to convert it to a two-tuple "Point". In OpenCV, a point (or vector) is defined similar to something below:
struct Point2f {
float x; // value for x-coordination
float y; // value for y-coordination
};
I want to convert a line:
Vec4f myLine;
to a directional vector and a point on that line:
Point2f & lineDirectionalVector;
Point2f & linePoint;
I don't want to copy it, so I just use references. Thus, I wrote:
Point2f & lineDirectionalVector = *(Point2f*)(&myLine[0]);
Point2f & linePoint= *(Point2f*)(&myLine[2]);
The question is: It this way a good practice? If not, how do I do it? Prehaps the first one can be written like this:
Point2f & lineDirectionalVector = reinterpret_cast<Point2f>(myLine);
Any suggestions? Preferred ways? Or perhaps I just make a copy like this:
Point2f lineDirectionalVector(myLine[0], myLine[1]);
Point2f linePoint(myLine[2], myLine[3]);
which is more readable...
The Eigen C++ linear algebra library does what you want a little more first-class with segment, head, and tail vector methods. It is normally best to embrace that which tries to make it first class as there are various errors in what you have typed that might take you a while to hunt down and if you ask what is most readable, well that code would always raise some hairs on the back of my neck... also OpenCV's whole point vs vec concept is dubious.
It's worth noting however, that arrays are guaranteed to be contiguous with no padding so there is no issue casting around various with something like that. You will need to be careful with casting structures such as Point2f though as alignment and padding issues can easily arise when structs get involved. It's a good idea to use static_asserts when you write that type of code and read relevant parts of the standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With