【发布时间】:2021-05-19 00:59:19
【问题描述】:
我正在使用 pytessearct 从图像中提取文本。但它不适用于倾斜的图像。考虑下面给出的图像:
这是提取文本的代码,它在不倾斜的图像上运行良好。
img = cv2.imread(<path_to_image>)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5),0)
ret3, thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
def findSignificantContours (img, edgeImg):
contours, heirarchy = cv2.findContours(edgeImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# Find level 1 contours
level1 = []
for i, tupl in enumerate(heirarchy[0]):
# Each array is in format (Next, Prev, First child, Parent)
# Filter the ones without parent
if tupl[3] == -1:
tupl = np.insert(tupl, 0, [i])
level1.append(tupl)
significant = []
tooSmall = edgeImg.size * 5 / 100 # If contour isn't covering 5% of total area of image then it probably is too small
for tupl in level1:
contour = contours[tupl[0]];
area = cv2.contourArea(contour)
if area > tooSmall:
significant.append([contour, area])
# Draw the contour on the original image
cv2.drawContours(img, [contour], 0, (0,255,0),2, cv2.LINE_AA, maxLevel=1)
significant.sort(key=lambda x: x[1])
#print ([x[1] for x in significant]);
mx = (0,0,0,0) # biggest bounding box so far
mx_area = 0
for cont in contours:
x,y,w,h = cv2.boundingRect(cont)
area = w*h
if area > mx_area:
mx = x,y,w,h
mx_area = area
x,y,w,h = mx
# Output to files
roi = img[y:y+h,x:x+w]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5),0)
ret3, thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2_imshow(thresh)
text = pytesseract.image_to_string(roi);
print(text); print("\n"); print(pytesseract.image_to_string(thresh));
print("\n")
return [x[0] for x in significant];
edgeImg_8u = np.asarray(thresh, np.uint8)
# Find contours
significant = findSignificantContours(img, edgeImg_8u)
mask = thresh.copy()
mask[mask > 0] = 0
cv2.fillPoly(mask, significant, 255)
# Invert mask
mask = np.logical_not(mask)
#Finally remove the background
img[mask] = 0;
Tesseract 无法从此图像中提取文本。有没有办法可以旋转它以完美对齐文本,然后将其提供给 pytesseract?如果我的问题需要更明确的说明,请告诉我。
【问题讨论】:
-
可以得到卡片的旋转矩形和角度。使用角度拉直旋转并将该图像输入 Tesseract。
-
是的,我找到了矩形和计数数组。如何从中形成矩形?如果你能给我一些建议,那就太好了。 @eldesgraciado
-
不是你想要的轮廓边界矩形。您需要使用 cv2.minAreaRect() 找到旋转的矩形,从中可以获得中心、宽度和高度以及旋转。您可以使用旋转来纠正您的图像。请参阅docs.opencv.org/4.1.1/d3/dc0/… 的文档。另见pyimagesearch.com/2017/02/20/text-skew-correction-opencv-python
标签: python opencv machine-learning image-processing computer-vision