본문 바로가기

분류 전체보기

다항식 곡선 피팅 알고리즘

2020. 2. 6.

 

//Polynomial Fit
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
    int i,j,k,n,N;
    cout.precision(4);                        //set precision
    cout.setf(ios::fixed);
    cout<<"\nEnter the no. of data pairs to be entered:\n";        //To find the size of arrays that will store x,y, and z values
    cin>>N;
    double x[N],y[N];
    cout<<"\nEnter the x-axis values:\n";                //Input x-values
    for (i=0;i<N;i++)
        cin>>x[i];
    cout<<"\nEnter the y-axis values:\n";                //Input y-values
    for (i=0;i<N;i++)
        cin>>y[i];
    cout<<"\nWhat degree of Polynomial do you want to use for the fit?\n";
    cin>>n;                                // n is the degree of Polynomial 
    double X[2*n+1];                        //Array that will store the values of sigma(xi),sigma(xi^2),sigma(xi^3)....sigma(xi^2n)
    for (i=0;i<2*n+1;i++)
    {
        X[i]=0;
        for (j=0;j<N;j++)
            X[i]=X[i]+pow(x[j],i);        //consecutive positions of the array will store N,sigma(xi),sigma(xi^2),sigma(xi^3)....sigma(xi^2n)
    }
    double B[n+1][n+2],a[n+1];            //B is the Normal matrix(augmented) that will store the equations, 'a' is for value of the final coefficients
    for (i=0;i<=n;i++)
        for (j=0;j<=n;j++)
            B[i][j]=X[i+j];            //Build the Normal matrix by storing the corresponding coefficients at the right positions except the last column of the matrix
    double Y[n+1];                    //Array to store the values of sigma(yi),sigma(xi*yi),sigma(xi^2*yi)...sigma(xi^n*yi)
    for (i=0;i<n+1;i++)
    {    
        Y[i]=0;
        for (j=0;j<N;j++)
        Y[i]=Y[i]+pow(x[j],i)*y[j];        //consecutive positions will store sigma(yi),sigma(xi*yi),sigma(xi^2*yi)...sigma(xi^n*yi)
    }
    for (i=0;i<=n;i++)
        B[i][n+1]=Y[i];                //load the values of Y as the last column of B(Normal Matrix but augmented)
    n=n+1;                //n is made n+1 because the Gaussian Elimination part below was for n equations, but here n is the degree of polynomial and for n degree we get n+1 equations
    cout<<"\nThe Normal(Augmented Matrix) is as follows:\n";    
    for (i=0;i<n;i++)            //print the Normal-augmented matrix
    {
        for (j=0;j<=n;j++)
            cout<<B[i][j]<<setw(16);
        cout<<"\n";
    }    
    for (i=0;i<n;i++)                    //From now Gaussian Elimination starts(can be ignored) to solve the set of linear equations (Pivotisation)
        for (k=i+1;k<n;k++)
            if (B[i][i]<B[k][i])
                for (j=0;j<=n;j++)
                {
                    double temp=B[i][j];
                    B[i][j]=B[k][j];
                    B[k][j]=temp;
                }
    
    for (i=0;i<n-1;i++)            //loop to perform the gauss elimination
        for (k=i+1;k<n;k++)
            {
                double t=B[k][i]/B[i][i];
                for (j=0;j<=n;j++)
                    B[k][j]=B[k][j]-t*B[i][j];    //make the elements below the pivot elements equal to zero or elimnate the variables
            }
    for (i=n-1;i>=0;i--)                //back-substitution
    {                        //x is an array whose values correspond to the values of x,y,z..
        a[i]=B[i][n];                //make the variable to be calculated equal to the rhs of the last equation
        for (j=0;j<n;j++)
            if (j!=i)            //then subtract all the lhs values except the coefficient of the variable whose value                                   is being calculated
                a[i]=a[i]-B[i][j]*a[j];
        a[i]=a[i]/B[i][i];            //now finally divide the rhs by the coefficient of the variable to be calculated
    }
    cout<<"\nThe values of the coefficients are as follows:\n";
    for (i=0;i<n;i++)
        cout<<"x^"<<i<<"="<<a[i]<<endl;            // Print the values of x^0,x^1,x^2,x^3,....    
    cout<<"\nHence the fitted Polynomial is given by:\ny=";
    for (i=0;i<n;i++)
        cout<<" + ("<<a[i]<<")"<<"x^"<<i;
    cout<<"\n";
    return 0;
}//output attached as .jpg

 

