图像处理中的平均滤波器

问题描述 投票:0回答:1

我需要一个使用平均滤波器使图像模糊的程序。它还必须使用不同的尺寸:3x3、5x5等。

这是我所拥有的:

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

image = cv2.imread('tranquility.jpg')

#blur = cv2.blur(image,(3,3))
width = image.shape[1]
height = image.shape[0]
result = np.zeros((image.shape[0], image.shape[1]), dtype='uint8')


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


plt.subplot(121),plt.imshow(image),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(result),plt.title('Blurred')
plt.xticks([]), plt.yticks([])
plt.show()

输出看起来像这样:

“

由于某种原因,原始图像是蓝色的,它应该具有正常的肤色。此外,模糊版本为纯紫色。如何修改代码,使其正常模糊图像。

附加信息:

  1. 我指的是这个主题:Averaging Filter using python;
  2. 实际上,使用这里的平均滤波器代码会使图像模糊,但是由于某种原因它是蓝色的。 OpenCV

更新:Original Image

python image-processing average cv2
1个回答
0
投票

您的原始图像看起来偏蓝,因为cv2.imread返回的图像具有以下三个通道的顺序:蓝色,绿色和红色。 plt.imshow适用于RGB图像,因此您需要转换原始数据:

bgr_image = cv2.imread(your_image_filename)
rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
plt.imshow(rgb_image)

如Romain所述,最好使用库而不是对过滤器进行编码。在您的特定情况下,cv2.blur确实可以满足您的需求:

# 3x3 mask
blurred_image3 = cv2.blur(bgr_image, (3, 3))
cv2.imwrite('blurred_image3.png', blurred_image3)

# 5x5 mask
blurred_image5 = cv2.blur(bgr_image, (5, 5))
cv2.imwrite('blurred_image5.png', blurred_image5)

掩码3x3的结果图像:

blurred image, mask 3x3

掩码5x5的结果图像:

blurred image, mask 5x5

© www.soinside.com 2019 - 2024. All rights reserved.