OpenCV: Find all non-zero coordinates of a binary Mat image

前端 未结 3 684
失恋的感觉
失恋的感觉 2020-12-01 11:10

I\'m atttempting to find the non-zero (x,y) coordinates of a binary image.

I\'ve found a few references to the function countNonZero() which only count

3条回答
  •  情深已故
    2020-12-01 11:18

    There is the following source code that was supplied for OpenCV 2.4.3, which may be helpful:

    #include 
    #include 
    
    /*! @brief find non-zero elements in a Matrix
     *
     * Given a binary matrix (likely returned from a comparison
     * operation such as compare(), >, ==, etc, return all of
     * the non-zero indices as a std::vector (x,y)
     *
     * This function aims to replicate the functionality of
     * Matlab's command of the same name
     *
     * Example:
     * \code
     *  // find the edges in an image
     *  Mat edges, thresh;
     *  sobel(image, edges);
     *  // theshold the edges
     *  thresh = edges > 0.1;
     *  // find the non-zero components so we can do something useful with them later
     *  vector idx;
     *  find(thresh, idx);
     * \endcode
     *
     * @param binary the input image (type CV_8UC1)
     * @param idx the output vector of Points corresponding to non-zero indices in the input
     */
    void find(const cv::Mat& binary, std::vector &idx) {
    
        assert(binary.cols > 0 && binary.rows > 0 && binary.channels() == 1 && binary.depth() == CV_8U);
        const int M = binary.rows;
        const int N = binary.cols;
        for (int m = 0; m < M; ++m) {
            const char* bin_ptr = binary.ptr(m);
            for (int n = 0; n < N; ++n) {
                if (bin_ptr[n] > 0) idx.push_back(cv::Point(n,m));
            }
        }
    }
    

    Note - it looks like the function signature was wrong so I've changed the output vector to pass-by-reference.

提交回复
热议问题