https://www.bragitoff.com/2015/09/c-program-for-polynomial-fit-least-squares/

 

C++ Program for Polynomial Fit (Least Squares) - BragitOff.com

//Polynomial Fit #include #include #include using namespace std; int main() { int i,j,k,n,N; cout.precision(4); //set precision cout.setf(ios::fixed); cout<<"\nEnter the no. of data pairs…

www.bragitoff.com

 

댓글

C++ Template 문법 주의사항

2020. 2. 6.

1. 함수 호출 시 리턴 값의 자료형은 선언해줘야 함 

template<typename index_t, typename vec2_t>
std::vector<index_t> triangulate(const std::vector<vec2_t> &polygon)
{
    return tri::triangulate<index_t, vec2_t>(polygon);
}


// triangulate 실행
outTriMeshIdx_List = math::triangulate<int, cv::Point2d>(inPolygon_2D_offset);

 

2. 템플릿 사용 함수의 멤버 변수는 모두 참조 형태여야 함

 

3. 템플릿 선언은 각 함수마다 할당해야함

 

4. 템플릿 변수를 전달인자로 사용하는 함수 호출 시, 선언되지 않은 인자를 입력할 경우 자료형을 적시해야함

ignore<int, double, bool>(1, 2.0, true)

5. 템플릿 변수를 사용하는 함수의 전달인자 중 구조체가 있을 때, 해당 인자는 default 매개변수로 설정 안됨. 이를 해결하기 위해선 함수오버로딩을 사용하는것이 좋음 (포인터로 선언하여 nullptr 을 초기값으로 설정..)

https://stackoverflow.com/questions/6289694/default-argument-for-structure-reference-in-c

 

Default argument for structure reference in C++

I want to give a default value to a function parameter, which is reference to a structure . What can I give as the default value ?

stackoverflow.com

6. 템플릿 함수는 헤더와 구현부가 분리되면 안됨 (특히 vector<_T> 를 사용할 경우 링크에러발생함)

http://www.cplusplus.com/forum/general/101759/

 

LNK 2019 problem - C++ Forum

LNK 2019 problem I'm trying to implement Vector with templates but, I've got a problem with linker. What did I wrong ? Does anybody can see some mistakes? I enclose all of my important files. compilation communicate: 1> vector.cpp 1> main.cpp 1> Generating

www.cplusplus.com

http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=50&MAEULNo=20&no=432364&ref=432364

 

[질문] 템플릿을 사용하면 LNK2019에러가 나옵니다. | 마을 :: 컨텐츠 상세보기

[질문] 템플릿을 사용하면 LNK2019에러가 나옵니다. | 마을 :: 컨텐츠 상세보기

www.devpia.com

 

7. 선언과 구현부를 구분하고 싶다면 .hpp 을 사용할 것

// template.h
#ifndef CLASSA_H
#define CLASSA_H
template <typename Object>
class A
{
public:
	A ();
	A (Object);
	Object foo();
private:
	Object element=0;
};
#include "template.hpp"
#endif
----------------------------------------

// template.hpp
template <typename Object>
A::A () {}

template <typename Object>
A::A (Object e) { e = element; }

template <typename Object>
Object A::foo() { return element; }

 

https://www.sapphosound.com/archives/389

 

[C++] 템플릿 클래스의 선언과 구현을 분리하는 방법 & 헤더 중복 포함 방지하기 – Roughness Leads To Perfection

이 글을 읽기 전에 C++ 템플릿 프로그래밍에 대해 [검색]해보고 이해를 해보셔야 합니다. 여기서는 결론만 말합니다. #ifndef CLASSA_H #define CLASSA_H class A { public: A () {} A (int e) { e = element; } int foo() { return element; } private: int element=0; }; #endif #ifndef CLASSA_H#define CLASSA_Hclass A

www.sapphosound.com

 

 

 

참고 사이트

http://tcpschool.com/cpp/cpp_template_function

 

코딩교육 티씨피스쿨

4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등

tcpschool.com

 

댓글

Contour Algorithm OpenCV

2020. 2. 5.
댓글

Moore Neighbor Contour Tracing algorithm

2020. 2. 5.

1. Moore Neighborhood

The Moore neighborhood of a pixel, P, is the set of 8 pixels which share a vertex or edge with that pixel. These pixels are namely pixels P1, P2, P3, P4, P5, P6, P7 and P8 shown in Figure 1 below.
The Moore neighborhood (also known as the 8-neighbors or indirect neighbors) is an important concept that frequently arises in the literature.

http://www.imageprocessingplace.com/downloads_V3/root_downloads/tutorials/contour_tracing_Abeer_George_Ghuneim/moore.html

 

Contour Tracing

 

www.imageprocessingplace.com

 

2. Moore Neighbor Contour Tracing Algorithm in C++

This post shows the implementation of Moore’s neighbor tracing algorithm in C++. This algorithm performs what is called contour tracing i.e.
tracing the borders or boundaries of, in this case, a binary image. The two images below illustrates what the algorithm does with a pure black and white/binary image.

Short explanation of how the algorithm works

Pad the image with a white 1 pixel wide border. Start scanning from the top-left position and scan each pixel from left to right downwards. When a black pixel is found, trace around the contour in a clockwise direction. Tracing the contour is done by checking the 8 neighbors and see if they are black. The neighbors are checked in a clockwise manner. When we are finished tracing the contour, we start scanning again from were we started to trace and a variable “inside” is set to true. This variable will be set back to false when a white pixel is encountered. This variable is used to prevent processing of non-contours.

A good and more detailed explanation of how this simple little algorithm works can be found here

The implementation

The function below uses a 1D pixel array which definition you can find in the header file included in the source along with some other definitions and functions that are needed to run the function. The code below simply show the implementation of the actual algorithm. The C++ files can be downloaded here along with some test files using the SDL library

The C++ files can be downloaded here along with some test files using the SDL library

The algorithm is in the contour-tracing.cpp file and the main.cpp file contains a test run of the algorithm which displays the result to the screen and saves it as a bitmap image using SDL.

