ZBLOG

C++ opencv 图像每一行最左侧非零点位置提取 最右侧非零点位置提取 并画在原始图像上

要在原始图像上标记每一行的最左侧和最右侧非零点位置,可以使用 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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=18754

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?