9-4Perspective.py

000: import cv2
001: import numpy as np
002:
003: def __main():
004: img = cv2.imread(‘20200905_163733.jpg’)
005:
006: img = getResize(img)
007: org = img.copy()
008: height, width, channel = img.shape
009:
010: # マス目四隅の座標を登録
011: pts1 = np.float32([[388, 174], [943, 170], [243, 717], [1068, 720]])
012: color = (255, 0, 0)
013: # オリジナル画像に確認用でとしてマーカーを付ける
014: for i, pos in enumerate(pts1):
015: cv2.circle(img=org, center=(pos[0], pos[1]), radius=5, color=color, thickness=-1, lineType=cv2.LINE_AA)
016:
017: # 変換後のマス目四隅の座標を登録
018: pts2 = np.float32([[100, 100], [720, 100], [100, 960], [720, 960]])
019:
020: M = cv2.getPerspectiveTransform(src=pts1, dst=pts2)
021: # ここで処理を実行
022: dst = cv2.warpPerspective(src=img, M=M, dsize=(width, height))
023:
024: cv2.imshow(‘Original’, org)
025: cv2.imshow(‘Final result’, dst)
026: cv2.waitKey(0)
027: cv2.destroyAllWindows()
028:
029: def getResize(src):
030: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
031: height = src.shape[0]
032: width = src.shape[1]
033:
034: largeSize = max(height, width) # 大きい方の辺のサイズ
035: resizeRate = basePixSize / largeSize # 変更比率を計算
036:
037: dst = cv2.resize(src, (int(width * resizeRate), int(height * resizeRate)), interpolation=None)
038:
039: return dst
040:
041: if __name__ == ‘__main__’:
042: print(cv2.__version__)
043:
044: __main()