Hello everyone, in this project I'm trying to convert an image to a matrix of ASCII characters but I got stuck at some point and I would be happy te get your help.
The idea is:
- Load an image as a Mat object
- Iterate through all the pixels and store them in a 2D array
where each cell is going to be an array of 3 variables [R, G, B]
- Iterate through the pixels array and get the average of the RGB values
and store them into an array called brightness
- Iterate through the brightness array and map each double value to a specific char
where the chars are saved in the chars string variable
<pre>public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Imgcodecs imageCodecs = new Imgcodecs();
Mat matrix = Imgcodecs.imread("pineapple.jpg");
Mat c = matrix.clone();
int pixelsCounter = 0;
System.out.println("width: " + c.width() + ", height: " + c.height());
ArrayList<ArrayList<Double>> pixels = new ArrayList<>();
for (int i = 0; i < c.height(); i++) {
for (int j = 0; j < c.width(); j++) {
pixelsCounter++;
ArrayList<Double> tmp = new ArrayList<>();
tmp.add(c.get(i, j)[0]);
tmp.add(c.get(i, j)[1]);
tmp.add(c.get(i, j)[2]);
pixels.add(tmp);
}
}
System.out.println("Pixels: " + pixelsCounter);
ArrayList<Double> brightness = new ArrayList<>();
for(int i = 0; i < pixels.size(); i++) {
double avgBrightness = (pixels.get(i).get(0) + pixels.get(i).get(1) +
pixels.get(i).get(2))/3;
brightness.add(avgBrightness);
}
Map<Double, Character> map = new HashMap<>();
final String chars = "`^\\\",:;Il!i~+_-?][}{1)
(|\\\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$";
for(int i = 0; i < brightness.size(); i++) {
Character c1 = chars.charAt((int) Math.ceil(((chars.length() - 1) *
brightness.get(i)/255)));
map.put(brightness.get(i), c1);
}
map.entrySet().forEach( entry -> {
System.out.println( entry.getKey() + " => " + entry.getValue() );
});
}
Till this point my program does all the above steps that I mentioned. The problem is that it I don't know how to print these chars in a way that it will look like a real ascii art figure?
What I have tried:
I've tried so many ways to do this but I can't find anything online related to how to do this in Java using OpenCV library.