简体   繁体   中英

How do I create a Mat matrix using OpenCV in Python?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM