package t3x.tnn.utility;
import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class OCR {
static public String recognize(Point hg, Point bd, Color color, boolean isColorEcriture){
String res = null;
File fImg = new File("screenshot.png");
while(res == null){
BufferedImage img = ScreenHandler.getScreen(hg, bd);
if(isColorEcriture)
img = changeWithColorEcriture(img, color);
else
img = changeWithColorFond(img, color);
try {
ImageIO.write(img, "PNG", fImg);
Process p = Runtime.getRuntime().exec("nconvert -out ppm -o text.ppm screenshot.png");
p.waitFor();
p.destroy();
p = Runtime.getRuntime().exec("gocr045 text.ppm");
p.waitFor();
if(p.getInputStream().available()>0)
res = IOHandler.getResponse(p.getInputStream());
p.destroy();
}catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fImg.exists())
fImg.delete();
File texte = new File("text.ppm");
if(texte.exists())
texte.delete();
return res.replace("l", "1").replace("O", "0").trim();
}
private static BufferedImage changeWithColorEcriture(BufferedImage bi, Color ecriture) {
if (bi != null) {
int w = bi.getWidth();
int h = bi.getHeight();
int pixel;
BufferedImage bitmp = new BufferedImage(w, h, bi.getType());
BufferedImage biOut = new BufferedImage(w, h, bi.getType());
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
pixel = bi.getRGB(x, y);
if(pixel != ecriture.getRGB())
pixel = Color.BLUE.getRGB();
else
pixel = Color.BLACK.getRGB();
bitmp.setRGB(x, y, pixel);
}
}
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
pixel = bitmp.getRGB(x, y);
if(pixel == Color.BLUE.getRGB())
pixel = Color.WHITE.getRGB();
biOut.setRGB(x, y, pixel);
}
}
return biOut;
} else {
return bi;
}
}
private static BufferedImage changeWithColorFond(BufferedImage bi, Color fond) {
if (bi != null) {
int w = bi.getWidth();
int h = bi.getHeight();
int pixel;
BufferedImage bitmp = new BufferedImage(w, h, bi.getType());
BufferedImage biOut = new BufferedImage(w, h, bi.getType());
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
pixel = bi.getRGB(x, y);
if(pixel == fond.getRGB())
pixel = Color.BLUE.getRGB();
else
pixel = Color.WHITE.getRGB();
bitmp.setRGB(x, y, pixel);
}
}
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
pixel = bitmp.getRGB(x, y);
if(pixel == Color.BLUE.getRGB())
pixel = Color.WHITE.getRGB();
biOut.setRGB(x, y, pixel);
}
}
return biOut;
} else {
return bi;
}
}
}