con*_*dor 2 python numpy image-processing antialiasing python-imaging-library
我想从图像中删除抗锯齿功能。此代码将从图像中获取 4 种主要颜色,将每个像素与 4 种主要颜色进行比较并分配最接近的颜色。
import numpy as np
from PIL import Image
image = Image.open('pattern_2.png')
image_nd = np.array(image)
image_colors = {}
for row in image_nd:
for pxl in row:
pxl = tuple(pxl)
if not image_colors.get(pxl):
image_colors[pxl] = 1
else:
image_colors[pxl] += 1
sorted_image_colors = sorted(image_colors, key=image_colors.get, reverse=True)
four_major_colors = sorted_image_colors[:4]
def closest(colors, color):
colors = np.array(colors)
color = np.array(color)
distances = np.sqrt(np.sum((colors - color) ** 2, axis=1))
index_of_smallest = np.where(distances == np.amin(distances))
smallest_distance = colors[index_of_smallest]
return smallest_distance[0]
for y, row in enumerate(image_nd):
for x, pxl in enumerate(row):
image_nd[y, x] = closest(four_major_colors, image_nd[y, x])
aliased = Image.fromarray(image_nd)
aliased.save("pattern_2_al.png")
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,颜色之间的边界并不完美。
这就是我追求的结果:
(图像托管网站似乎压缩了图像,并且不会正确显示“锯齿”图像)
这里的主要问题在于你的closest方法:
def closest(colors, color):
colors = np.array(colors)
color = np.array(color)
distances = np.sqrt(np.sum((colors - color) ** 2, axis=1))
Run Code Online (Sandbox Code Playgroud)
和colors都color成为 NumPy 类型的数组uint8。现在,当减去uint8值时,不会得到负值,但会发生整数下溢,导致值接近255。因此,之后的计算结果distances是错误的,最终导致选色错误。
因此,最快的解决方法是将这两个变量转换为int32:
def closest(colors, color):
colors = np.array(colors).astype(np.int32)
color = np.array(color).astype(np.int32)
distances = np.sqrt(np.sum((colors - color) ** 2, axis=1))
Run Code Online (Sandbox Code Playgroud)
此外,利用 NumPy 的矢量化功能可能很有用。为您考虑以下方法closest:
def closest(colors, image):
colors = np.array(colors).astype(np.int32)
image = image.astype(np.int32)
distances = np.argmin(np.array([np.sqrt(np.sum((color - image) ** 2, axis=2)) for color in colors]), axis=0)
return colors[distances].astype(np.uint8)
Run Code Online (Sandbox Code Playgroud)
因此,不要迭代所有像素
for y in np.arange(image_nd.shape[0]):
for x in np.arange(image_nd.shape[1]):
image_nd[y, x] = closest(four_major_colors, image_nd[y, x])
Run Code Online (Sandbox Code Playgroud)
你可以简单地传递整个图像:
image_nd = closest(four_major_colors, image_nd)
Run Code Online (Sandbox Code Playgroud)
使用给定的图像,我的机器速度提高了 100 倍。当然,查找 RGB 直方图值也可以进行优化。(不幸的是,我对 Python 字典的体验还不是很好......)
不管怎样——希望有帮助!
| 归档时间: |
|
| 查看次数: |
2850 次 |
| 最近记录: |