gpt4 book ai didi

c++ - 获取白色像素的坐标(OpenCV)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:06:52 26 4
gpt4 key购买 nike

在 OpenCV (C++) 中,我有一张黑白图像,其中一些形状看起来充满了白色 (255)。知道了这一点,我怎样才能得到图像中这些对象所在的坐标点呢?我对获取所有白色像素坐标很感兴趣。

还有比这更简洁的方法吗?

std::vector<int> coordinates_white; // will temporaly store the coordinates where "white" is found 
for (int i = 0; i<img_size.height; i++) {
for (int j = 0; j<img_size.width; j++) {
if (img_tmp.at<int>(i,j)>250) {
coordinates_white.push_back(i);
coordinates_white.push_back(j);
}
}
}
// copy the coordinates into a matrix where each row represents a *(x,y)* pair
cv::Mat coordinates = cv::Mat(coordinates_white.size()/2,2,CV_32S,&coordinates_white.front());

最佳答案

有一个内置函数可以做到这一点 cv::findNonZero

返回非零像素位置列表。

给定一个二进制矩阵(可能从 cv::threshold()cv::compare()>== 等操作返回)返回所有非零索引作为 cv::Matstd::vector<cv::Point>

例如:

cv::Mat binaryImage; // input, binary image
cv::Mat locations; // output, locations of non-zero pixels
cv::findNonZero(binaryImage, locations);
// access pixel coordinates
Point pnt = locations.at<Point>(i);

cv::Mat binaryImage; // input, binary image
vector<Point> locations; // output, locations of non-zero pixels
cv::findNonZero(binaryImage, locations);
// access pixel coordinates
Point pnt = locations[i];

关于c++ - 获取白色像素的坐标(OpenCV),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34978705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com