Python中图像锐化的错误

b55*_*555 2 python image image-processing filter python-imaging-library

from PIL import Image
fp="C:\\lena.jpg"
img=Image.open(fp)
w,h=img.size
pixels=img.load()

imgsharp=Image.new(img.mode,img.size,color=0)
sharp=[0,-1,0,-1,8,-1,0,-1,0]

for i in range(w):
    for j in range(h):

        for k in range(3):
                for m in range(3):
                    l=pixels[i-k+1,j-m+1]*sharp[i]

        if l>255:
            l=255
        elif l<0:
            l=0
        imgsharp.putpixel((i,j),l)

imgsharp.show()
Run Code Online (Sandbox Code Playgroud)

我想将3x3蒙版大小的高通(锐化)滤镜应用于灰度图像。但我收到一个错误:

Traceback (most recent call last):
File "C:\sharp.py", line 16, in <module>
l=pixels[i-k+1,j-m+1]*sharp[i]
IndexError: image index out of range
Run Code Online (Sandbox Code Playgroud)

如何解决我的错误以及如何使图像锐化在此代码中起作用?

gro*_*ina 5

您提到的特定错误是因为您没有处理图像的边框。一种解决方案是填充图像或处理宽度和高度限制。例如:取代i-k+1j-m+1max(0, min(w, i-k+1))max(0, min(h, j-m+1)))分别。

您的代码还有其他问题:

  • 您正在访问的过滤器元素不正确...您可能是说sharp[3*m+k]您在哪里写的sharp[i]
  • 您使用的是彩色图像还是灰度图像?对于彩色图像,l具有3个尺寸,不能直接与单个数字(0或255)进行比较。
  • 同样,l值的裁剪和putpixel调用应位于最内部的循环内。
  • 您的内核看起来有些奇怪。那8应该是5吗?也许9和0变成-1?看一下内核这个例子
  • 具有多个嵌套循环的这种实现不是很有效。

我为您的问题推荐以下解决方案。

如果您想锐化图像,仅此而已,可以使用PIL.Image.filter

from PIL import Image, ImageFilter


img = Image.open('lena.png')
img_sharp = img.filter(ImageFilter.SHARPEN)
img_sharp.show()
Run Code Online (Sandbox Code Playgroud)

如果确实要指定内核,请尝试使用以下命令scipy。一定要看一下卷积文档

from PIL import Image

from scipy import ndimage, misc
import numpy as np


img = misc.imread('lena.png').astype(np.float)  # read as float
kernel = np.array([0, -1, 0, -1, 5, -1, 0, -1, 0]).reshape((3, 3, 1))

# here we do the convolution with the kernel
imgsharp = ndimage.convolve(img, kernel, mode='nearest')
# then we clip (0 to 255) and convert to unsigned int
imgsharp = np.clip(imgsharp, 0, 255).astype(np.uint8)

Image.fromarray(imgsharp).show()  # display
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用OpenCV。看一下这篇文章。它将澄清许多实现细节。

  • 多么有用的答案。我希望我可以投票两次。 (2认同)