【问题标题】:OpenCV fill missing pixelsOpenCV 填充缺失的像素
【发布时间】:2021-06-19 20:57:50
【问题描述】:

也许有人有想法,我们如何将白色数字上的黑色像素填充为白色,并使该图像更易于识别

我正在尝试内核大小 (1,1) 的 GaussianBlur,但它没有有效帮助,有时图像上的数字会合并,这是最糟糕的结果

【问题讨论】:

  • @ChristophRackwitz 像素填充好后,这个图像的轮廓就会很好地找到,然后我们可以使用 matchtemplate 函数来识别每个数字。希望清楚
  • 尝试形态闭合...docs.opencv.org/master/d9/d61/…
  • @mark-setchell 它可能会关闭附近的数字并破坏下一个轮廓搜索。但这是个主意,谢谢,会尝试

标签: opencv opencv-python opencv-contour gaussianblur matchtemplate


【解决方案1】:

您可以使用 MATLAB imfill 的等效项,但结果将是二进制图像。

我找到了 imfill here 的 Python 实现(它使用 Scikit-image)。

代码如下:

import cv2
import numpy as np
from skimage.morphology import reconstruction

def imfill(img):
    # https://stackoverflow.com/questions/36294025/python-equivalent-to-matlab-funciton-imfill-for-grayscale
    # Use the matlab reference Soille, P., Morphological Image Analysis: Principles and Applications, Springer-Verlag, 1999, pp. 208-209.
    #  6.3.7  Fillhole
    # The holes of a binary image correspond to the set of its regional minima which
    # are  not  connected  to  the image  border.  This  definition  holds  for  grey scale
    # images.  Hence,  filling  the holes of a  grey scale image comes down  to remove
    # all  minima  which  are  not  connected  to  the  image  border, or,  equivalently,
    # impose  the  set  of minima  which  are  connected  to  the  image  border.  The
    # marker image 1m  used  in  the morphological reconstruction by erosion is set
    # to the maximum image value except along its border where the values of the
    # original image are kept:

    seed = np.ones_like(img)*255
    img[ : ,0] = 0
    img[ : ,-1] = 0
    img[ 0 ,:] = 0
    img[ -1 ,:] = 0
    seed[ : ,0] = 0
    seed[ : ,-1] = 0
    seed[ 0 ,:] = 0
    seed[ -1 ,:] = 0

    fill_img = reconstruction(seed, img, method='erosion')

    return fill_img

img = cv2.imread('5375.jpg', cv2.IMREAD_GRAYSCALE)  # Read image as grayscale

img_thresh = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)[1]  # Convert to B/W

fill_img = imfill(img_thresh)

cv2.imshow('img', img)
cv2.imshow('fill_img', fill_img)
cv2.waitKey()
cv2.destroyAllWindows()

结果:

注意:
使用cv2.findContours 和drawContours 可能会得到相同的结果,但您应该在img_thresh 上应用findContours。


如果你想要更接近原始图像的结果,你可以使用关闭形态操作,并使用'fill_img'作为掩码:

closed_img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, np.ones((35, 35)))
closed_img[fill_img == 0] = 0  # Set to zero where fill_img is zero.

结果:

【讨论】:

  • 谢谢,会尝试并回复
猜你喜欢
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 2016-08-26
  • 1970-01-01
相关资源
最近更新 更多