使用 OpenCV warpPerspective 时如何显示整个图像

时间:2022-11-11
本文介绍了使用 OpenCV warpPerspective 时如何显示整个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我这里有 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 时如何显示整个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:使用 python opencv 跟踪白色 下一篇:从图像中提取奶牛编号

相关文章

最新文章