在 Python 中使用 openCV 边界框算法检测数字

Detect digits with the openCV Bounding Box algorithm in Python

我正在开发一个可以识别多个数字的软件。为了裁剪图像的数字,我使用的是 openCV。我遇到的问题是边界框算法不仅检测数字。它也在检测数字中的结构。

解决此问题的最简单方法是设置结构必须具有的最小大小。这不起作用,因为我必须检测任何大小的数字。 有人有解决这个问题的想法吗?

这是代码:

im = cv2.imread('img.jpg')
    gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    contours,hierarchy = cv2.findContours(gray,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
    idx = 0
    for cnt in contours:

            xe,ye,we,he = cv2.boundingRect(cnt)
            roi=im[ye-100:ye+he+100,xe-100:xe+we+100]

            if xe > 30:
                    if ye > 30:
                            if he > 30:
                                    if we > 30:
                                            idx += 1
                                            cv2.imwrite(str(idx) + '.jpg', roi)
                                            cv2.rectangle(im,(xe,ye),(xe+we,ye+he),(200,0,0),2)


                                            cv2.imwrite('dev.jpg', im)

根据documentation

您可以通过将参数 cv2.RETR_LIST 更改为 cv2.RETR_EXTERNAL

来将 findContours 方法的模式更改为仅 return 最外层轮廓

Contour retrieval mode (if you use Python see also a note below).

  • CV_RETR_EXTERNAL retrieves only the extreme outer contours. It sets hierarchy[i][2]=hierarchy[i][3]=-1 for all the contours.

  • CV_RETR_LIST retrieves all of the contours without establishing any hierarchical relationships.

  • CV_RETR_CCOMP retrieves all of the contours and organizes them into a two-level hierarchy. At the top level, there are external boundaries of the components. At the second level, there are boundaries of the holes. If there is another contour inside a hole of a connected component, it is still put at the top level.

  • CV_RETR_TREE retrieves all of the contours and reconstructs a full hierarchy of nested contours. This full hierarchy is built and shown
    in the OpenCV contours.c demo.