-1

ich have a script to transform and warp an Image with open cv. unfortunatel i get an error. It seems that cv2.warpPerspective cannot read the image. Do have an idea to solve the issue? You will find the code here:

import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.ion()


img = cv2.imread('path to jpeg')

img_copy = np.copy(img)


img_copy = cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB)
plt.imshow(img_copy)

pt_A =[162,83]
pt_B = [68,324]
pt_C = [542,324]
pt_D = [405,83]


width_AD = np.sqrt(((pt_A[0] - pt_D[0]) ** 2) + ((pt_A[1] - pt_D[1]) ** 2))
width_BC = np.sqrt(((pt_B[0] - pt_C[0]) ** 2) + ((pt_B[1] - pt_C[1]) ** 2))
maxWidth = max(int(width_AD), int(width_BC))

height_AB = np.sqrt(((pt_A[0] - pt_B[0]) ** 2) + ((pt_A[1] - pt_B[1]) **2))
height_CD = np.sqrt(((pt_C[0] - pt_D[0]) ** 2) + ((pt_C[1] - pt_D[1]) **2))
maxHeight = max(int(height_AB), int(height_CD))

input_pts = np.float32([pt_A, pt_B, pt_C, pt_D])
output_pts = np.float32([[0,0],[0,maxHeight -1],[maxWidth -1, maxHeight -1], [maxWidth -1, 0]])

M = cv2.perspectiveTransform(input_pts, output_pts)

out = cv2.warpPerspective(img,M,(maxWidth,maxHeight),flags=cv2.INTER_LINEAR)`

the image i have used is attached. enter image description here thanks for your help! BR

I put cv2.waitkey() in the code without any success. It would be great to get an modified code solving the issue.

Padavan
  • 1
  • 1

1 Answers1

0

The solution below doesn't use matplotlib but seems to give the desired output. Note that your 4th point, pt_D, was slightly off so I adjusted it to match with the actual court last corner.

import cv2
import numpy as np

img = cv2.imread('./tennis_court.jpg')

pt_A =[162,83]
pt_B = [68,324]
pt_C = [542,324]
pt_D = [450,83]  #Your initial point [405,83] looked wrong

rect = np.array((pt_A, pt_B, pt_C, pt_D), dtype="float32")

width_AD = np.sqrt(((pt_A[0] - pt_D[0]) ** 2) + ((pt_A[1] - pt_D[1]) ** 2))
width_BC = np.sqrt(((pt_B[0] - pt_C[0]) ** 2) + ((pt_B[1] - pt_C[1]) ** 2))
maxWidth = max(int(width_AD), int(width_BC))

height_AB = np.sqrt(((pt_A[0] - pt_B[0]) ** 2) + ((pt_A[1] - pt_B[1]) **2))
height_CD = np.sqrt(((pt_C[0] - pt_D[0]) ** 2) + ((pt_C[1] - pt_D[1]) **2))
maxHeight = max(int(height_AB), int(height_CD))

dst = np.array(
    [[0, 0],[maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], 
    dtype = "float32")

M = cv2.getPerspectiveTransform(rect, dst)
out = cv2.warpPerspective(img, M, (maxWidth, maxHeight))

cv2.imshow('Original', img)
cv2.imshow('Result', out)
cv2.waitKey(0)

Result

Tiphel
  • 323
  • 1
  • 11