【发布时间】:2014-07-23 23:40:18
【问题描述】:
我有一组抗锯齿灰度 PNG 图像。我需要知道如何以编程方式恢复抗锯齿效果并再次获得锐利的边缘。
我正在使用 GDI+,但我对代码不太感兴趣。我需要一个算法。
灰度图像(应该)仅包含 6 种颜色(或不同深浅的灰色)。这样以后我可以使用颜色查找过滤器重新着色它们。但是,当保存图像时,Photoshop 会自动应用抗锯齿,因此边缘会变得模糊(因为启用了双三次插值模式)。我需要恢复这种效果。
这是一个例子:
这是 Photoshop 的截图
有人建议我应该应用锐化滤镜,所以我在 Photoshop 上尝试了它。这是它的外观:
尽管外边缘很好,但 2 种不同颜色相遇的边缘会显示伪影。
编辑:
这就是我最终做到的方式。这是非常即兴的,可能可以做得更好更快,但我找不到更好的解决方案。
这个想法是遍历每个像素,获取其直接邻居并将其颜色与它们的颜色进行比较。如果它由至少 2 个相同颜色的像素支持,它会检查相邻像素是否也支持。如果不是,它会用自己的像素替换相邻像素。
代码:
private static void Resample(Bitmap bmp)
{
// First we look for the most prominent colors
// i.e. They make up at least 1% of the image
Hashtable stats = new Hashtable();
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
Color px = bmp.GetPixel(x, y);
if (px.A == 0)
continue;
Color pxS = Color.FromArgb(255, px);
if (stats.ContainsKey(pxS.ToArgb()))
stats[pxS.ToArgb()] = (int)stats[pxS.ToArgb()] + 1;
else
stats.Add(pxS.ToArgb(), 1);
}
}
float totalSize = bmp.Width*bmp.Height;
float minAccepted = 0.01f;
List<int> selectedColors = new List<int>();
// Make up a list with the selected colors
foreach (int key in stats.Keys)
{
int total = (int)stats[key];
if (((float)total / totalSize) > minAccepted)
selectedColors.Add(key);
}
// Keep growing the zones with the selected colors to cover the invalid colors created by the anti-aliasing
while (GrowSelected(bmp, selectedColors));
}
private static bool GrowSelected(Bitmap bmp, List<int> selectedColors)
{
bool flag = false;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
Color px = bmp.GetPixel(x, y);
if (px.A == 0)
continue;
Color pxS = Color.FromArgb(255, px);
if (selectedColors.Contains(pxS.ToArgb()))
{
if (!isBackedByNeighbors(bmp, x, y))
continue;
List<Point> neighbors = GetNeighbors(bmp, x, y);
foreach(Point p in neighbors)
{
Color n = bmp.GetPixel(p.X, p.Y);
if (!isBackedByNeighbors(bmp, p.X, p.Y))
bmp.SetPixel(p.X, p.Y, Color.FromArgb(n.A, pxS));
}
}
else
{
flag = true;
}
}
}
return flag;
}
private static List<Point> GetNeighbors(Bitmap bmp, int x, int y)
{
List<Point> neighbors = new List<Point>();
for (int i = x - 1; i > 0 && i <= x + 1 && i < bmp.Width; i++)
for (int j = y - 1; j > 0 && j <= y + 1 && j < bmp.Height; j++)
neighbors.Add(new Point(i, j));
return neighbors;
}
private static bool isBackedByNeighbors(Bitmap bmp, int x, int y)
{
List<Point> neighbors = GetNeighbors(bmp, x, y);
Color px = bmp.GetPixel(x, y);
int similar = 0;
foreach (Point p in neighbors)
{
Color n = bmp.GetPixel(p.X, p.Y);
if (Color.FromArgb(255, px).ToArgb() == Color.FromArgb(255, n).ToArgb())
similar++;
}
return (similar > 2);
}
结果: 原图: http://i.imgur.com/8foQwFe.png
【问题讨论】:
-
你需要提供一些你已经尝试过的例子,或者你遇到的问题。您不应该要求其他人为您完成任务。
-
您可以通过扫描 3x3 块相同颜色的像素来获取要在输出中使用的颜色目录。
标签: image-processing graphics rendering antialiasing imagefilter