This is web exercise 3.1.14. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Set pixel (i, j) to the color of the most frequent value among pixels with Manhattan distance W of (i, j) in the original image.
Here is my program:
import java.awt.Color;
public class OilPaintingFilter
{
public static int findNumberOfPixels(int distance)
{
int numberOfPixels = 4;
if (distance == 1) return numberOfPixels;
int increment = 8;
for (int i = 2; i <= distance; i++)
{
numberOfPixels += increment;
increment += 4;
}
return numberOfPixels;
}
public static Color[] findNeighboringColors(Picture picture, int col, int row, int distance)
{
int width = picture.width();
int height = picture.height();
Color[] pixels = new Color[findNumberOfPixels(distance)+1];
int counter = 0;
for (int j = col-distance; j <= col+distance; j++)
{
for (int i = row-distance; i <= row+distance; i++)
{
if ((Math.abs(col-j) + Math.abs(row-i)) <= distance)
{
pixels[counter] = picture.get(Math.abs(j)%width,Math.abs(i)%height);
counter++;
}
}
}
return pixels;
}
public static Color findMostFrequentNeighbor(Color[] pixels)
{
int[] colors = new int[pixels.length];
for (int i = 0; i < pixels.length; i++)
{
for (int j = 0; j < pixels.length; j++)
{
if (pixels[i].equals(pixels[j]))
{
colors[i]++;
}
}
}
int max = 0;
int index = 0;
for (int i = 0; i < pixels.length; i++)
{
if (colors[i] > max)
{
max = colors[i];
index = i;
}
}
return pixels[index];
}
public static Picture applyPaintingFilter(Picture picture, int distance)
{
int width = picture.width();
int height = picture.height();
Picture newPicture = new Picture(width,height);
for (int col = 0; col < width; col++)
{
for (int row = 0; row < height; row++)
{
Color newColor = findMostFrequentNeighbor(findNeighboringColors(picture, col, row, distance));
newPicture.set(col,row,newColor);
}
}
return newPicture;
}
public static void main(String[] args)
{
Picture picture = new Picture(args[0]);
int distance = Integer.parseInt(args[1]);
Picture newPicture = applyPaintingFilter(picture, distance);
newPicture.show();
}
}
Picture is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it:
Input (picture of a puffin taken from Pinterest):
with Manhattan distance = 10
Output:
Is there any way that I can improve my program?
Thanks for your attention.