【问题标题】:Averaging Filter using python使用python平均过滤器
【发布时间】:2018-03-29 10:20:30
【问题描述】:

我是 python 新手,并尝试在图像上应用平均滤波器作为我理解平均概念的方式

将包括自身在内的相邻元素相加,然后除以元素个数 technique

但问题是图像变暗而不是图像模糊

image = cv2.imread('./images/hip-salt.jpg', 0);
width = image.shape[1]
height = image.shape[0]
result = np.zeros((image.shape[0], image.shape[1]), int)

def meanFilter():
  for row in range(height):
     for col in range(width):  
         currentElement=0; left=0; right=0; top=0; bottom=0; topLeft=0; 
         topRight=0; bottomLeft=0; bottomRight=0;
         counter = 1           
         currentElement = image[row][col]

         if not col-1 < 0:
             left = image[row][col-1]
             counter +=1                        
         if not col+1 > width-1:
             right = image[row][col+1]
             counter +=1 
         if not row-1 < 0:
             top = image[row-1][col]
             counter +=1 
         if not row+1 > height-1:
             bottom = image[row+1][col]
             counter +=1 

         if not row-1 < 0 and not col-1 < 0:
             topLeft = image[row-1][col-1]
             counter +=1 
         if not row-1 < 0 and not col+1 > width-1:
             topRight = image[row-1][col+1]
             counter +=1 
         if not row+1 > height-1 and not col-1 < 0:
             bottomLeft = image[row+1][col-1]
             counter +=1 
         if not row+1 > height-1 and not col+1 > width-1:
             bottomRight = image[row+1][col+1]
             counter +=1

         total = int(currentElement)+int(left)+int(right)+int(top)+int(bottom)+int(topLeft)+int(topRight)+int(bottomLeft)+int(bottomRight)
         avg = total/counter
         result[row][col] = avg

meanFilter(); 
cv2.imshow('Averaging Filter', result);
cv2.waitKey(0)
cv2.destroyAllWindows()

【问题讨论】:

  • 需要注意的一点是,如果您使用的是 python 2,那么 total/counter 将返回一个截断的 int
  • 使用python 3,我实际上使用pyqt制作了一个gui应用程序进行图像处理
  • 你不能使用 cv2/numpy 函数来代替重新发明轮子吗?

标签: python numpy opencv image-processing


【解决方案1】:

我测试了你的代码,问题似乎是类型!

结果的值是int,但它们应该是uint8
您可以在开始时正确填写,也可以在显示之前重新填写,如下所示:

result = result.astype('uint8')

你为什么要手动制作这个过滤器?为什么不使用内置的模糊滤镜?您可能想阅读this

【讨论】:

  • result = np.zeros((image.shape[0], image.shape[1]), np.int8) 改变这条线给出了更好的结果,不是完全黑暗的图像,但也不需要图像(模糊图像)
  • result = np.zeros((image.shape[0], image.shape[1]), dtype='uint8') 应该是
猜你喜欢
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 2013-03-11
相关资源
最近更新 更多