码迷,mamicode.com
首页 > 其他好文 > 详细

估计PI——OpenCV&Cpp

时间:2016-12-15 01:06:18      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:sid   val   erro   poi   rand   src   image   opencv   .com   

  来源:《Learning Image Processing With OpenCV》

  算法原理:蒙特卡洛

  PI的计算公式:

  技术分享

  Cpp代码:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{
	const int side=100;
	const int npixels=8000;

	int i,j;
	Mat s1=Mat::zeros(side, side, CV_8UC1); // 背景黑色
	Mat s2=s1.clone();
	circle(s1, Point(side/2, side/2), side/2, 255, -1); // 白色填充的圆

	imshow("s1", s1);

	for (int k=0; k<npixels;k++)
	{
		i = rand()%side;
		j = rand()%side;
		s2.at<uchar>(i, j)=255;
	}
	Mat r;
	bitwise_and(s1, s2, r);
	imshow("s2", s2);
	imshow("r", r);

	int Acircle = countNonZero(r);
	int Asquare = countNonZero(s2);
	float Pi=4*(float)Acircle/Asquare;
	cout << "Estimated value of Pi:"<<Pi<<endl;
	waitKey();
	return 0;
}

  踩到的坑:

问题1. 看输出的s2的图像,理论上是黑背景白点,但是随机8000个点下来就看不出了,还以为是白背景黑点了。。。

解决:npixels=80

问题2:编译出现突然出现错误,error LNK1104: 无法打开***.exe

解决:删除已经生成的Debug文件夹,点击重新生成。(参考这里

估计PI——OpenCV&Cpp

标签:sid   val   erro   poi   rand   src   image   opencv   .com   

原文地址:http://www.cnblogs.com/buzhizhitong/p/6181562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!