blurring an image with image.crop() - AttributeError: 'numpy.ndarray' object has no attribute 'crop'

blurring an image with image.crop() - AttributeError: 'numpy.ndarray' object has no attribute 'crop'

我有一张图片,我想模糊其中的一部分。

我正在寻找的输出就像这个 Filter part of image using PIL, python 答案中看到的部分模糊的棋盘。

我尝试使用上述答案中的代码,但收到一条错误消息:

----> 2 ic = image.crop(box)

AttributeError: 'numpy.ndarray' object has no attribute 'crop'

我该如何前进?我应该尝试将 np.ndarry 转换为图像吗?

谢谢!

# libraries 
import cv2
from PIL import Image

# read in  
path = 'C://Users/my_account//Desktop//robert_downey_jr_image.png'
image = cv2.imread(path)

# blurring 
box = (30, 30, 110, 110)  
ic = image.crop(box)
for i in range(10):  
    ic = ic.filter(ImageFilter.BLUR)
image.paste(ic, box)

image.show()

# ERROR MESSAGE 
----> 2 ic = image.crop(box)
AttributeError: 'numpy.ndarray' object has no attribute 'crop'

你的图片只是一个NumPy数组,没有你说的crop属性

您需要使用 PIL 图像库打开它:

image = Image.open(path)

然后就可以调用crop了。参见 https://pillow.readthedocs.io/en/stable/reference/Image.html