pixel * mooreNeighborTracing(pixel * image, int width, int height)
{
  bool inside = false;
  int pos = 0;

  // Need to start by padding the image by 1 pixel
  pixel * paddedImage = padImage(image, width, height, WHITE);

  // Allocate new image as a 1D array
  pixel * borderImage = (pixel *)malloc(sizeof(pixel) * (height+2) * (width+2));

  // Set entire image to WHITE
  for(int y = 0; y < (height+2); y ++)
  {
    for(int x = 0; x < (width+2); x ++)
    {
      borderImage[x + y*(width+2)] = WHITE;
    }
  }

  for(int y = 0; y < (height+2); y ++)
  {
    for(int x = 0; x < (width+2); x ++)
    {
      pos = x + y*(width+2);

      // Scan for BLACK pixel
      if(borderImage[pos] == BLACK && !inside)    // Entering an already discovered border
      {
        inside = true;
      }
      else if(paddedImage[pos] == BLACK && inside)  // Already discovered border point
      {
        continue;
      }
      else if(paddedImage[pos] == WHITE && inside)  // Leaving a border
      {
        inside = false;
      }
      else if(paddedImage[pos] == BLACK && !inside)  // Undiscovered border point
      {
        borderImage[pos] = BLACK;   // Mark the start pixel
        int checkLocationNr = 1;  // The neighbor number of the location we want to check for a new border point
        int checkPosition;      // The corresponding absolute array address of checkLocationNr
        int newCheckLocationNr;   // Variable that holds the neighborhood position we want to check if we find a new border at checkLocationNr
        int startPos = pos;      // Set start position
        int counter = 0;       // Counter is used for the jacobi stop criterion
        int counter2 = 0;       // Counter2 is used to determine if the point we have discovered is one single point

        // Defines the neighborhood offset position from current position and the neighborhood
        // position we want to check next if we find a new border at checkLocationNr
        int neighborhood[8][2] = {
            {-1,7},
            {-3-width,7},
            {-width-2,1},
            {-1-width,1},
            {1,3},
            {3+width,3},
            {width+2,5},
            {1+width,5}
          };
        // Trace around the neighborhood
        while(true)
        {
          checkPosition = pos + neighborhood[checkLocationNr-1][0];
          newCheckLocationNr = neighborhood[checkLocationNr-1][1];

          if(paddedImage[checkPosition] == BLACK) // Next border point found
          {
            if(checkPosition == startPos)
            {
              counter ++;

              // Stopping criterion (jacob)
              if(newCheckLocationNr == 1 || counter >= 3)
              {
                // Close loop
                inside = true; // Since we are starting the search at were we first started we must set inside to true
                break;
              }
            }

            checkLocationNr = newCheckLocationNr; // Update which neighborhood position we should check next
            pos = checkPosition;
            counter2 = 0;             // Reset the counter that keeps track of how many neighbors we have visited
            borderImage[checkPosition] = BLACK; // Set the border pixel
          }
          else
          {
            // Rotate clockwise in the neighborhood
            checkLocationNr = 1 + (checkLocationNr % 8);
            if(counter2 > 8)
            {
              // If counter2 is above 8 we have traced around the neighborhood and
              // therefor the border is a single black pixel and we can exit
              counter2 = 0;
              break;
            }
            else
            {
              counter2 ++;
            }
          }
        }
      }
    }
  }

  // Remove white padding and return it
  pixel * clippedBorderImage = (pixel *)malloc(sizeof(pixel) * (height) * (width));
  for(int x = 0; x < width; x ++)
  {
    for(int y = 0; y < height; y ++)
    {
      clippedBorderImage[x+y*width] = borderImage[x+1+(y+1)*(width+2)];
    }
  }
  return clippedBorderImage;
}

 

https://www.eriksmistad.no/moore-neighbor-contour-tracing-algorithm-in-c/

 

Moore Neighbor Contour Tracing Algorithm in C++ – Erik Smistad

This post shows the implementation of Moore’s neighbor tracing algorithm in C++. This algorithm performs what is called contour tracing i.e. tracing the borders or boundaries of, in this case, a binary image. The two images below illustrates what the algor

www.eriksmistad.no

 

댓글

2019 Most Common 3D File Formats

2020. 1. 6.

2019년 기준으로,

3D 파일 포맷의 종류 및 점유율 순위, 많이 사용되고 있는 3D 모델 처리 SW 종류 등에 대해 잘 설명되어있음.

 

 

출처: https://all3dp.com/3d-file-format-3d-files-3d-printer-3d-cad-vrml-stl-obj/#Top

 

댓글

[산수 메모] 한 점을 지나가는 라인을 알 때, 한 점과 일정 거리만큼 떨어진 라인 위 점의 좌표

2020. 1. 3.

queryPt(x,y)

queryPt를 지나는 라인의 기울기(라디안) m

queryPt와 떨어진 일정거리 d

 

newPt.x = queryPt.x + (d * cos(m));

newPt.y = queryPt.y + (d * sin(m));

 

출처: https://nasmaki.tistory.com/entry/산수-메모-한점과-기울기를-알때-일정거리만큼-떨어진-점의-좌표 [나즈막히의 빗방울교향곡]

댓글

