Quantcast
Channel: OpenCV Q&A Forum - Latest question feed
Viewing all articles
Browse latest Browse all 600

Alignment using COG

$
0
0
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 using namespace cv; using namespace std; void moveContour(vector& 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> 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> allContours; vector hierarchy; Mat gray = imread("C:/Users/nuzha/Desktop/Contour16.jpg", IMREAD_GRAYSCALE); //calculate moments Moments mu = moments(gray, 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(gray.size(), CV_8UC1); Point center(drawing.cols / 2, drawing.rows / 2); Mat res; cvtColor(gray, res, CV_GRAY2BGR); Mat alignedImage = Mat::zeros(gray.size(), CV_8UC1); //align the contour circle(res, COG, 2, Scalar(0, 0, 255), 3, 8); circle(res, center, 2, Scalar(0, 0, 255), 3, 8); findContours(gray, 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 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("COG", res); imwrite("COG.jpg", res); imshow("Aligned", alignedImage); imwrite("Aligned.jpg", alignedImage); waitKey(); return 0; }

Viewing all articles
Browse latest Browse all 600

Latest Images

Trending Articles



Latest Images