使用Python和OpenCV矫正图像

6

有没有办法使用Python中的OpenCV来使这张图片变直?我尝试使用不同的转换方式,但是无法实现。

Image

这是我的代码:

rows, cols, h = img.shape

M = np.float32([[1, 0, 100], [0, 1, 50]])

然后我应用仿射变换。

dst = cv2.warpAffine(roi, M, (cols, rows))

我仍然无法获得期望的图像矫正输出。现在已经纠结了将近一个小时。有人可以帮我吗?


只有知道旋转角度或者矩形边框的顶点位置,才能实现这一操作。 - ZdaR
什么是边界点? - rbo13
粉色的框限制了你书的边界。 - ZdaR
1
@ZdaR 我会根据粉色框进行调整? - rbo13
1个回答

10

你还记得 我之前的帖子 吗?这个答案是基于那个帖子的。

因此,我获得了围绕书籍的边界框的4个角点,并将其输入到单应性函数中。

代码:

#---- 4 corner points of the bounding box
pts_src = np.array([[17.0,0.0], [77.0,5.0], [0.0, 552.0],[53.0, 552.0]])

#---- 4 corner points of the black image you want to impose it on
pts_dst = np.array([[0.0,0.0],[77.0, 0.0],[ 0.0,552.0],[77.0, 552.0]])

#---- forming the black image of specific size
im_dst = np.zeros((552, 77, 3), np.uint8)

#---- Framing the homography matrix
h, status = cv2.findHomography(pts_src, pts_dst)
 
#---- transforming the image bound in the rectangle to straighten
im_out = cv2.warpPerspective(im, h, (im_dst.shape[1],im_dst.shape[0]))
cv2.imwrite("im_out.jpg", im_out)

enter image description here

既然你已经拿到了书籍周围的轮廓边界框,那么你需要将这4个点放入数组pts_src中。


啊哈,好的...从未想过我可以在这种情况下应用它。谢了老铁。只有一个问题,你是怎么得到这个值的?pts_src = np.array([[17.0,0.0], [77.0,5.0], [0.0, 552.0],[53.0, 552.0]])pts_dst = np.array([[0.0,0.0],[77.0, 0.0],[ 0.0,552.0],[77.0, 552.0]])im_dst = np.zeros((552, 77, 3), np.uint8) - rbo13
我该如何从我的轮廓中获取点?因为当我打印它时,它返回一个集合。我不知道从哪里开始。希望你能给我建议。非常感谢。 - rbo13
你是如何找到并绘制轮廓的?在找到轮廓后,应用以下代码进行轮廓处理:rect = cv2.minAreaRect(cnt)box = cv2.boxPoints(rect)box = np.int0(box)。四个角落都会在box里面。更多信息请查看此文档 - Jeru Luke
嗨@JeruLuke。我将在cv2.findHomography()中提供“box”吗?这是我目前的进展链接 - rbo13
@whaangbuu 我看到了你的程式碼。你沒有使用 邊界框(bounding box) 屬性。請訪問 此頁面 上的邊緣矩形。它會在你的輪廓周圍創建一個矩形。該矩形包含輪廓的點。你可以將這些點插入代碼中的 pts_dst 中 :D - Jeru Luke
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接