简体   繁体   English

如何使用 Pillow 模糊 Python 中的图像

[英]How to blur a image in Python using Pillow

I am trying to take an image and blur it in Python using Pillow.我正在尝试使用 Pillow 在 Python 中拍摄图像并将其模糊。

The only things that are imported are random and Image.唯一导入的东西是随机和图像。

The only functions of Image I can use are open, size, load, new, close, show and save.我可以使用的 Image 的唯一功能是打开、调整大小、加载、新建、关闭、显示和保存。

I know that I have to take the average RGB values of the pixels surrounding every pixel and then set that value to be the RGB value of the center pixel.我知道我必须取每个像素周围像素的平均 RGB 值,然后将该值设置为中心像素的 RGB 值。

The problem is that I don't know how to get these values and look at specific edge cases where there are fewer adjacent pixels.问题是我不知道如何获取这些值并查看相邻像素较少的特定边缘情况。

I am not allowed to import anything and can only use lists, loops, if statements, dictionaries, and tuples.我不能导入任何东西,只能使用列表、循环、if 语句、字典和元组。

Take a look at this: https://en.wikipedia.org/wiki/Kernel_%28image_processing%29看看这个: https://en.wikipedia.org/wiki/Kernel_%28image_processing%29

Basically, you'll want to loop over the image and compute the new value for each pixel.基本上,您需要遍历图像并计算每个像素的新值。 If you can change the size of the image, then you can simply ignore the borders and therefore the edge cases.如果您可以更改图像的大小,那么您可以简单地忽略边界,从而忽略边缘情况。 Otherwise, you'll need to apply one of the edge-handling techniques listed in the wiki page.否则,您将需要应用 wiki 页面中列出的边缘处理技术之一。

Good luck!!祝你好运!!

You can use numpy.lib.stride_tricks.as_strided in order to create a window along the two spatial dimensions which can then be used to average neighboring points via mean .您可以使用numpy.lib.stride_tricks.as_strided以沿两个空间维度创建 window ,然后可用于通过 mean 对相邻点进行mean The following uses a (3, 3) window, ie only considering direct neighbors but different values are possible of course.下面使用(3, 3) window,即只考虑直接邻居,但当然可以有不同的值。 To work on the edges, the original image first gets padded by repeating the edge values.要处理边缘,首先通过重复边缘值来填充原始图像。 Then the window averaging process can be repeated an arbitrary number times, depending on the desired blur factor.然后 window 平均过程可以重复任意次数,具体取决于所需的模糊因子。 Here is some example code:这是一些示例代码:

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

original_image = np.array(Image.open('example.jpg'))
image = np.pad(original_image, ((1,), (1,), (0,)), mode='edge')
window = np.lib.stride_tricks.as_strided(
    image,
    image.shape + (3, 3),
    image.strides + image.strides[:2]
)[:-2, :-2]

for __ in range(10):
    image[1:-1, 1:-1] = window.mean(axis=(-1, -2))

plt.title('Original')
plt.imshow(original_image)
plt.figure()
plt.title('Blurred')
plt.imshow(image[1:-1, 1:-1])

plt.show()

And here are the two image versions for comparison:这是两个图像版本进行比较:

原来的

模糊
Photo by Cameron Venti on Unsplash卡梅隆·文蒂 (Cameron Venti) 在 Unsplash 上拍摄的照片

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM