位图分割的Python实现

最近重温了一下位图分割的相关内容,发现网络上位图分割原理讲得已经很清楚了,但是代码多为C++实现或者Matlab实现,因为需要Python的版本,于是出现了这篇博客。
想要了解位图分割的原理的读者,可以参考下面这篇博客。

https://www.cnblogs.com/qinguoyi/p/7601179.html

话不多说,直接来代码。

import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('Fig3.13.jpg', 0)
imgBS = np.zeros_like(img)

plt.figure("Image")
plt.subplot(2, 4, 1)
plt.imshow(img, cmap='gray')
plt.axis('off')
plt.title('original')

for n in range(1, 8):
    for x in range(img.shape[0]):
        for y in range(img.shape[1]):
            gray = img[x, y] & pow(2, n-1)
            if gray == pow(2, n-1):
                imgBS[x, y] = 255
            else:
                imgBS[x, y] = 0

    plt.subplot(2, 4, n+1)
    plt.imshow(imgBS, cmap='gray')

    plt.axis('off')
    plt.title(str(n) + 'bit')
plt.show()

原始图像
结果:
结果

猜你喜欢

转载自blog.csdn.net/Test_Duriel/article/details/121404624