使用开放式透视变换

2024-05-19 10:54:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Python和opencv实现透视转换。当变换是通过在图像上选择4个点来完成的,输出图像是高度模糊的。即使我不使用鼠标事件来选择4个点(相当硬编码),图像质量仍然是模糊的。这里我的计划尝试是:

`def draw_circle(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img, (x, y), 5, (255, 0, 0), -1)
        p = (x, y)
        l.append(p)
        print(l)

cv2.namedWindow('image', cv2.WINDOW_NORMAL)
img = cv2.imread('Path  to my input image')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
cv2.resizeWindow('image', 600, 600)

cv2.setMouseCallback('image', draw_circle)

while 1:
    cv2.imshow('image', img)
    if cv2.waitKey(20) & 0xFF == 27:
        break
cv2.destroyAllWindows()

rows, cols, channels = img.shape
pts1 = np.float32(l)
pts2 = np.float32([[0, 0], [200, 0], [200, 100], [0, 100]])

M = cv2.getPerspectiveTransform(pts1, pts2)
dst = cv2.warpPerspective(img, M, (200, 100), cv2.INTER_LINEAR)

h1 = math.sqrt((abs(pts1[1][0] - pts1[0][0])) ** 2 + (abs(pts1[1][1] - pts1[0][1])) ** 2)
h2 = math.sqrt((abs(pts1[3][0] - pts1[2][0])) ** 2 + (abs(pts1[3][1] - pts1[2][1])) ** 2)
v1 = math.sqrt((abs(pts1[3][0] - pts1[0][0])) ** 2 + (abs(pts1[3][1] - pts1[0][1])) ** 2)
v2 = math.sqrt((abs(pts1[2][0] - pts1[1][0])) ** 2 + (abs(pts1[2][1] - pts1[1][1])) ** 2)
max_h = int(max(h1, h2))
max_v = int(max(v1, v2))


dst = cv2.resize(dst, (max_h, max_v))
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(dst), plt.title('Output')
plt.show()`

这是我的输入图像:这是一个带有选择性饮料的冰箱图像

screen shot

这是我的输出图像:这是透视变换后的输出图像

screen shot


Tags: 图像imageeventimgpltmathabssqrt
1条回答
网友
1楼 · 发布于 2024-05-19 10:54:54

在代码中替换此行

pts2 = np.float32([[0, 0], [200, 0], [200, 100], [0, 100]])

对于这个(也许您必须切换v/h顺序,我不知道python语法):

^{pr2}$

通过将max_h/max_v计算移动到变换计算之前。然后删除调整大小的代码。在

目前,您首先(隐式地)调整为100x200的临时图像,如果随后将其调整为更大的图像,则会非常模糊。在

相关问题 更多 >

    热门问题