估计PI——OpenCV&Cpp

  来源:《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文件夹,点击重新生成。(参考这里

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