티스토리 뷰

 

#include "pch.h"
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

void onMouse(int, int, int, int, void *);
void dusflq(Point2f, Point2f, Point2f);

int cnt = 0;
double a, b, c;

Mat image(500, 500, CV_8UC3, Scalar(255, 100, 100));
Point2f m_pt1, m_pt2, m_pt3;

int main() {

	line(image, Point(0, 480), Point(499, 480), Scalar(0), 1); // x축
	line(image, Point(20, 0), Point(20, 499), Scalar(0), 1);   // y축
	imshow("포물선", image);

	setMouseCallback("포물선", onMouse, 0);
	waitKey();
	return 0;
}

void onMouse(int event, int x, int y, int flags, void * params) {

	switch (event) {

	case EVENT_LBUTTONDOWN:
		char text[20] = "";

		Point2f center(x, y), pts[4];
		circle(image, center, 10, Scalar(20), 1);
		

		sprintf(text, "(%d, %d)", (int)center.x, (int)center.y);
		putText(image, text, Point(center.x - 30, center.y + 25), 2, 0.4, Scalar(0), 1);

		if (cnt == 0) {
			m_pt1 = Point2f(x - 20, 480 - y);
			printf("pt1.x : %lf, pt1.y : %lf\n", m_pt1.x, m_pt1.y);
		}

		else if (cnt == 1) {
			m_pt2 = Point2f(x - 20, 480 - y);
			printf("pt2.x : %lf, pt2.y : %lf\n", m_pt2.x, m_pt2.y);
		}
		else if (cnt == 2) {
			m_pt3 = Point2f(x - 20, 480 - y);
			printf("pt3.x : %lf, pt3.y : %lf\n", m_pt3.x, m_pt3.y);

			dusflq(m_pt1, m_pt2, m_pt3);
			
			Point ps(20, 480); // 시작 지점

			int x, y, xx, yy;

			for (int x = 0; x < 500; x++) {
				y = x * x * a + x * b + c;
				xx = ps.x + x;
				yy = ps.y - y;

				// 출력 범위 제한
				xx = max(min(500 - 1, xx), 0);
				yy = max(min(500 - 1, yy), 0);

				image.at<Vec3b>(yy, xx) = Vec3b(255, 255, 255);
			}
			cnt = -1;
		}

		imshow("포물선", image);
		cnt++;
		break;
	}
}

void dusflq(Point2f pt1, Point2f pt2, Point2f pt3) {

	Mat abc;
	Mat A = (Mat_<float>(3, 3) << pow(pt1.x, 2), pt1.x, 1, pow(pt2.x, 2), pt2.x, 1, pow(pt3.x, 2), pt3.x, 1);
	Mat B = (Mat_<float>(3, 1) << pt1.y, pt2.y, pt3.y);
	
	solve(A, B, abc);
	cout << "Coefficients:\n " << abc << endl;

	a = abc.at<float>(0);
	b = abc.at<float>(1);
	c = abc.at<float>(2);

	cout << "Equation:\n y = " << a << "x^2 + " << b << "x + " << c << endl;
}

sprintf 에러: https://j0n9m1n1.com/254