如何在 openCV 上获得 leptonica 的 pixReduceRankBinary2 和 pixCloseBrick 的相同结果?

how can I get the same result of leptonica's pixReduceRankBinary2 and pixCloseBrick on openCV?

我正在将一个使用 leptonica 库的 go 程序翻译成一个使用 openCV 的 python 脚本,但我找不到翻译以下内容的方法:

img = pixReduceRankBinary2(img, 2, NULL);
img = pixReduceRankBinary2(img, 2, NULL);
img = pixCloseBrick(NULL, img, 2, 3);

openCV 中是否有这些函数的实现?

这是使用 Python/OpenCV/Skimage 执行此操作的一种方法。只需读取图像并确保它是二进制的。使用 Skimage downscale_local_mean 使用 2x2 邻域按 2 进行下采样,生成两倍较小图像的因子,其值是 2x2 邻域的均值。然后再次以 25% 的增量阈值以对应于其 pixReduceRankBinary2 函数的 leptonica 计数。

输入(米粒):

import cv2
import numpy as np
import skimage.transform

# read image
img = cv2.imread('rice_bw.png')

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold to binary
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]

# decimate by factor of 2 to mean values in 2x2 regions
decimate = skimage.transform.downscale_local_mean(thresh, (2,2))

# set count to 1,2,3 or 4
count=2

# convert count to percent of 255 in increments of 25%
count_thresh = 255 * (25/100) * count

# threshold again
result = cv2.threshold(decimate, count_thresh, 255, cv2.THRESH_BINARY)[1]

# write result to disk
cv2.imwrite("rice_bw_binary_decimate.png", result)

# show result
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

count=2 的结果: