python - 使用 OpenCV/Numpy 展平图像背景

标签 python image opencv numpy

我正在创建一个图像分析工具(使用 Python)。 我已经有了 Otsu 阈值处理产生的分割图像。 使用 OpenCv kmeans 函数,我将图像中的颜色数量减少到 4。 K-means 集群之一应该是黑色背景(BGR 值 [0,0,0] )。

由于 K-means 算法,背景像素现在不是 [0,0,0],而是显示像素值,例如[0,2,1].

我希望这个背景簇再次变成绝对黑色。图像表示为 3D numpy 数组。目前我只是在反复调整背景:

    X, Y, Z = img.shape
    for xi in xrange(X):
        for yi in xrange(Y):
            if all([value < 10 for value in img[xi][yi]]): 
                img[xi][yi] = np.zeros((1,3), dtype=int)

这是一个相对较慢的操作。是否有更智能的方法来做到这一点,可能使用专门的 OpenCV/Numpy 函数?

最佳答案

你可以像这样向量化这个操作:

In [29]: A = np.random.random_integers(0,10,(2,4,3))

In [30]: A
Out[30]: 
array([[[ 5,  9,  1],
        [ 4,  0,  2],
        [ 0,  5,  9],
        [ 8,  7,  8]],

       [[ 1,  6,  7],
        [ 8, 10,  9],
        [ 2, 10,  1],
        [ 9,  2,  3]]])

In [32]: np.all(A < 5, axis=-1)  # I chose a threshold of 5
Out[32]: 
array([[False,  True, False, False],
       [False, False, False, False]], dtype=bool)

In [33]: A[np.all(A < 5, axis=-1)] = 100  # and set the values to 100 to easily show what has changed

In [34]: A
Out[34]: 
array([[[  5,   9,   1],
        [100, 100, 100],
        [  0,   5,   9],
        [  8,   7,   8]],

       [[  1,   6,   7],
        [  8,  10,   9],
        [  2,  10,   1],
        [  9,   2,   3]]])

通过指定 np.all(some_array, axis=-1),您将在最后一个轴上执行 all 操作,这是 RGB 值所在的位置。您会看到,在此测试数组中,只有一个这样的像素(位于 A[0,1])满足该条件。

关于python - 使用 OpenCV/Numpy 展平图像背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28319530/

相关文章:

python - 在 Windows 上安装 curses .whl 包

python - pytext 中的 Dict[str, Any] 或 Dict[str, Field]

html - 如何在 <ion-img> 上设置高度

python - 我如何知道在 python 中使用 OpenCV 检测到的白色区域的位置?

c++ - 对比 openCV 拉伸(stretch)图像

c++ - 提高特定任务的 tesseract 性能

python - 属性错误: 'Model' object has no attribute '_name' during input layer concatenation

python - AWS Elastic Beanstalk CLI 使用错误的 Python 版本

image - 写入超过 256 个标签的图像

javascript - 如何在单击按钮时加载图像?