我已经编写了一个简单的dragon curve分形。它似乎在大多数情况下都起作用,但是存在一个奇怪的逻辑错误,该错误将某些行的旋转方向移动了一个像素。通常这不是问题,但是经过几代人的努力,以适当的大小,分形看起来似乎很奇怪。
我正在c ++中使用open cv生成它,但是我很确定这是一个计算错误,而不是显示错误。我已经多次将这些值打印到控制台上,并亲眼看到,在两个值之间,它们之间存在一位数字的差异,这是完全相同的,这意味着一行的一端可能是200,另一端是201。 >
这里是完整代码:
#include<iostream>
#include<cmath>
#include<opencv2/opencv.hpp>
const int width=500;
const int height=500;
const double PI=std::atan(1)*4.0;
struct point{
int x;
int y;
point(int x_,int y_){
x=x_;
y=y_;
}};
cv::Mat img(width,height,CV_8UC3,cv::Scalar(255,255,255));
double deg_to_rad(double degrees){return degrees*PI/180;}
point rotate(int degree, int centx, int centy, int ll) {
double radians = deg_to_rad(degree);
return point(centx + (ll * std::cos(radians)), centy + (ll * std::sin(radians)));
}
void generate(point & r, std::vector < point > & verticies, int rotation = 90) {
int curRotation = 90;
bool start = true;
point center = r;
point rot(0, 0);
for (point i: verticies) {
double dx = center.x - i.x;
double dy = center.y - i.y;
//distance from centre
int ll = std::sqrt(dx * dx + dy * dy);
//angle from centre
curRotation = std::atan2(dy, dx) * 180 / PI;
//add 90 degrees of rotation
rot = rotate(curRotation + rotation, center.x, center.y, ll);
verticies.push_back(rot);
//endpoint, where the next centre will be
if (start) {
r = rot;
start = false;
}
}
}
void gen(int gens, int bwidth = 1) {
int ll = 7;
std::vector < point > verticies = {
point(width / 2, height / 2 - ll),
point(width / 2, height / 2)
};
point rot(width / 2, height / 2);
for (int i = 0; i < gens; i++) {
generate(rot, verticies);
}
//draw lines
for (int i = 0; i < verticies.size(); i += 2) {
cv::line(img, cv::Point(verticies[i].x, verticies[i].y), cv::Point(verticies[i + 1].x, verticies[i + 1].y), cv::Scalar(0, 0, 0), 1, 8);
}
}
int main() {
gen(10);
cv::imshow("", img);
cv::waitKey(0);
return 0;
}
我已经编写了一个简单的龙形曲线分形。它似乎在大多数情况下都起作用,但是存在一个奇怪的逻辑错误,该错误将某些行的旋转方向移动了一个像素。这通常不会是...
首先,您使用int
存储点坐标-这是一个坏主意-您失去了所有点位置的准确性。使用double
或float
。