如何在python中显示中值灰度图像?

时间:2016-02-10 16:13:16

标签: python opencv image-processing

我有一个图像,我在图像中找到5 * 5块的中位数和偏差,并将其保存到图像中。现在,当我显示结果时,它们是原始图像的掩模,而它不应该如此。它应该向我显示灰度级的模糊图像而不是黑白!!你知道我犯了什么错吗?

这是我的代码:

img = cv2.imread('M.png', 0)

win = 5   # block window
height, width = img.shape   

MedianOfBlock = []   
DeviationOfBlock = []

for i in range(0, (height-2*win)):
    MedianOfBlock.append([])
    DeviationOfBlock.append([])
    for j in range(0, (width- 2*win)):
       block = np.array(img[i:i+win, j:j+win])

      # Compute the median in each window
      MedianOfBlock[i].append(np.median(block))

      # Compute the standard deviation in each window
DeviationOfBlock[i].append(FindDeviation(block,MedianOfBlock[i][j],  win))

DeviationOfBlock2 = np.array(DeviationOfBlock)
MedianOfBlock2 = np.array(MedianOfBlock)
cv2.imshow('OriginalImage',img)
cv2.waitKey()
cv2.imshow('MedianImage',MedianOfBlock2 )
cv2.waitKey()
cv2.imshow('DeviationOfBlock',DeviationOfBlock2 )
cv2.waitKey()

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我认为你正在尝试进行图像过滤,这个过程是通过内核卷积完成的,Opencv模块有一个名为cv2.filter2D的函数。您可以使用使用平均内核的中值内核进行图像过滤。

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

   img = cv2.imread('opencv_logo.png')

   kernel = np.ones((5,5),np.float32)/25
   dst = cv2.filter2D(img,-1,kernel)

   plt.subplot(121),plt.imshow(img),plt.title('Original')
   plt.xticks([]), plt.yticks([])
   plt.subplot(122),plt.imshow(dst),plt.title('Averaging')
   plt.xticks([]), plt.yticks([])
   plt.show()  

Obs:如果你没有matplotlib模块,只需安装它或使用Opencv的默认绘图功能

请检查documentation