vs中imshow函数报错_openCV3.3.1 connectedComponentsWithStats()函数bug解决

在学习OpenCV轮廓查找并使用connectedComponentsWithStats()函数时遇到程序崩溃问题,原因是最后一个参数传入noArray()。解决方案是改传一个Mat矩阵,确保程序正常运行。分享此解决经验以供参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在学习openCV轮廓查找部分的快速连通区域分析时,将《学习opencv3》中绘制连通区域的例程(P369)手动敲了一遍,但是出现了如下报错:

262213be38d72db82fb7aa436f70778d.png

经调试发现问题出在connectedComponentsWithStats()函数的使用上。

	int nccomps = connectedComponentsWithStats(img_edge, labels, stats, noArray());

重新翻书时发现书中程序注释有这样一句话:最后一个参数输入noArray()可能会导致程序崩溃,建议传入一个矩阵以保证程序的顺利运行。于是我给最后一个参数传入了一个Mat矩阵,问题解决。全部代码如下:

  1. #include<iostream>
  2. #include<opencv2opencv.hpp>
  3. #include<algorithm>
  4. using namespace std;
  5. using namespace cv;
  6. int main(int argc, char** argv)
  7. {
  8. Mat img, img_edge, labels, img_color, stats, centroids;
  9. if (argc != 2 || (img = imread(argv[1],CV_LOAD_IMAGE_GRAYSCALE)).empty())
  10. {
  11. cout << argv[0] << endl << "error..." << endl;
  12. return -1;
  13. }
  14. //labels = Mat(img.size(), CV_8UC3);
  15. threshold(img, img_edge, 128, 255, CV_THRESH_BINARY);
  16. imshow("image after threshold", img_edge);
  17. int i;
  18. int nccomps = connectedComponentsWithStats(img_edge, labels, stats, centroids);//nccomps是轮廓个数
  19. cout << "total connected components detected:" << nccomps << endl;
  20. vector<Vec3b> colors(nccomps + 1);
  21. colors[0] = Vec3b(0, 0, 0);//背景颜色为黑色
  22. for (i = 1; i < nccomps + 1; i++)
  23. {
  24. colors[i] = Vec3b(rand() % 256, rand() % 256, rand() % 256);
  25. if (stats.at<int>(i - 1, CC_STAT_AREA) < 100)
  26. colors[i] = Vec3b(0, 0, 0);//面积太小的轮廓被填充为背景色
  27. }
  28. img_color = Mat::zeros(img.size(), CV_8UC3);
  29. for (int y = 0; y < img_color.rows; y++)
  30. {
  31. for (int x = 0; x < img_color.cols; x++)
  32. {
  33. int label = labels.at<int>(y, x);
  34. CV_Assert(0 <= label &&label <= nccomps);
  35. img_color.at<Vec3b>(y, x) = colors[label];
  36. }
  37. }
  38. imshow("labeled map", img_color);
  39. waitKey(0);
  40. return 0;
  41. }

因为我在网上没有找到这个问题的解决方式,所以写出来和大家一起交流分享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值

举报

选择你想要举报的内容(必选)
  • 内容涉黄
  • 政治相关
  • 内容抄袭
  • 涉嫌广告
  • 内容侵权
  • 侮辱谩骂
  • 样式问题
  • 其他
点击体验
DeepSeekR1满血版
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回顶部

登录后您可以享受以下权益:

×