OpenCV

Python(파이썬)에서 OpenCV를 이용해 perspective correction 사진 교정하기

HooSL 2022. 1. 11. 10:58

먼저 필요한 라이브러리를 import 해줍니다.

import cv2
import numpy as np
from numpy.matrixlib import matrix

#점을 찍으면 좌표를 찾아주는 함수입니다.
from utils import get_four_points

위의 좌표찍어주는 함수입니다.

utils.py를 새로만들어 주세요

# Copyright 2017 BIG VISION LLC ALL RIGHTS RESERVED
# 
# This code is made available to the students of 
# the online course titled "Computer Vision for Faces" 
# by Satya Mallick for personal non-commercial use. 
#
# Sharing this code is strictly prohibited without written
# permission from Big Vision LLC. 
#
# For licensing and other inquiries, please email 
# spmallick@bigvisionllc.com 
#

import cv2
import numpy as np

def mouse_handler(event, x, y, flags, data) :
    
    if event == cv2.EVENT_LBUTTONDOWN :
        cv2.circle(data['im'], (x,y),3, (0,0,255), 5, 16);
        cv2.imshow("Image", data['im']);
        if len(data['points']) < 4 :
            data['points'].append([x,y])

def get_four_points(im):
    
    # Set up data to send to mouse handler
    data = {}
    data['im'] = im.copy()
    data['points'] = []
    
    #Set the callback function for any mouse event
    cv2.imshow("Image",im)
    cv2.setMouseCallback("Image", mouse_handler, data)
    cv2.waitKey(0)
    
    # Convert array to np.array
    points = np.vstack(data['points']).astype(float)
    
    return points

4점을 찍는데 시계방향으로 찍어야합니다.

 

image = cv2.imread('data/images/book1.jpg')

# cv2.imshow('original',image) #원본이미지 출력

point_src = get_four_points(image)

point_dst = np.array([0,0, 300,0, 300,400, 0,400]) #시계 방향으로
point_dst = point_dst.reshape(4,2)

matrix, status = cv2.findHomography(point_src,point_dst)

image_dst = cv2.warpPerspective(image,matrix,(300,400))

cv2.imshow('dst',image_dst)

cv2.waitKey(0)
cv2.destroyAllWindows()