Ask Your Question

Video mask in OpenCV

asked 2013-02-12 14:59:14 -0600

hesperus gravatar image


I'm just learning OpenCV for a school assignment. I need to mask a specific section of a given video and track the objects within this section. The section is usually specified as a rectangle, and this rectangle represents the section or the slice of the video that needs to be masked. Only objects within this slice or section must be tracked. The rectangle is formulated by getting the x,y coordinates of both the top right corner and the bottom right corner, I have already done this. Now I need to mask those rectangle dimensions out of the video. Attached is a simple representation I made to indicate what exactly should be achieved. The grey rectangle represents the area of the video that should be tracked.

The code is too long to post, but I'm currently reading the video frame by frame using VideoCapture, and every frame is being stored in a matrix (Mat currentFrame).


I have been reading some things about manipulating the matrix that represents the frame and setting the required pixel values to 0 or something along those lines, but is there any other way ? If anyone could refer me to openCV examples or particular parts of the documentation that I need to look at I would deeply appreciate it.

Thank you.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2013-02-12 15:25:46 -0600

berak gravatar image
//if all you need is the cropped image inside the rect:
Mat cropped = img(Rect(40,40,300,300));

// if instead, you want to mask out(blacken) everthing BUT the rect in your image,
// make a mask imag, 8bit, same size as your image:
mask = cv::Mat::zeros(img.size(),CV_8UC1);

// mark some rect as white: (the 'pass through' area)
mask(Rect(60,60,300,300)) = 255;

// 'and' your image with the mask
img &= mask;
edit flag offensive delete link more

answered 2013-02-13 02:09:44 -0600

You can use the ROI (Region Of Interest) doc. It create a new header and you can directly manipulate this image, without copy. You don't need to set zeros outside the ROI, if you manipulate the ROI, it's like you're manipulating a new image of the size specified in the ROI, with image's original values.

edit flag offensive delete link more

Question Tools


Asked: 2013-02-12 14:59:14 -0600

Seen: 3,855 times

Last updated: Feb 13 '13