【发布时间】:2020-03-25 00:27:22
【问题描述】:
我想从图像中移除抗锯齿。此代码将从图像中获取 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")
如您所见,颜色之间的边界并不完美。
这就是我想要的结果:
(似乎图片托管网站压缩了图片,并且不会正确显示“别名”图片)
【问题讨论】:
-
@HansHirse 可能是对的;我没有考虑这方面,并检查了后面的大部分内容;-)我想指出两个方面:①您确定四种主要颜色的方法仅适用于没有很多中间色且没有大区域的抖动(JPG 工件和类似的),但也许您的输入符合这些特征。 ② 如果主色 A 接近主色 B 和 C 之间的线,您的算法将选择 A 作为 B 和 C 之间的抗锯齿像素。您可以通过使用相邻像素而不是简单的颜色匹配来解决此问题。跨度>
标签: python numpy image-processing python-imaging-library antialiasing