OpenCV:查找二进制 Mat 图像的所有非零坐标

OpenCV: Find all non-zero coordinates of a binary Mat image(OpenCV:查找二进制 Mat 图像的所有非零坐标)
本文介绍了OpenCV:查找二进制 Mat 图像的所有非零坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找二进制图像的非零 (x,y) 坐标.

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

我发现了一些对函数 countNonZero() 的引用,它只计算非零坐标和 findNonZero() 我不确定如何访问或使用,因为它似乎已从文档中完全删除.

I've found a few references to the function countNonZero() which only counts the non-zero coordinates and findNonZero() which I'm unsure how to access or use since it seems to have been removed from the documentation completely.

这个是最接近的参考我找到了,但仍然没有帮助.我将不胜感激任何具体的帮助.

This is the closest reference I found, but still not helpful at all. I would appreciate any specific help.

- 要指定,这是使用 C++

- To specify, this is using C++

推荐答案

这里解释了 findNonZero() 如何保存非零元素.以下代码对于访问二进制图像的非零坐标应该很有用.方法 1 在 OpenCV 中使用 findNonZero(),方法 2 检查每个像素以找到非零(正)像素.

Here is an explanation for how findNonZero() saves non-zero elements. The following codes should be useful to access non-zero coordinates of your binary image. Method 1 used findNonZero() in OpenCV, and Method 2 checked every pixels to find the non-zero (positive) ones.

方法一:

#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;

int main(int argc, char** argv) {
    Mat img = imread("binary image");
    Mat nonZeroCoordinates;
    findNonZero(img, nonZeroCoordinates);
    for (int i = 0; i < nonZeroCoordinates.total(); i++ ) {
        cout << "Zero#" << i << ": " << nonZeroCoordinates.at<Point>(i).x << ", " << nonZeroCoordinates.at<Point>(i).y << endl;
    }
    return 0;
}

方法二:

#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;

int main(int argc, char** argv) {
    Mat img = imread("binary image");
    for (int i = 0; i < img.cols; i++ ) {
        for (int j = 0; j < img.rows; j++) {
            if (img.at<uchar>(j, i) > 0) {  
                cout << i << ", " << j << endl;     // Do your operations
            }
        }
    }
    return 0;
}

这篇关于OpenCV:查找二进制 Mat 图像的所有非零坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)