使用python平均过滤器

问题描述:

我是python的新手,并尝试将平均过滤器应用于图像,这是我理解平均概念的方式

I am new in python and trying apply averaging filter on image as the way i understand averaging concept

总结包括自身在内的相邻元素,然后将其除以元素数量 技术

summing up the neighboring elements including itself and divide it by number of elements technique

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

But the problem is getting dark image rather then blur image as result

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()

我测试了您的代码,问题似乎出在此类型上!

I tested your code and the issue appears to be the type!

result的值为int,但应为uint8
您可以先正确填写它,也可以在显示之前重新铸造它,如下所示:

the values of result are int but they should be uint8
you can either fill it in correctly to begin with or recast it before displaying, like this:

result = result.astype('uint8')

为什么您要手动制作此过滤器?为什么不使用内置的模糊滤镜?您可能需要阅读

why are you making this filter manually though? why not use the built in blur filter? you may want to read this