使用马尔可夫链将RGB图像转换为黑白(01)

2024-10-02 14:22:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力找到这个问题的答案,我不太了解马尔可夫链的使用,我想得到一些帮助:

[输入图像]https://i.stack.imgur.com/r9XCE.png

[输出图像示例]https://i.stack.imgur.com/3pllU.png

这就是我们开始的,经典

我只想把这张图像转换成黑白,但我必须使用马尔可夫链概率,我根本不懂

有人能给我一些提示吗? 我相信我们必须随机选取N个像素的时间,并应用somme Probama magic将其更改为黑色或白色(基于概率和邻居)

提前感谢(我不是专门搜索代码,而是要实现的逻辑)


Tags: 答案https图像com示例pngstack时间
1条回答
网友
1楼 · 发布于 2024-10-02 14:22:23

以下是使用马尔可夫链对图像进行二值化的一种方法:

假设(通过马尔可夫特性)像素值仅取决于其邻居(假设为4-nbd),假设其nbd像素中有n个为白色,则估计像素为白色的概率,即,对于4-nbd,首先计算其NBR中的p(x(i,j)=1 | n也为1)的条件概率,其中,对于4-nbd,n=0,1,2,3,4(另外,让我们使用全局阈值来计算概率,如以下代码所示,这可以看作是训练阶段):

from skimage.io import imread
im = imread('https://i.stack.imgur.com/r9XCE.png')

def count_nbrs(im, i, j, th): # counts number of nbd pixels are 1 given a pixel, with threshold th
    count = 0
    count += np.mean(im[i-1,j]) > th
    count += np.mean(im[i+1,j]) > th
    count += np.mean(im[i,j-1]) > th
    count += np.mean(im[i,j+1]) > th
    return count

th = 140 #np.mean(im) # a global threshold
nnbrs = 5 # use 4-nbd
freq = np.zeros(nnbrs)
tot = np.zeros(nnbrs)
h, w, _ = im.shape
for i in range(1, h-1):
   for j in range(1, w-1):
      count = count_nbrs(im, i, j, th)
      if np.mean(im[i,j]) > th:
         freq[count] += 1
      tot[count] += 1
prob = freq/tot 
print(prob)
# Prob(x(i,j)=1|n of its nbrs are 1) in the image, for n=0,1,2,3,4
# [0.00775595 0.09712838 0.48986784 0.91385768 0.99566323]

现在,让我们使用这些估计概率将彩色图像中的每个像素更改为黑白,具体取决于其nbd(这可以被认为是测试阶段):

h, w, _ = im.shape
im1 = np.zeros((h, w))
for i in range(1, h-1):
    for j in range(1, w-1):
        c = count_nbrs(im, i, j, th) # count number of neighbors with white pixel
        im1[i,j] = 255*(prob[c] > 0.5) # use Prob vector to determine value of the pixel
plt.imshow(im1, 'gray')
plt.show()

获得的二值图像的质量远远优于全局阈值(请查看)

enter image description here

您可以随机选择像素,并在给定1个NBR(阈值)的情况下计算像素值为1的概率,相应地设置像素值,使用以下代码进行大量迭代N,它将生成类似的二值图像

N = 100000
h, w, _ = im.shape
im1 = np.zeros((h, w))
for k in range(N):
    i = np.random.randint(1,h-1,1)[0]
    j = np.random.randint(1,w-1,1)[0]
    c = count_nbrs(im, i, j, th)
    im1[i,j] = 255*(prob[c] > 0.5) 
plt.imshow(im1, 'gray')
plt.show()

enter image description here

下一个动画显示如何使用上述代码生成二进制图像

enter image description here

相关问题 更多 >