for (int nRow = 0; nRow < ImgBin.rows; nRow++) { for (int nCol = 0; nCol < ImgBin.cols; nCol++) { ImgBin.row(nRow).data[nCol] = 255; } }如何将这个mat里的坐标转成点集
时间: 2024-03-27 21:38:26 浏览: 13
您可以使用OpenCV中的findNonZero函数来将二值图像转换为点集。示例代码如下:
```
Mat ImgBin; // 假设这是一个二值图像
// 将所有像素点的值设置为255
for (int nRow = 0; nRow < ImgBin.rows; nRow++) {
for (int nCol = 0; nCol < ImgBin.cols; nCol++) {
ImgBin.row(nRow).data[nCol] = 255;
}
}
// 将二值图像转换为点集
vector<Point> points;
findNonZero(ImgBin, points);
```
在上面的代码中,我们使用findNonZero函数将二值图像ImgBin转换为一个点集points。这个点集中包含了ImgBin中所有像素值为非零的像素点的坐标。您可以将这个点集用于您的后续处理。
相关问题
for (auto it : m_pts) { for (int nRow = it.y(); nRow < it.y()+4; nRow++) { for (int nCol = it.x(); nCol < it.x()+4; nCol++) { ImgBin.row(nRow).data[nCol] = 255; } } }这个函数将点集遍历,但我只想让我点下的点设为白色,该如何修改
如果你只想让点集中的点设为白色,可以使用以下代码:
```c++
for (auto it : m_pts) {
ImgBin.row(it.y()).data[it.x()] = 255;
}
```
这将只在每个点的位置上将像素设置为白色。如果你想要将每个点周围的 4x4 区域都设置为白色,可以使用以下代码:
```c++
for (auto it : m_pts) {
for (int nRow = it.y(); nRow < it.y()+4; nRow++) {
for (int nCol = it.x(); nCol < it.x()+4; nCol++) {
if (nRow >= 0 && nRow < ImgBin.rows && nCol >= 0 && nCol < ImgBin.cols) {
ImgBin.row(nRow).data[nCol] = 255;
}
}
}
}
```
这将在每个点的周围 4x4 区域内将像素设置为白色。需要注意的是,如果点集中的某个点位于图像边界上,那么周围的某些像素可能不在图像范围内,因此需要添加判断语句来避免访问越界。
在qgraphicsview中用此函数遍历多个点集for (auto it : m_pts) { /*int rect_x = it.x() - RECT_SIZE/4 ; int rect_y = it.y() - RECT_SIZE /4; cv::Rect rect(rect_x, rect_y, RECT_SIZE, RECT_SIZE); rect = rect & cv::Rect(0, 0, ImgBin.cols, ImgBin.rows); for (int nRow = rect_y - rect.height; nRow < rect_y + rect.height; nRow++) { for (int nCol = rect_x - rect.width; nCol < rect_x + rect.width; nCol++) {*/ ImgBin.row(it.y()).data[it.x()] = 255; }在超出图片的地方会进入断点
根据您提供的代码,可能是由于循环中的 rect 超出了图像的范围,导致在超出图片的地方进入了断点。
您可以在循环前加入判断,确保 rect 不会超出图像的范围。例如:
```cpp
for (auto it : m_pts) {
int rect_x = it.x() - RECT_SIZE / 4;
int rect_y = it.y() - RECT_SIZE / 4;
cv::Rect rect(rect_x, rect_y, RECT_SIZE, RECT_SIZE);
rect = rect & cv::Rect(0, 0, ImgBin.cols, ImgBin.rows);
for (int nRow = rect.y; nRow < rect.y + rect.height; nRow++) {
for (int nCol = rect.x; nCol < rect.x + rect.width; nCol++) {
ImgBin.row(nRow).data[nCol] = 255;
}
}
}
```
这里,使用 `cv::Rect` 的 `&` 运算符来确保 `rect` 不会超出图像的范围。同时,在循环中使用 `rect.x` 和 `rect.y` 作为起始值,确保不会越界。