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)
如何解决我的错误以及如何使图像锐化在此代码中起作用?
您提到的特定错误是因为您没有处理图像的边框。一种解决方案是填充图像或处理宽度和高度限制。例如:取代i-k+1
和j-m+1
由max(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
调用应位于最内部的循环内。我为您的问题推荐以下解决方案。
如果您想锐化图像,仅此而已,可以使用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。看一下这篇文章。它将澄清许多实现细节。
归档时间: |
|
查看次数: |
4320 次 |
最近记录: |