我正在尝试对一张图片进行平滑处理,通过遍历其像素,计算3x3补丁区域的平均值,然后将该平均值应用到此补丁中的所有9个像素。
代码:
import matplotlib.pyplot as plt
import numpy as np
import cv2 as cv
from PIL import Image
# 1. Load Image
name = 'ebay.png'
img = cv.imread(name) #import image
h, w = img.shape[:2]
# 2. Smooth with kernel size 3
for y in range(0, w, 3):
for x in range(0, h, 3):
px1 = img[x][y] #0/0
px2 = img[x][y+1] #0/1
px3 = img[x][y+2] #0/2
px4 = img[x+1][y] #1/0
px5 = img[x+1][y+1] #1/1
px6 = img[x+1][y+2] #1/2
px7 = img[x+2][y] #2/0
px8 = img[x+2][y+1] #2/1
px9 = img[x+2][y+2] #2/2
average = np.average(px1 + px2 + px3 + px4 + px5 + px6 + px7 + px8 + px9)
img[x][y] = average #0/0
img[x][y+1] = average #0/1
img[x][y+2] = average #0/2
img[x+1][y] = average #1/0
img[x+1][y+1] = average #1/1
img[x+1][y+2] = average #1/2
img[x+2][y] = average #2/0
img[x+2][y+1] = average #2/1
img[x+2][y+2] = average #2/2
# 3. Transform the resulting image into pgm format and save result
new_image = Image.fromarray(img)
new_image.save('new.png')
# 4. Show image
new_image.show()
However this just makes my new image just very pixely and not smooth at all.
我觉得我在这里做错了什么:
average = np.average(px1 + px2 + px3 + px4 + px5 + px6 + px7 + px8 + px9)
由于我现在只使用px5作为平均值,所以新图像看起来更好(但仍然不是非常流畅)。请查看下面的图像:
float(px1)
等应该解决问题。 - Cris Luengo