【发布时间】:2022-02-25 00:02:15
【问题描述】:
我为检测和纠正偏斜而生成的代码给了我不一致的结果。我目前正在开展一个项目,该项目利用图像上的 OCR 文本提取(通过 Python 和 OpenCV),因此如果需要准确的结果,消除偏斜是关键。我的代码使用cv2.minAreaRect 来检测歪斜。
我使用的图像都是相同的(将来也会如此),所以我不确定是什么导致了这些不一致。我在其中应用了我的代码时包含了两组前后图像(包括来自cv2.minAreaRect 的偏斜值),其中一组显示成功移除偏斜并且未移除偏斜(看起来它增加了更多偏斜)。
图片 1 之前 (-87.88721466064453)
图像 1 之后(成功的纠偏)
图片 2 之前 (-5.766754150390625)
图像 2 之后(不成功的纠偏)
我的代码如下。注意:我使用的图像比此处包含的图像要多得多。到目前为止,检测到的偏差一直在 [-10, 0) 或 (-90, -80] 范围内,因此我试图在我的代码中考虑这一点。
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_gray = cv2.bitwise_not(img_gray)
thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
coords = np.column_stack(np.where(thresh > 0))
angle = cv2.minAreaRect(coords)[-1]
if (angle < 0 and angle >= -10):
angle = -angle #this was intended to undo skew for values in [-10, 0) by simply rotating using the opposite sign
else:
angle = (90 + angle)/2
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
deskewed = cv2.warpAffine(img, M, (w, h), flags = cv2.INTER_CUBIC, borderMode = cv2.BORDER_REPLICATE)
我浏览了各种帖子和文章以找到适当的解决方案,但没有成功。 This post 对理解偏差值最有帮助,但即便如此我也无法走得太远。
【问题讨论】:
-
参见pyimagesearch.com/2017/02/20/text-skew-correction-opencv-python,尤其是他们如何校正 minAreaRect 角度
标签: python opencv image-processing skew