首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python中的图像锐化错误

Python中的图像锐化错误
EN

Stack Overflow用户
提问于 2017-11-19 21:10:00
回答 1查看 6.6K关注 0票数 1
代码语言:javascript
复制
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()

我想对灰度图像应用3x3遮罩大小的高通(锐化)滤镜。但是我得到了一个错误:

代码语言:javascript
复制
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

我怎样才能纠正我的错误,怎样才能让图像锐化在这段代码中工作呢?

EN

回答 1

Stack Overflow用户

发布于 2018-07-11 04:19:59

我们也可以用scipy.convolve2d来锐化RGB图像。我们必须对每个图像通道分别应用卷积。下面的代码显示了与lena图像相同的内容

代码语言:javascript
复制
from scipy import misc, signal
import numpy as np

im = misc.imread('../images/lena.jpg')/255. # scale pixel values in [0,1] for each channel

print(np.max(im))
# 1.0
print(im.shape)
# (220, 220, 3)

sharpen_kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
im_sharpened = np.ones(im.shape)
for i in range(3):
    im_sharpened[...,i] = np.clip(signal.convolve2d(im[...,i], sharpen_kernel, mode='same', boundary="symm"),0,1)

fig, ax = plt.subplots(nrows=2, figsize=(10, 20))
ax[0].imshow(im)
ax[0].set_title('Original Image', size=20)
ax[1].imshow(im_sharpened)
ax[1].set_title('Sharpened Image', size=20)
plt.show()

我们可以使用高斯内核首先模糊图像,并从原始图像中减去,以获得锐化的图像,如以下代码所示:

代码语言:javascript
复制
from scipy import misc, ndimage

im = misc.imread('../images/lena.jpg') / 255 # scale pixel values in [0,1] for each channel    

# First a 1-D  Gaussian
t = np.linspace(-10, 10, 30)
bump = np.exp(-0.1*t**2)
bump /= np.trapz(bump) # normalize the integral to 1

# make a 2-D kernel out of it
kernel = bump[:, np.newaxis] * bump[np.newaxis, :]

im_blur = ndimage.convolve(im, kernel.reshape(30,30,1))

im_sharp = np.clip(2*im - im_blur, 0, 1)

fig, ax = plt.subplots(nrows=2, figsize=(10, 20))

ax[0].imshow(im)
ax[0].set_title('Original Image', size=20)

ax[1].imshow(im_sharp)
ax[1].set_title('Sharpened Image', size=20)

plt.show()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47377230

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档