Ask Your Question
1

Keeping only non-zero elements in cv::Mat

asked 2013-03-25 06:44:25 -0500

mada gravatar image

Hi,

I´ve got a problem trying to get rid of the zero valued elements in matrix. I want to remove them and keep only non-zero elements in it.

Example: Mat: [1,2,3,0,0,0,4,5,6,0,0,0...] --> [1,2,3,4,5,6,...]

What would be the easiest and fastest way to do it? I have looked into SparseMat, but does not seem to work. Any other solutions? If it is possible to do it directly in GpuMat before downloading the results to cv::Mat, it would be even better.

Thanks!

edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted
2

answered 2013-03-25 09:29:41 -0500

Guanta gravatar image

If you don't want to use SparseMat than I see only the way to do it by hand, i.e.

  1. either: cv::countNonZero(mat) -> gives you number of non-zero-elements -> create new matrix with size of this number of non-zero-elements -> fill new matrix with non-zero elements

  2. or: create std::vector of your type of numbers -> go through your matrix and push_back() those numbers which are non-zero to your vector -> create new matrix header on top of your vector

However, you should also consider to just use a mask for your following procedure, you can generate it by e.g. cv::Mat mask = (your_mat == 0).

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

Stats

Asked: 2013-03-25 06:44:25 -0500

Seen: 3,370 times

Last updated: Mar 25 '13