Ask Your Question
0

How to create 4D mat, like dnn::blobFromImage do?

asked 2020-09-09 04:39:02 -0500

beizhengren gravatar image

updated 2020-09-09 05:39:44 -0500

Hi everyone,
I want to create a Mat with 4 dimensions, just like [1 x 3 x 416 x 416] in NCHW order.

cv::Mat mat_image = imread("dog.jpg", IMREAD_UNCHANGED);

print some attributes as following:
dims: 2
size: 576 x 768
rows: 576
cols: 768
channels: 3
Q: Without using dnn::blobFromImage, how can I convert it to [1 x 3 x 416 x 416] tensor or Mat?
Thanks!

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2020-09-09 09:20:49 -0500

berak gravatar image

updated 2020-09-10 02:08:23 -0500

do something like this:

Mat bgr = ... // you probably need to resize / crop it here

// preallocate the blob:
int siz[] = {1, 3, bgr.rows, bgr.cols};
Mat blob(4, siz, bgr.depth());

// get pointers to preallocated image planes 
vector<Mat> slices = {
    Mat(bgr.rows, bgr.cols, bgr.depth(), blob.ptr<uchar>(0,0)), // beware, hardcoded type here !
    Mat(bgr.rows, bgr.cols, bgr.depth(), blob.ptr<uchar>(0,1)),
    Mat(bgr.rows, bgr.cols, bgr.depth(), blob.ptr<uchar>(0,2)),
};

// split color planes
split(bgr, slices);
edit flag offensive delete link more

Comments

@berak Thanks for your detailed answer! I'll try it soon!

beizhengren gravatar imagebeizhengren ( 2020-09-14 03:54:43 -0500 )edit

@berak Hi, How can I convert the new bgr to fp16 type? Thank you!

beizhengren gravatar imagebeizhengren ( 2020-11-03 01:09:26 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2020-09-09 04:39:02 -0500

Seen: 167 times

Last updated: Sep 10 '20