-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathOpenCvService.java
More file actions
164 lines (129 loc) · 5.99 KB
/
OpenCvService.java
File metadata and controls
164 lines (129 loc) · 5.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package solutions.bellatrix.plugins.opencv;
import nu.pattern.OpenCV;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import plugins.screenshots.ScreenshotPlugin;
import solutions.bellatrix.core.configuration.ConfigurationService;
import solutions.bellatrix.core.utilities.Log;
import solutions.bellatrix.core.utilities.SingletonFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
public class OpenCvService {
/**
* @return the current scaling factor (e.g., 1.0 for 100%, 1.25 for 125%)
*/
public static double getJavaMonitorScaling() {
GraphicsConfiguration gc = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
// Get the default transform
AffineTransform transform = gc.getDefaultTransform();
// The scaling factor is typically the same for both X and Y
double scaleX = transform.getScaleX();
double scaleY = transform.getScaleY();
// Return X scale (usually same as Y scale)
return scaleX;
}
public static Point getLocation(Base64Encodable encodedImage) {
OpenCvServiceSettings openCvServiceSettings = ConfigurationService.get(OpenCvServiceSettings.class);
if (openCvServiceSettings == null) {
openCvServiceSettings = new OpenCvServiceSettings();
}
var precisionThreshold = openCvServiceSettings.getDefaultMatchThreshold();
var shouldGrayscale = openCvServiceSettings.isShouldGrayscale();
return getLocation(encodedImage, shouldGrayscale, precisionThreshold);
}
/**
* @return the coordinates of the image found on the screen
*/
public static Point getLocation(Base64Encodable encodedImage, boolean shouldGrayScale, double precisionThreshold) {
var screenshotPlugin = SingletonFactory.getInstance(ScreenshotPlugin.class);
Log.info("Locating image using precision: %s; Should Grayscale = %s".formatted(precisionThreshold, shouldGrayScale));
if (screenshotPlugin == null) {
throw new IllegalArgumentException("Screenshot plugin not registered!");
}
var screenshot = screenshotPlugin.takeScreenshot();
OpenCV.loadLocally();
Mat result = loadImages(encodedImage, screenshot, shouldGrayScale);
return getMatchLocation(encodedImage, result, precisionThreshold);
}
private static Point getMatchLocation(Base64Encodable encodedImage, Mat result, double precisionThreshold) {
BufferedImage bufferedImage;
Core.MinMaxLocResult mmr = Core.minMaxLoc(result);
if (mmr.maxVal < precisionThreshold) {
throw new RuntimeException("Match not found above threshold. Closest match at: %s".formatted(mmr.maxVal));
}
Log.info("Image located with precision: %s".formatted(mmr.maxVal));
Point matchLoc = mmr.maxLoc;
if (encodedImage.getXOffset() == 0 && encodedImage.getYOffset() == 0) {
try {
bufferedImage = getImageWidthHeight(encodedImage);
} catch (IOException e) {
throw new RuntimeException(e);
}
double[] imageCenterCoordinates = {
matchLoc.x / getJavaMonitorScaling() + (double)(bufferedImage.getWidth() / 2),
matchLoc.y / getJavaMonitorScaling() + (double)(bufferedImage.getHeight() / 2)
};
matchLoc.set(imageCenterCoordinates);
}
return matchLoc;
}
private static BufferedImage getImageWidthHeight(Base64Encodable encodedImage) throws IOException {
String cleanBase64 = removePrefixFromBase64(encodedImage);
byte[] decodedBytes = Base64.getDecoder().decode(cleanBase64);
ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);
BufferedImage bimg = ImageIO.read(bis);
return bimg;
}
private static Mat loadImages(Base64Encodable encodedImage, byte[] screenshot, boolean shouldGrayScale) {
Mat template = getMatrixFromBase64(encodedImage);
if (shouldGrayScale) {
changeToGrayscale(template);
}
Mat source = getMatrixFromBinaryData(screenshot);
if (shouldGrayScale) {
changeToGrayscale(source);
}
Mat result = createResultMatrix(source, template);
Imgproc.matchTemplate(source, template, result, Imgproc.TM_CCOEFF_NORMED);
return result;
}
private static Mat changeToGrayscale(Mat template) {
Mat templateGrayscale = new Mat();
Imgproc.cvtColor(template, templateGrayscale, Imgproc.COLOR_BGR2GRAY);
template = templateGrayscale;
return template;
}
private static Mat getMatrixFromBase64(Base64Encodable encodedImage) {
String cleanBase64 = removePrefixFromBase64(encodedImage);
byte[] decodedBytes = Base64.getDecoder().decode(cleanBase64);
return getMatrixFromBinaryData(decodedBytes);
}
private static String removePrefixFromBase64(Base64Encodable encodedImage) {
String base64Image = encodedImage.getBase64Image();
return base64Image.replaceFirst("^data:.+?;base64,", "");
}
private static Mat getMatrixFromBinaryData(byte[] decodedBytes) {
Mat mat = new Mat(1, decodedBytes.length, CvType.CV_8U);
mat.put(0, 0, decodedBytes);
return Imgcodecs.imdecode(mat, Imgcodecs.IMREAD_COLOR);
}
private static Mat createResultMatrix(Mat source, Mat template) {
Mat result = new Mat();
int result_cols = source.cols() - template.cols() + 1;
int result_rows = source.rows() - template.rows() + 1;
result.create(result_rows, result_cols, CvType.CV_32FC1);
return result;
}
}