要在原始图像上标记每一行的最左侧和最右侧非零点位置,可以使用 OpenCV 绘制圆圈或线段来表示这些位置。以下是实现该功能的完整示例代码:
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
void findAndDrawNonZeroPoints(Mat& image) {
// 确保输入是单通道的
if (image.channels() != 1) {
cerr << "Input image must be a single channel (grayscale) image." << endl;
return;
}
// 存储每一行的最左和最右非零点
vector<int> leftMost(image.rows, -1);
vector<int> rightMost(image.rows, -1);
for (int y = 0; y < image.rows; ++y) {
for (int x = 0; x < image.cols; ++x) {
if (image.at<uchar>(y, x) != 0) { // 找到非零点
if (leftMost[y] == -1) { // 如果还没有找到该行的最左边的非零点
leftMost[y] = x;
}
rightMost[y] = x; // 更新该行的最右边的位置
}
}
}
// 在原始图像上绘制结果,创建一个彩色版本以便于可视化
Mat colorImage;
cvtColor(image, colorImage, COLOR_GRAY2BGR);
for (int y = 0; y < image.rows; ++y) {
if (leftMost[y] != -1) {
// 绘制左侧非零点为绿色圆圈
circle(colorImage, Point(leftMost[y], y), 5, Scalar(0, 255, 0), -1);
}
if (rightMost[y] != -1) {
// 绘制右侧非零点为红色圆圈
circle(colorImage, Point(rightMost[y], y), 5, Scalar(0, 0, 255), -1);
}
}
// 显示原始图像和标记后的图像
imshow("Original Image", image);
imshow("Marked Image", colorImage);
waitKey(0); // 等待用户按键以关闭窗口
}
int main() {
Mat img = imread("your_image.png", IMREAD_GRAYSCALE); // 替换成你的图片路径
if (img.empty()) {
cerr << "Could not open or find the image!" << endl;
return -1;
}
findAndDrawNonZeroPoints(img);
return 0;
}
功能说明:
findAndDrawNonZeroPoints
函数:与之前相似,但增加了绘制逻辑。- 彩色转换:将灰度图像转换为彩色,以便更好地可视化标记(绿色用于左侧非零点,红色用于右侧非零点)。
- 绘制函数:使用
circle()
函数在指定位置画圆圈,以显示找到的左、右边界。
注意事项:
- 请确保你替换
your_image.png
为实际存在的灰度图像路径。 - 根据需要,你可以调整圆圈的半径或颜色。
- 使用
imshow()
显示两个窗口,一个是原始图像,一个是带有标记的新图像,等待用户按键后关闭。
内容由零声教学AI助手提供,问题来源于学员提问