代码之家  ›  专栏  ›  技术社区  ›  Utonium

使用python平均化过滤器

  •  -2
  • Utonium  · 技术社区  · 7 年前

    我是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()
    
    1 回复  |  直到 7 年前
        1
  •  -1
  •   Nullman    7 年前

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

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

    result = result.astype('uint8')
    

    但为什么要手动创建此筛选器?为什么不使用内置模糊过滤器?您可能想阅读 this