Alignment using COG

asked 2017-03-11 23:37:57 -0600

Nuz gravatar image

updated 2017-03-12 07:04:17 -0600

Hello..i am using COG to align an image. But, when the image is being translated to the center of gravity, it is showing the old image boundary and the new translated image, which is not a good result.What i want is just the new aligned image without the old image boundary. Can someone help me with this?

Here is the code:

   #include "opencv2\opencv.hpp"
     #include<vector>

      using namespace cv;
      using namespace std;

      void moveContour(vector<Point>& allContours, int x, int y)
      {
for (size_t i = 0; i < allContours.size(); i++)
{
    allContours[i].x += x;
    allContours[i].y += y;
}
  }

      int findBiggestContour(vector<vector<Point> > allContours) {
int indexOfBiggestContour = -1;
int sizeOfBiggestContour = 0;
for (int i = 0; i < allContours.size(); i++) {
    if (allContours[i].size() > sizeOfBiggestContour) {
        sizeOfBiggestContour = allContours[i].size();
        indexOfBiggestContour = i;
    }
}
return indexOfBiggestContour;
    }



        int main()
       {

vector<vector<Point>> allContours;
vector<Vec4i> hierarchy;

Mat img = imread("C:/Users/nuzha/Desktop/Contour16.jpg", IMREAD_GRAYSCALE);

//calculate moments
Moments mu = moments(img, true);

Point COG;//center of gravity

COG = Point(mu.m10 / mu.m00, mu.m01 / mu.m00); //find the COG of ROI

Mat drawing = Mat::zeros(img.size(), CV_8UC1);
Point center(drawing.cols / 2, drawing.rows / 2);

Mat alignedImage = Mat::zeros(img.size(), CV_8UC1); //align the contour

circle(img, COG, 2, Scalar(125, 100, 0), 3, 8);
circle(img, center, 2, Scalar(125, 100, 0), 3, 8);


findContours(img, allContours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
int indexOfContour = findBiggestContour(allContours);

if (indexOfContour > -1)
{
    drawContours(drawing, allContours, indexOfContour, Scalar(255), -1, 8, hierarchy);
    std::vector<Point> ROI;
    ROI = allContours[indexOfContour];
    mu = moments(ROI);

    //Translate the ROI to the COG of the image
    int x;//horizontal
    if (COG.x > center.x)
    {
        x = COG.x - center.x;
        x = -x;
    }
    else
    {
        x = (COG.x - center.x)*-1;
    }

    int y;//vertical

    if (COG.y < center.y)
    {
        y = center.y - COG.y;
    }
    else
    {
        y = center.y - COG.y;
    }

    moveContour(allContours[indexOfContour], x, y);
    drawContours(alignedImage, allContours, indexOfContour, Scalar(255), -1, 8, hierarchy);
}

imshow("Aligned", alignedImage);
imwrite("Aligned.jpg", alignedImage);
waitKey();

return 0;
       }
edit retag flag offensive close merge delete

Comments

1

I don't understand your program. You read a grayscale image in jpg and apply moments to this image. Please read docs

LBerger gravatar imageLBerger ( 2017-03-12 04:54:32 -0600 )edit

what is COG?

jsxyhelu gravatar imagejsxyhelu ( 2017-03-14 00:12:17 -0600 )edit