You need to enable JavaScript to run this app. 如何使用Python对图像的局部区域应用滤镜效果
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python对图像的局部区域应用滤镜效果

问题原因

你当前未处理区域显示为黑色,是因为输出数组imfil被初始化为全0数组,没有经过特效计算的位置默认值为0(对应RGB黑色),未继承原图的像素内容。

所需修改

只需要改动3个核心位置即可实现需求:

  1. 初始化输出数组时直接拷贝原图,而非创建全0数组,这样未经过特效处理的区域默认保留原图内容
  2. 修正im.convert("RGB")的写法,该方法会返回新的Image对象,需要赋值后才能生效,避免原图为RGBA格式时出现维度错误
  3. 可选:给计算后的像素值增加范围限制,避免数值超出0-255区间导致显示异常

如果需要自定义特效作用区域,调整遍历逻辑里的row、column的起止范围即可,你当前代码里的Nxnew=int(0.5*Nx)就是限定仅上半张图生效,调整这个参数或者自定义列的范围就能灵活控制作用区域。

修改后完整代码

import numpy as np
import matplotlib.pyplot as plt
from math import floor
from PIL import Image

print('Please insert the effect of your choice:')
print('1. No effect')
print('2. Edge detection')
print('3. Image Sharpening')
print('4. Image Blurring')
ch=(input('Insert the number of choice: '))
if ch!='1' and ch!='2' and ch!='3' and ch!='4':
    print('No effect available')
    ch=(input('Insert the number of choice: '))
    
im=Image.open('unnamed.jpg')
# 修正convert方法的赋值逻辑
im = im.convert("RGB")
imagematrix=np.array(im)
(Nx,Ny,M)=imagematrix.shape

if ch=='1':
    kernel=np.array([[0,0,0],[0,1,0],[0,0,0]])
elif ch=='2':
    kernel=np.array([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]])
elif ch=='3':
    kernel=np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])
elif ch=='4':
    kernel=np.array([[1,1,1],[1,1,1],[1,1,1]])

div=np.sum(kernel)

if div==0:
   div=1
Nxnew=int(0.5*Nx)
# 初始化时直接拷贝原图,未处理区域自动保留原图内容
imfil = imagematrix.copy()
for j in range (0,M):
    for row in range (1, Nxnew-1):
        for column in range(1, Ny-1):
            a=0
            for b in range(-1,2):
                for k in range(-1,2):
                    a+=imagematrix[row+b,column+k,j]*kernel[b+1,k+1]
            # 增加clip限制,避免像素值超出0-255范围
            imfil[row,column,j]=np.clip(floor(abs(a/div)), 0, 255)
plt.imshow(imfil)
plt.show()

内容的提问来源于stack exchange,提问作者rehan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 08:45:02