4

When processing an image with text in OpenCV, my opening operation does not result in proper output data. The issue is quite similar to the one described in this article: http://www.cpe.eng.cmu.ac.th/wp-content/uploads/CPE752_06part2.pdf

Screenshot from PDF section

What I can see, people suggest to use reconstruction operations. Is there any build-in mechanism in OpenCV or some known library/code that implements this?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
user2957984
  • 225
  • 3
  • 6
  • morphological reconstruction is very simple to implement but it is time consuming. For complete reconstruction you have to use a structuring element with the size of 3x3, the original image, the processed image until there are no other changes. I have to search and I can put some code but is based on the opencv v1 – alinoz Apr 21 '15 at 14:37

2 Answers2

5

Here's my Python3 implementation in analogy to MatLab's imreconstruct algorithm:

import cv2
import numpy as np


def imreconstruct(marker: np.ndarray, mask: np.ndarray, radius: int = 1):
    """Iteratively expand the markers white keeping them limited by the mask during each iteration.

    :param marker: Grayscale image where initial seed is white on black background.
    :param mask: Grayscale mask where the valid area is white on black background.
    :param radius Can be increased to improve expansion speed while causing decreased isolation from nearby areas.
    :returns A copy of the last expansion.
    Written By Semnodime.
    """
    kernel = np.ones(shape=(radius * 2 + 1,) * 2, dtype=np.uint8)
    while True:
        expanded = cv2.dilate(src=marker, kernel=kernel)
        cv2.bitwise_and(src1=expanded, src2=mask, dst=expanded)

        # Termination criterion: Expansion didn't change the image at all
        if (marker == expanded).all():
            return expanded
        marker = expanded
Semnodime
  • 1,872
  • 1
  • 15
  • 24
2

This answer arrives late, but here is the basic algorithm for under-reconstruction:

  1. Inputs are two images: ImReference and ImMarker, with marker <= reference
  2. Intermediate image: ImRec
  3. Output image: ImResult
  4. Copy ImMarker into ImRec
  5. copy ImRec into ImResult
  6. ImDilated = Dilation(ImResult)
  7. ImRec = Minimum(ImDilated, ImReference)
  8. If ImRec != ImResult then return to step 5.

It's not the most optimal algorithm, but it uses only basic operations.

FiReTiTi
  • 5,597
  • 12
  • 30
  • 58