[알고리즘] RIFT: Multi-modal Image Matching Based on Radiation-invariant Feature Transform

2019. 12. 23.

영상 센서 타입, 촬영 기하가 상이하게 다른 두 장의 영상에 대해 특징점 매칭을 수행하는 알고리즘

관련 알고리즘으로 IMAS가 있음

 

참조:  Image Matching by Affine Simulation (IMAS)

댓글

OpenCV 2차원 Mat을 1차원 벡터에 입력하기

2019. 12. 17.
// 2차원 Mat 생성 (signed int 자료형)
cv::Mat chkMask(cv::Size(width, height), CV_32SC1, cv::Scalar(0));

// 1차원 벡터 생성 (signed int 자료형)
vector<int> chkMaskData;

// 1차원 벡터에 2차원 Mat 버퍼 복사
chkMaskData.assign((int*)chkMask.data, (int*)chkMask.data + chkMask.total());

 

댓글

Visual Studio C++ 코드 편집기의 intelisense가 많이 느릴 때

2019. 12. 17.

Visual Studio C++ 로 오픈소스 등을 함께 이용하면서 코드를 길게 작성할 경우, 인텔리센스 반응이 점점 느려지는 현상을 발견함.

 

구글링을 통해 아래의 방법으로 속도를 향상시켰음.

 

Tools -> Options -> Text Editor -> C/C++ -> Advanced -> IntelliSense
* Disable Auto Updating = True
* Disable #include Auto Complete = True
* Max Cached Translation Units = 5 이상(2~15) (VS2015에선 설정이 안됐음)
    - 일반적으로 동시에 작업하는 소스 파일수로 설정

 

단점으로는, namespace, macro, define 등의 변수에 컬러링이 안됨

 

코드를 간결하게 잘 짜는 습관이 필요할 듯..

댓글

클래스 소멸자 실행 시 포인터 멤버 변수 메모리 해제 오류

2019. 11. 17.

클래스 내 포인터 멤버 변수 정의시, 생성자와 소멸자에서 아래 처럼 메모리 할당 및 해제 관리를 해주어야 함

@class.h

class A
{
private:
    float *_buffer;
public:
    A();
    ~A();
}

@class.cpp
#include "class.h"

A::A()
{
    _buffer = new float;
}

A::~A()
{
    if(_buffer == nullptr) delet[] _buffer;
}

 

 

댓글

CLI/C++,C# 프로젝트에서 빌드 후 실행은 잘 되지만 C++ 코드에 디버깅 진입 안될 때

2019. 11. 15.

컴파일, 빌드, 실행 까지 문제없이 진행되기 때문에 원인파악이 매우 어려웠음

코드 상의 문제는 아닌것으로 파악되서 프로젝트 설정 정보를 예전에 릴리즈한 버전과 비교함

결과적으로 C# 프로젝트 설정 정보에서 아키텍처 설정이 변경되서 생긴 문제로 파악됨

 

아래 그림에서 확인할 수 있듯이,

예전 프로젝트 설정 정보는 프로세서 아키텍처가 "ADM64"로 설정되어 있었는데,

현재 프로젝트는 아키텍처 정보가 입력되어있지 않음.

 

그런데 현재 사용중인 PC의 CPU는 인텔 i7임.

따라서 문제의 원인이 아니고 우연히 고쳐졌을 경우도 있음. 

앞으로 더 지켜봐야함...

댓글

AHK로 우측 알트키 한영키로 매핑하기

2019. 11. 4.

1. 테스트 시 키보드 설정 환경

    - 레이아웃: 한글 키보드(103/106키)

    - 키보드모델명: 레오폴드 FC750R 텐키리스

2. 매핑 방법

    1) AHK 설치

    2) 메모장에 아래 스크립트 작성 후 *.ahk 파일로 저장

SC138::
Send, {vk15sc138}
Sleep, 100
return

    3) 스크립트 실행

자료출처: http://www.kbdmania.net/xe/tipandtech/121168

댓글