Skip to content

Instantly share code, notes, and snippets.

@mimaun
Created December 24, 2016 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mimaun/6fdec3f15571944ae6034e473dee0f59 to your computer and use it in GitHub Desktop.
Save mimaun/6fdec3f15571944ae6034e473dee0f59 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import cv2
from PIL import Image
import pytesseract
import sys
import math
if __name__ == '__main__':
## 画像読み込み
filename = 'traff3.jpg'
img = cv2.imread(filename, cv2.IMREAD_COLOR)
# 補正したい画像中の台形の四隅の座標
# upper left
Q1 = np.array([int(192), int(136)])
# upper right
Q2 = np.array([int(607), int(115)])
# lower right
Q3 = np.array([int(658), int(382)])
# lower left
Q4 = np.array([int(230), int(408)])
ratio = 1.6
# 補正後の長方形の高さと幅
newRecHeihgt = int(math.sqrt((Q3[0]-Q2[0])*(Q3[0]-Q2[0]) + (Q3[1]-Q2[1])*(Q3[1]-Q2[1])))
newRecWidth = int(ratio * newRecHeihgt)
# 補正後の新しい四隅の座標
R1 = Q1
R2 = np.array([R1[0]+newRecWidth, R1[1]])
R3 = np.array([R1[0]+newRecWidth, R1[1]+newRecHeihgt])
R4 = np.array([R1[0], R1[1]+newRecHeihgt])
# 補正後の長方形の形を赤線で表示
rec = cv2.imread(filename, cv2.IMREAD_COLOR)
cv2.rectangle(rec, (R1[0],R1[1]), (R3[0],R3[1]), (0, 0, 255), 3)
cv2.imshow('rectangle', rec)
# それぞれの座標をnumpyのarrayへ
src = np.array([Q1,Q2,Q3,Q4], np.float32)
dst = np.array([R1,R2,R3,R4], np.float32)
print src
print dst
# Perspective Correction
# 透視変換の行列を求める
transmtx = cv2.getPerspectiveTransform(src,dst)
offsetSize = int(250)
# 変換行列を用いて画像の透視変換
warp = cv2.warpPerspective(img, transmtx, (newRecWidth+offsetSize, newRecHeihgt+offsetSize))
# 変換後の画像表示
cv2.imshow('warp', warp)
# 画像を保存
cv2.imwrite('warp.jpg', warp)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment