hiii
Im searching for a method or an algorithm that can help me
in finding number of holes in an image

this image is basically for a letter like "D" "B"
--->number of holes can distinguish between those letters..

this will help me alot in my project if it works
any suggestion .. i would appreciate it
thanks ..

Dani AI

Generated

asked for a way to detect closed curves (holes) in a character image and pointed to reference material. Below are concise, practical approaches you can apply immediately, with a short OpenCV/Python example that counts holes per connected character.

Three reliable approaches

  • Contour hierarchy: use cv2.findContours with RETR_CCOMP/RETR_TREE. Child contours of an object are its holes. This gives per-object hole counts and bounding boxes.
  • Flood-fill + connected components: flood-fill the external background, invert the result; the remaining white regions are holes. Good for a fast global hole count.
  • Topological (Euler number): Euler = objects − holes; libraries like scikit-image expose this if you want a single topological measure.

Example (OpenCV/Python)

import cv2
import numpy as np

def to_binary(gray):
    # returns binary image with object=255, background=0 (adjust if needed)
    _, th = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    return th

def holes_by_contours(bin_img, min_area=20):
    cnts = cv2.findContours(bin_img.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    contours = cnts[0] if len(cnts) == 2 else cnts[1]
    hierarchy = cnts[-1]
    hole_counts = {}
    if hierarchy is None:
        return []
    for i, h in enumerate(hierarchy[0]):
        parent = h[3]
        if parent != -1 and cv2.contourArea(contours[i]) >= min_area:
            hole_counts[parent] = hole_counts.get(parent, 0) + 1
    results = []
    for i, cnt in enumerate(contours):
        if hierarchy[0][i][3] == -1:
            results.append({'bbox': cv2.boundingRect(cnt), 'holes': hole_counts.get(i, 0)})
    return results

def holes_by_floodfill(bin_img):
    im_ff = bin_img.copy()
    h, w = bin_img.shape[:2]
    mask = np.zeros((h+2, w+2), np.uint8)
    cv2.floodFill(im_ff, mask, (0,0), 255)
    holes_img = cv2.bitwise_not(im_ff)
    n_labels, _ = cv2.connectedComponents(holes_img)
    return max(0, n_labels - 1)

Troubleshooting notes

  • Ensure correct binarization: Otsu or adaptive threshold after gentle blur works well for noisy/antialiased scans.
  • Use morphological closing to seal thin gaps that would break a hole. Choose kernel size by image DPI.
  • Filter tiny contour areas to ignore specks.
  • For multi-component characters or nested holes, contour-hierarchy gives the cleanest per-character counts.

These methods are fast, robust, and cover most handwritten or printed-letter cases.

Recommended Answers

All 3 Replies

Just look at the 2nd reply and see how they implement OCR...

Thanks Ramy,,
I looked to the link ,, it is really useful
but im implementing these steps but with different algorithms
for classification..

so that again im asking the same question
but in another way...

how can we detect the existence of closed curve in an image
any help would be appreciated

Sorry Dima I didn't make it before but I'm trying to help I search and I found this book Mathematical Tools in Computer Graphics with C# Implementations By Alexandre Hardy, Willi-Hans Steeb and I think it has the answer can you please take a look on http://books.google.com.eg/books?id=IGtIWmM2GWIC&pg=PA164&lpg=PA164&dq=detect+closed+curve+in+an+image+C%23&source=bl&ots=eBFYLo3g6L&sig=curnJy8dZ-t9GJ-3plt7PrLhoT0&hl=en&ei=NtGvSuuMOdzLjAes_tnABA&sa=X&oi=book_result&ct=result&resnum=7#v=onepage&q=&f=false

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.