ZBLOG

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

要在原始图像上标记每一行的最左侧和最右侧非零点位置,可以使用 OpenCV 绘制圆圈或线段来表示这些位置。以下是实现该功能的完整示例代码:

  1. #include <opencv2/opencv.hpp>
  2. #include <iostream>
  3. #include <vector>
  4. using namespace cv;
  5. using namespace std;
  6. void findAndDrawNonZeroPoints(Mat& image) {
  7. // 确保输入是单通道的
  8. if (image.channels() != 1) {
  9. cerr << "Input image must be a single channel (grayscale) image." << endl;
  10. return;
  11. }
  12. // 存储每一行的最左和最右非零点
  13. vector<int> leftMost(image.rows, -1);
  14. vector<int> rightMost(image.rows, -1);
  15. for (int y = 0; y < image.rows; ++y) {
  16. for (int x = 0; x < image.cols; ++x) {
  17. if (image.at<uchar>(y, x) != 0) { // 找到非零点
  18. if (leftMost[y] == -1) { // 如果还没有找到该行的最左边的非零点
  19. leftMost[y] = x;
  20. }
  21. rightMost[y] = x; // 更新该行的最右边的位置
  22. }
  23. }
  24. }
  25. // 在原始图像上绘制结果,创建一个彩色版本以便于可视化
  26. Mat colorImage;
  27. cvtColor(image, colorImage, COLOR_GRAY2BGR);
  28. for (int y = 0; y < image.rows; ++y) {
  29. if (leftMost[y] != -1) {
  30. // 绘制左侧非零点为绿色圆圈
  31. circle(colorImage, Point(leftMost[y], y), 5, Scalar(0, 255, 0), -1);
  32. }
  33. if (rightMost[y] != -1) {
  34. // 绘制右侧非零点为红色圆圈
  35. circle(colorImage, Point(rightMost[y], y), 5, Scalar(0, 0, 255), -1);
  36. }
  37. }
  38. // 显示原始图像和标记后的图像
  39. imshow("Original Image", image);
  40. imshow("Marked Image", colorImage);
  41. waitKey(0); // 等待用户按键以关闭窗口
  42. }
  43. int main() {
  44. Mat img = imread("your_image.png", IMREAD_GRAYSCALE); // 替换成你的图片路径
  45. if (img.empty()) {
  46. cerr << "Could not open or find the image!" << endl;
  47. return -1;
  48. }
  49. findAndDrawNonZeroPoints(img);
  50. return 0;
  51. }

功能说明:

  • findAndDrawNonZeroPoints 函数:与之前相似,但增加了绘制逻辑。
  • 彩色转换:将灰度图像转换为彩色,以便更好地可视化标记(绿色用于左侧非零点,红色用于右侧非零点)。
  • 绘制函数:使用 circle() 函数在指定位置画圆圈,以显示找到的左、右边界。

注意事项:

  • 请确保你替换 your_image.png 为实际存在的灰度图像路径。
  • 根据需要,你可以调整圆圈的半径或颜色。
  • 使用 imshow() 显示两个窗口,一个是原始图像,一个是带有标记的新图像,等待用户按键后关闭。


    内容由零声教学AI助手提供,问题来源于学员提问

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?