使用OpenCV的minAreaRect()方法去除MNIST数据集图像的倾斜

5

我使用了OpenCV的minAreaRect来矫正Mnist数字图像。对于大多数数字,它效果很好,但在某些情况下,它没有正确检测到minAreaRect,进而导致数字被进一步倾斜。

这是代码可以处理的图像:
输入图像: input
minAreaRect图像: minAreaRect
矫正后图像: deskew

但对于以下图像,代码并不起作用:
输入图像: input2 minAreaRect 图像: minarea 矫正后图像: deskewed

我想在这里提到,我确实使用了:#coords = np.column_stack(np.where(thresh>0)),但这根本没有起作用。 请建议使用OpenCV的minAreaRect(首选)函数来解决问题。 我已经测试了多张图片,我明白问题出在min Area Rectangle的形成上,在第二个例子中,很明显min Area Rectangle是不可见的(因为它穿过数字本身)。

以下是代码:

import numpy as np
import cv2

image=cv2.imread('MNIST/mnist_png/testing/9/73.png')#for 4##5032,6780 #8527,2436,1391
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)## for 9 problem with 4665,8998,73,7
gray=cv2.bitwise_not(gray)
Gblur=cv2.blur(gray,(5,5))
thresh=cv2.threshold(Gblur,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

#cv2.imshow("gray_thresh_blur",thresh)

#Finding Contours will be used to draw the min area rectangle

 _,contours,_=cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
cnt1 = contours[0]
cnt=cv2.convexHull(contours[0])
angle = cv2.minAreaRect(cnt)[-1]
print("Actual angle is:"+str(angle))
rect = cv2.minAreaRect(cnt)

p=np.array(rect[1])
#print(p[0])
if p[0] < p[1]:
        print("Angle along the longer side:"+str(rect[-1] + 180))
        act_angle=rect[-1]+180
else:
        print("Angle along the longer side:"+str(rect[-1] + 90))
        act_angle=rect[-1]+90
#act_angle gives the angle with bounding box

if act_angle < 90:
        angle = (90 + angle)
        print("angleless than -45")

        # otherwise, just take the inverse of the angle to make
        # it positive
else:
        angle=act_angle-180
        print("grter than 90")

# rotate the image to deskew it
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image,M,(w,h),flags=cv2.INTER_CUBIC,borderMode=cv2.BORDER_REPLICATE)




box = cv2.boxPoints(rect)
print(box)
box = np.int0(box)
print(box)


p=cv2.drawContours(thresh,[box],0,(0,0,255),1)
print("contours"+str(p))
cv2.imwrite("post/MinAreaRect9.png",p)

cv2.imwrite("post/Input_9.png", image)
cv2.imwrite('post/Deskewed_9.png', rotated)

你能分享一个样例偏斜的图像和相应的期望输出吗? - ZdaR
是的,我只是在添加它。 - SolitaryReaper
1个回答

3

需要注意以下几点:

  • 大多数OpenCV函数使用白色前景和黑色背景。因此,请注释掉此行代码:

gray=cv2.bitwise_not(gray)

  • 确保计算字母的外部轮廓。这意味着您需要忽略所有子轮廓。为此,请使用cv2.RETR_EXTERNAL

contours=cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[1]

  • 最后,请确保分配正确的角度以查找旋转矩阵。

通过这些更改:

rs1 rs2


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