問題描述
我這里有 2 張測試圖片.我的問題是,如何在不裁剪圖像的情況下將第一張圖像中的正方形映射到第二張圖像中的四邊形.
I have 2 test images here. My is question is, how to map the square in first image to the quadrilateral in the second image without cropping the image.
圖 1:
圖 2:
這是我當前使用 openCV warpPerspective 函數的代碼.
Here is my current code using openCV warpPerspective function.
import cv2
import numpy as np
img1_square_corners = np.float32([[253,211], [563,211], [563,519],[253,519]])
img2_quad_corners = np.float32([[234,197], [520,169], [715,483], [81,472]])
h, mask = cv2.findHomography(img1_square_corners, img2_quad_corners)
im = cv2.imread("image1.png")
out = cv2.warpPerspective(im, h, (800,800))
cv2.imwrite("result.png", out)
結果:
如您所見,由于 warpPerspective 函數中的 dsize=(800,800) 參數,我無法獲得圖像 1 的完整視圖.如果調整 dsize,正方形將無法正確映射.有沒有辦法調整輸出圖像的大小,以便我可以得到圖像 1 的全圖?
As you can see, because of dsize=(800,800) parameter in the warpPerspective function, I can't get full view of image 1. If I adjust the dsize, the square won't map properly. Is there any way to resize the output image so that I can get whole picture of image 1?
推薦答案
是的,但您應該意識到輸出圖像可能非常大.我很快編寫了以下 Python 代碼,但即使是 3000 x 3000 的圖像也無法適應輸出,由于轉換,它太大了.雖然,這是我的代碼,但我希望它對你有用.
Yes, but you should realise that the output image might be very large. I quickly wrote the following Python code, but even a 3000 x 3000 image could not fit the output, it is just way too big due to the transformation. Although, here is my code, I hope it will be of use to you.
import cv2
import numpy as np
import cv #the old cv interface
img1_square_corners = np.float32([[253,211], [563,211], [563,519],[253,519]])
img2_quad_corners = np.float32([[234,197], [520,169], [715,483], [81,472]])
h, mask = cv2.findHomography(img1_square_corners, img2_quad_corners)
im = cv2.imread("image1.png")
這里創建一個輸出圖像,我以 (3000, 3000) 為例.
Create an output image here, I used (3000, 3000) as an example.
out_2 = cv.fromarray(np.zeros((3000,3000,3),np.uint8))
通過使用舊的 cv
接口,我直接寫入輸出,因此不會被裁剪.我使用 cv2
接口嘗試了這個,但由于某種原因它不起作用......也許有人可以對此有所了解?
By using the old cv
interface, I wrote directly to the output, and so it does not get cropped. I tried this using the cv2
interface, but for some reason it did not work... Maybe someone can shed some light on that?
cv.WarpPerspective(cv.fromarray(im), out_2, cv.fromarray(h))
cv.ShowImage("test", out_2)
cv.SaveImage("result.png", out_2)
cv2.waitKey()
無論如何,這會給出一個非常大的圖像,其中包含您的原始圖像 1,變形.如果您指定輸出圖像足夠大,整個圖像將可見.(這可能確實很大!)
Anyway, this gives a very large image, that contains your original image 1, warped. The entire image will be visible if you specify the output image to be large enough. (Which might be very large indeed!)
我希望這段代碼可以幫助到你.
I hope that this code may help you.
這篇關于使用 OpenCV warpPerspective 時如何顯示整個圖像的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!