#python
import cv2
import numpy as np
src = None
srcPts = np.zeros((4, 2), dtype=np.float32)
dstPts = np.zeros((4, 2), dtype=np.float32)
def on_mouse(event, x, y, flags, param):
global src, srcPts
cnt = param[0]
if event == cv2.EVENT_LBUTTONDOWN:
if cnt < 4:
srcPts[cnt] = [x, y]
cnt += 1
cv2.circle(src, (x, y), 5, (0, 0, 255), -1)
cv2.imshow("src", src)
if cnt == 4:
w, h = 200, 300
dstPts[0] = [0, 0]
dstPts[1] = [w - 1, 0]
dstPts[2] = [w - 1, h - 1]
dstPts[3] = [0, h - 1]
pers = cv2.getPerspectiveTransform(srcPts, dstPts)
dst = cv2.warpPerspective(src, pers, (w, h))
cv2.imshow("dst", dst)
cv2.namedWindow("src")
cv2.setMouseCallback("src", on_mouse, [0])
src = cv2.imread("D:\\projects\\SampleCode\\006939-master\\ch08\\perspective\\card.bmp")
if src is None:
print("Image load failed!")
else:
cv2.imshow("src", src)
cv2.waitKey(0)
cv2.destroyAllWindows()
// C++
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
Mat src;
Point2f srcPts[4], dstPts[4];
void on_mouse(int event, int x, int y, int flags, void* userdata);
int main()
{
src = imread("card.bmp");
if (src.empty()) {
cerr << "Image load failed!" << endl;
return -1;
}
namedWindow("src");
setMouseCallback("src", on_mouse);
imshow("src", src);
waitKey(0);
return 0;
}
void on_mouse(int event, int x, int y, int flags, void*)
{
static int cnt = 0;
if (event == EVENT_LBUTTONDOWN) {
if (cnt < 4) {
srcPts[cnt++] = Point2f(x, y);
circle(src, Point(x, y), 5, Scalar(0, 0, 255), -1);
imshow("src", src);
if (cnt == 4) {
int w = 200, h = 300;
dstPts[0] = Point2f(0, 0);
dstPts[1] = Point2f(w - 1, 0);
dstPts[2] = Point2f(w - 1, h - 1);
dstPts[3] = Point2f(0, h - 1);
Mat pers = getPerspectiveTransform(srcPts, dstPts);
Mat dst;
warpPerspective(src, dst, pers, Size(w, h));
imshow("dst", dst);
}
}
}
}
C++ Code 출처 : OpenCV 4로 배우는 컴퓨터 비전과 머신 러닝 - 황선규 저
'OpenCV' 카테고리의 다른 글
ch09 hough (0) | 2024.05.20 |
---|---|
ch09 edges (0) | 2024.05.20 |
ch08 affine (0) | 2024.05.20 |
ch07 sharpen (0) | 2024.05.20 |
ch07 noise (0) | 2024.05.20 |