0

Obviously this line is wrong.

matOut = cv2::Mat::Mat(height, width, cv2.CV_8UC4)

this one too.

Mat matOut(height, width, cv2.CV_8UC4)

How do I create an modern openCV empty matrix with a given size, shape, format? The latest openCV docs on topic don't seem to be helping... I gleaned the formats used above directly from that document. Note: I'm assuming OpenCV (import cv2) Python3, import numpy, etc...

I was looking to create an empty matrix with the intent of copying content from a different buffer into it...

edit, more failed attempts...

matOut = cv2.numpy.Mat(height, width, cv2.CV_8UC4)

matOut = numpy.array(height, width, cv2.CV_8UC4)

9
  • Does this post answer your question? stackoverflow.com/questions/37182774/… Commented Mar 29, 2021 at 4:27
  • Absolutely not.. I spent 30 minutes there dissecting the code, etc... and yes, I downvoted it. Total waste of time.. It looks like it should work, but apparently there have been dramatic changes to libraries since that answer was posted. In its current form its less than worthless. Commented Mar 29, 2021 at 4:30
  • The Python implementation of OpenCV uses numpy arrays as main data type (and matrices) - is that what are you asking? Commented Mar 29, 2021 at 4:30
  • matOut = cv2.numpy.Mat(height, width, cv2.CV_8UC4) got me thru intellisense, but when I run I get the Exception has occurred: AttributeError module cv2 has no attribute numpy. Commented Mar 29, 2021 at 4:31
  • Are you importing numpy? Commented Mar 29, 2021 at 4:32

1 Answer 1

2

So user696969 called out a largely successful solution to the question asked. You create a new shaped area via:

matOut = numpy.zeros([height, width, 4], dtype=numpy.uint8)

note I have replaced the desired content, cv2.CV_8UC4, with its expected response, the number 4. There are 4 eight bit bytes in a simple RGBA pixel descriptor. I would have preferred if OpenCV tooling had performed that response as a function call, but that didn't seem to work...

I do want to share my use case. I originally was going to create an empty shaped matrix so I could transfer data from a single dimensional array there. As I worked this problem I realized there was a better way. I start the routine where I have received a file containing 8 bit RGBA data without any prefix metadata. Think raw BMP without any header info.

matContent = numpy.frombuffer(fileContent, numpy.uint8) 
matContentReshaped = matContent.reshape(height, width, 4)
cv2.imshow("Display Window", matContentReshaped)
k = cv2.waitKey(0)

Thats it. Easy, Peasy.... Thanks to user696969 and eldesgraciado for help here.

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

Comments

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.