我目前有一份需要智能扫描的文档。
为此,我需要在任何背景中找到文档的正确轮廓,以便我可以使用该图像进行扭曲的透视投影和检测。
这样做的主要问题是文档边缘检测到任何类型的背景。
我试图使用函数HoughLineP并尝试在通过canny边缘检测的灰度模糊图像上找到轮廓,直到现在。
MORPH = 9
CANNY = 84
HOUGH = 25
IM_HEIGHT, IM_WIDTH, _ = rescaled_image.shape
# convert the image to grayscale and blur it slightly
gray = cv2.cvtColor(rescaled_image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7,7), 0)
#dilate helps to remove potential holes between edge segments
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(MORPH,MORPH))
dilated = cv2.dilate(gray, kernel)
# find edges and mark them in the output map using the Canny algorithm
edged = cv2.Canny(dilated, 0, CANNY)
test_corners = self.get_corners(edged)
approx_contours = []
(_, cnts, hierarchy) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]
# loop over the contours
for c in cnts:
# approximate the contour
approx = cv2.approxPolyDP(c, 80, True)
if self.is_valid_contour(approx, IM_WIDTH, IM_HEIGHT):
approx_contours.append(approx)
break
如何通过OpenCV代码在文档周围找到合适的边界框。任何帮助都感激不尽。 (文档是从相机中以任何角度和任何彩色背景拍摄的。)
以下代码可能有助于您检测/分割图像中的页面...
import cv2
import matplotlib.pyplot as plt
import numpy as np
image = cv2.imread('test_p.jpg')
image = cv2.imread('test_p.jpg')
print(image.shape)
ori = image.copy()
image = cv2.resize(image, (image.shape[1]//10,image.shape[0]//10))
调整图像大小以使操作更快,以便我们可以实时工作。
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (11,11), 0)
edged = cv2.Canny(gray, 75, 200)
print("STEP 1: Edge Detection")
plt.imshow(edged)
plt.show()
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts[1], key = cv2.contourArea, reverse = True)[:5]
在这里,我们将仅考虑基于区域的排序列表中的前5个轮廓。这里高斯模糊的大小是比特敏感的,因此根据图像大小相应地选择它。完成上述操作后,图像可能会像..
for c in cnts:
### Approximating the contour
#Calculates a contour perimeter or a curve length
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.01 * peri, True)
# if our approximated contour has four points, then we
# can assume that we have found our screen
screenCnt = approx
if len(approx) == 4:
screenCnt = approx
break
# show the contour (outline)
print("STEP 2: Finding Boundary")
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
image_e = cv2.resize(image,(image.shape[1],image.shape[0]))
cv2.imwrite('image_edge.jpg',image_e)
plt.imshow(image_e)
plt.show()
最终图像可能看起来像......
在获得最终图像后,可以处理其余的事情......
代码参考: - Git Repository
我想这个答案会有所帮助......
存在类似的问题,称为正投影。
而不是做高斯模糊+形态操作来获取文档的边缘,首先尝试进行正交投影,然后通过您的方法找到轮廓。
要修整正确的边界框,请尝试使用某些预设值或参考字母,然后使用正交投影可以计算高度,从而计算边界框的尺寸。