PIL Quad transform to OpenCV transform

Viewed 280

I have a piece of Quad transformation (mapping from quadrilateral points to a rectangle) which I am trying to re-write it in OpenCV-Python, The problem is that PIL is not clear in this function, thus I am not able to get the same output from both

Here is the PIL version I am converting from:

# PIL 
img_cv=cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)
img_pil = Image.fromarray(np.array(img_cv))
(w,h) = img_pil.size
# in PIL we have order t-l b-l b-r t-r
quad = np.array([(100,80),(0,h//2),(w//2,h//2),(w//2,0)])
img_pil = img_pil.transform((w, h), PIL.Image.QUAD, quad.flatten(),PIL.Image.BILINEAR)
img_pil.save('output_pil.jpg')

and this is the OpenCV equivalent which I cannot figure

img_cv=cv2.imread(image_file)
(h,w,_) = img_cv.shape
# in opencv we have order t-l t-r b-r b-l
quad = np.array([(100,80),(w//2,0),(w//2,h//2),(0,h//2)],np.float32)

target = np.array([[0,0],[w,0],[w,h],[0,h]],np.float32)
#H, _ = cv2.findHomography(target,quad, params=None)
H = cv2.getPerspectiveTransform(quad,target)
transformed_image = cv2.warpPerspective(img_cv, H, (w, h), cv2.INTER_LINEAR)
cv2.imwrite('output_cv.jpg', transformed_image)

Here is the reference Image I am testing with

enter image description here

This is the result from PIL code

enter image description here

and this is the result from the openCV code

enter image description here

I am not sure where the problem is, as far as I can understand from the PIL quad transform, it maps between arbitrary quad points to rectangle points. And I think OpenCV code does the same, but totally different result. What is wrong? and what is the opencv equivalent? Thanks in advance

0 Answers
Related