[英]Check if all elements of a cv::mat are positive or equal to 0
I have a matrix cv::mat A
. 我有一个矩阵
cv::mat A
Is there an easy way to check if all elements of this matrix are positive or equal to 0, and return a True boolean if this condition is true? 有没有一种简单的方法可以检查此矩阵的所有元素是正数还是等于0,如果此条件为真,则返回True布尔值?
@francesco answer is nice in terms of C++, but not really effective nor functional tho. @francesco在C ++方面的答案很好,但不是真正有效也不是功能性的。
More effective method is using OpenCV built-in operation called checkRange() , it also provides position of first invalid element and support for multi-channel array. 更有效的方法是使用名为checkRange()的 OpenCV内置操作,它还提供第一个无效元素的位置并支持多通道数组。
Example usage: 用法示例:
cv::Point *pos;
bool is_ok = cv::checkRange( A, pos, 0, DBL_MAX );
As @MarkSetchell suggested in comments, you might also find minimum value in matrix and see if it is non-negative. 正如@MarkSetchell在评论中建议的那样,您可能还会在矩阵中找到最小值并查看它是否为非负值。 There is one OpenCV operation on array called
minMaxLoc()
which unfortunately doesn't work with multi-channel arrays, so you would have to reinterper whole array as single channel, first. 在数组上有一个名为
minMaxLoc()
OpenCV操作,遗憾的是它不适用于多通道数组,所以你必须首先将整个数组重新minMaxLoc()
为单通道。
double min;
cv::minMaxLoc( A.reshape(1), &min );
To make francescos solution work, you have to specify cv::Mat
type to iterators, eg. 要使francescos解决方案正常工作,您必须为迭代器指定
cv::Mat
类型,例如。 for CV_8U
type of matrix 对于
CV_8U
类型的矩阵
bool is_all_positive = (std::find_if(m.begin<uchar>(), m.end<uchar>(),
[](auto x) { return (x < 0); }) == m.end<uchar>());
As I previously said, this is not effective approach and would be (in my opinion) more useable than checkRange()
just in case we would like to compare values of specific channels - eg checking only for values of blue color in BGR image 正如我之前所说,这不是有效的方法,并且(在我看来)比
checkRange()
)更有用,以防万一我们想比较特定通道的值 - 例如只检查BGR图像中的蓝色值
bool is_all_positive = (std::find_if(m.begin<cv::Vec3b>(), m.end<cv::Vec3b>(),
[](auto x) { return (x[0] < 0); }) == m.end<cv::Vec3b>());
To have an efficient method, rather than using procedures that iterate over all elements of the matrix, you should use a method that stops as soon as a condition is found. 要拥有一个有效的方法,而不是使用迭代矩阵的所有元素的过程,您应该使用一个在找到条件后立即停止的方法。 You can use
std::find_if
您可以使用
std::find_if
#include <algorithm>
bool is_all_positive = (std::find_if(A.begin(), A.end(),
[](auto x) { return (x < 0); }) == A.end());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.