如何提取覆盖矩形区域的图像中的数字

How to extract digit in image that overide rect area

现在,我有一个使用图像处理检测数字的项目,但我不知道如何在数字覆盖矩形区域时提取。

这是输入:

我想得到类似底部图片的东西:

可以使用轮廓的概念使用 OpenCV 提取数字。以下实现在Python.

完成以下步骤:

  • 将图像转换为灰度图像
  • 应用适当的阈值,使数字为白色,而其他所有内容为黑色。
  • 现在找到等高线。因为你有小星星,它们也会被拾起。为避免捡起它们,请通过一个合适的区域,必须在该区域上方找到等高线。
  • 计算每个轮廓的凸包并在原始图像上屏蔽它们。

提取轮廓后,您需要处理单个凸包。

代码:

img = cv2.imread(r'C:\Users\Jackson\Desktop_new.jpg', 1)
img2 = img.copy()
cv2.imshow("original.jpg", img)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

_, threshed_img = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(threshed_img, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

#--- Black image to be used to draw individual convex hull ---
black = np.zeros_like(img)
#cv2.imshow("black.jpg", black)

contours = sorted(contours, key=lambda ctr: cv2.boundingRect(ctr)[0]) #added by OP : this sorts contours left to right, so images come in order

for cnt in contours:
    if cv2.contourArea(cnt) > 200:
        hull = cv2.convexHull(cnt)

        black2 = black.copy()

        #--- Here is where I am filling the contour after finding the convex hull ---
        cv2.drawContours(black2, [hull], -1, (255, 255, 255), -1)
        g2 = cv2.cvtColor(black2, cv2.COLOR_BGR2GRAY)
        _, t2 = cv2.threshold(g2, 127, 255, cv2.THRESH_BINARY)
        cv2.imshow("t2.jpg", t2)

        masked = cv2.bitwise_and(img2, img2, mask = t2)    
        cv2.imshow("masked.jpg", masked)

        print(len(hull))
        cv2.waitKey(0)

cv2.destroyAllWindows()

您应该能够得到如下内容: