워핑이라고도 하고 와핑이라고도 하는 데 모르겠당.
아.무.튼.
다음과 같이 포토샵을 이용해 왜곡 시켜버린 모나리자님의 사진이 있다.
나는 이 모나리자 그림을 왜곡 없이 멀쩡한 직사각형의 형태로 얻고 싶다.
이때 사용하는 것이 Warping 기법이다.
Mat preprocessing(Mat image) {
Mat gray_image, binary;
cvtColor(image, gray_image, CV_BGR2GRAY);
GaussianBlur(gray_image, gray_image, Size(5, 5), 0);
adaptiveThreshold(gray_image, binary, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 11, 7);
binary = binary == 255;
morphologyEx(binary, binary, MORPH_OPEN, Mat(), Point(-1, -1), 3);
binary = 255 - binary;
return binary;
}
int main() {
Mat image = imread("monas.jpg");
if (!image.data) return -1;
vector<Point> save_poly, poly;
vector<vector<Point> > contours;
vector<Point2f> corners(4);
findContours(preprocessing(image), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
vector<vector <Point> >::iterator it = contours.begin();
while (it != contours.end()) {
poly.clear();
approxPolyDP(*it, poly, 10, true);
if (poly.size() == 4) {
save_poly.assign(poly.begin(), poly.end());
polylines(image, poly, true, Scalar(255, 0, 0), 2);
corners[0] = poly[0];
corners[1] = poly[3];
corners[2] = poly[1];
corners[3] = poly[2];
}
++it;
}
Size warpSize(300, 400);
Mat warp_img(warpSize, image.type());
vector<Point2f> warpCorners(4);
warpCorners[0] = Point2f(0, 0);
warpCorners[1] = Point2f(warp_img.cols, 0);
warpCorners[2] = Point2f(0, warp_img.rows);
warpCorners[3] = Point2f(warp_img.cols, warp_img.rows);
Mat trans = getPerspectiveTransform(corners, warpCorners);
warpPerspective(image, warp_img, trans, warpSize);
imshow("Warp Image", warp_img);
imshow("image", image);
waitKey(0);
return 0;
}
결과는 다음과 같다.
사각형을 검출하기 위해 poly를 만들었는 데 얘가 좀 지 멋대로 잡아서 좌표 정리를 해줘야 한다.
자신이 각각의 좌표를 알고 있다면 굳이 사각형 검출까지 할 필요는 없다.
'전체보기 > OpenCV' 카테고리의 다른 글
Raspberry Pi OpenCV 3.2 설치 (0) | 2020.05.31 |
---|---|
Linux OpenCV g++ Compile (0) | 2020.05.31 |
OpenCV 설정 + findContours 에러 + extra 모듈 설정 (0) | 2019.11.14 |
댓글