python - wrapTransform后如何找到一个点?

标签 python opencv

我在 warpPerspective 之前在原始图像下找到了一组坐标/点,如何在经过透视校正的现在裁剪和校正图像中获得相应的点?

例如:

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

img = cv.imread('sudoku.png')
rows,cols,ch = img.shape
pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])

point = np.array([[10,10]])

M = cv.getPerspectiveTransform(pts1,pts2)
dst = cv.warpPerspective(img,M,(300,300))

plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')

如何将 img map 中的新坐标 [10,10] 获取到 dst 图像?

最佳答案

您必须执行与对图像所做的相同的转换(数学上的)。在这种情况下,这意味着使用 cv2.perspectiveTransform (请注意,输入需要每个点有 1 行、1 列和 2 个 channel ——第一个是 X,第二个是 Y 坐标)。

此函数将转换所有输入点,它不执行和裁剪。您将需要对变换后的坐标进行后处理,并丢弃落在裁剪区域之外的坐标。在您的情况下,您希望保留点 (0 <= x < 300) and (0 <= y < 300) .


示例代码:

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

img = cv.imread('sudoku.png')
rows,cols,ch = img.shape
pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])

points = np.float32([[[10, 10]], [[116,128]], [[254,261]]])

M = cv.getPerspectiveTransform(pts1,pts2)
dst = cv.warpPerspective(img,M,(300,300))

# Transform the points
transformed = cv.perspectiveTransform(points, M)

# Perform the cropping -- filter out points that are outside the crop area
cropped = []
for pt in transformed:
    x, y = pt[0]
    if x >= 0 and x < dst.shape[1] and y >= 0 and y < dst.shape[0]:
        print "Valid point (%d, %d)" % (x, y)
        cropped.append([[x,y]])
    else:
        print "Out-of-bounds point (%d, %d)" % (x, y)

# Turn it back into a single numpy array
cropped = np.hstack(cropped)

# Visualize
plt.subplot(121)
plt.imshow(img)
for pt in points:
    x, y = pt[0]
    plt.scatter(x, y, s=100, c='red', marker='x')

plt.title('Input')

plt.subplot(122)
plt.imshow(dst)
for pt in transformed:
    x, y = pt[0]
    plt.scatter(x, y, s=100, c='red', marker='x')

plt.title('Output')

plt.show()

控制台输出:

Out-of-bounds point (-53, -63)
Valid point (63, 67)
Valid point (192, 194)

可视化:

Visualization

关于python - wrapTransform后如何找到一个点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52653346/

相关文章:

python - 如何选择类别页面作为 Pelican 站点的主页?

c++ - Opencv:创建黑色窗口并向其写入文本

opencv - OpenCV中如何生成二进制描述符?

python - OpenCV:利用命令行进行人脸检测

python - 给定两个列表、单词和定义。我们需要创建一个名为 Cooldictionary 的字典,其中我们使用单词作为键,使用定义作为值

python - 将数据从一个 Pandas 数据框替换为另一个

python - 获取一个国家的天气,地点 bs4

python - 如何使用霍夫变换查找图像中的行数?

opencv - 谷歌测量应用程序如何在Android上运行?

Python PATH 中特殊字符编码问题