Compare commits

10 Commits
Author SHA1 Message Date
Paul-1108 545e803554 Luppt
Fehlt noch:
Transformation und Collision
2024-12-17 19:56:53 +01:00
moeckelda95243 ada8284535 16.12.24 22:39 Graphic manschma noch überforderet 2024-12-16 22:40:09 +01:00
Paul-1108 a7efee2023 Puffer Check
Bild Übergabe Check

Noch offen: Merge mit Bildanalyse und Zeichnen

16.12.2024 21:35
2024-12-16 21:36:19 +01:00
Paul-1108 789f9e56f1 Funktionierender Puffer
Bild wird nicht korrekt gespeichert
16.12.2024 16:48
2024-12-16 16:48:48 +01:00
Paul-1108 736154abf4 Funktionierender Puffer
16.12.2024 15.06
Siuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
2024-12-16 15:07:13 +01:00
stammingerpa92423 4e6a0ed98a Puffer Versuch
Speicher läuft voll
16.12.2024 03:30
2024-12-16 03:32:20 +01:00
moeckelda95243 b05c2a8319 Version 13.12 Fehler: getP1 und getP2 geben 0,0 zurück obwohl bis dahin noch richtige Koordinaten in currentPositionP1 -P2 gespeichert sind 2024-12-13 16:30:28 +01:00
Paul-1108 739a7e129c V2.2 des Gameloop und Logic
11.12.24 16:45
2024-12-11 16:46:05 +01:00
Paul-1108 32bad236ed V2 des Gameloop und Logic
sollte gehen
11.12.24 14:13
2024-12-11 14:16:46 +01:00
moeckelda95243 5f211026e4 Version 04.12 "vollständiges Programm mit Fehlern" 2024-12-04 17:07:47 +01:00
10 changed files with 566 additions and 251 deletions
+89 -30
View File
@@ -4,9 +4,12 @@
<option name="autoReloadType" value="SELECTIVE" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="4d75e996-cee4-4ec6-b802-5b56d0c0eac4" name="Changes" comment="Version 27.11 (&quot;fertiger&quot; Tracker)"> <list default="true" id="4d75e996-cee4-4ec6-b802-5b56d0c0eac4" name="Changes" comment="Funktionierender Puffer&#10;Bild wird nicht korrekt gespeichert&#10;16.12.2024 16:48">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/Tracker.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/Tracker.java" afterDir="false" /> <change beforePath="$PROJECT_DIR$/src/main/java/CamPuffer.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/CamPuffer.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/GameLoop.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/GameLoop.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/GraphicsProgram.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/GraphicsProgram.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/ImgAnalyzer.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/ImgAnalyzer.java" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -32,33 +35,34 @@
<option name="hideEmptyMiddlePackages" value="true" /> <option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" /> <option name="showLibraryContents" value="true" />
</component> </component>
<component name="PropertiesComponent"><![CDATA[{ <component name="PropertiesComponent">{
"keyToString": { &quot;keyToString&quot;: {
"Application.GTCar.executor": "Run", &quot;Application.GTCar.executor&quot;: &quot;Run&quot;,
"Application.GraphicsProgram.executor": "Run", &quot;Application.GraphicsProgram.executor&quot;: &quot;Run&quot;,
"Application.Tracker.executor": "Run", &quot;Application.Main.executor&quot;: &quot;Run&quot;,
"Downloaded.Files.Path.Enabled": "false", &quot;Application.Tracker.executor&quot;: &quot;Run&quot;,
"Repository.Attach.Annotations": "false", &quot;Downloaded.Files.Path.Enabled&quot;: &quot;false&quot;,
"Repository.Attach.JavaDocs": "false", &quot;Repository.Attach.Annotations&quot;: &quot;false&quot;,
"Repository.Attach.Sources": "false", &quot;Repository.Attach.JavaDocs&quot;: &quot;false&quot;,
"RunOnceActivity.OpenProjectViewOnStart": "true", &quot;Repository.Attach.Sources&quot;: &quot;false&quot;,
"RunOnceActivity.ShowReadmeOnStart": "true", &quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
"com.codeium.enabled": "true", &quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
"git-widget-placeholder": "master", &quot;com.codeium.enabled&quot;: &quot;true&quot;,
"kotlin-language-version-configured": "true", &quot;git-widget-placeholder&quot;: &quot;master&quot;,
"last_opened_file_path": "C:/Users/david/Documents/Uni/GTCar/opencv/build/java/opencv-4100.jar", &quot;kotlin-language-version-configured&quot;: &quot;true&quot;,
"node.js.detected.package.eslint": "true", &quot;last_opened_file_path&quot;: &quot;C:/Users/david/Documents/Uni/GTCar/opencv/build/java/opencv-4100.jar&quot;,
"node.js.detected.package.tslint": "true", &quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
"node.js.selected.package.eslint": "(autodetect)", &quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
"node.js.selected.package.tslint": "(autodetect)", &quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
"nodejs_package_manager_path": "npm", &quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
"project.structure.last.edited": "Libraries", &quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
"project.structure.proportion": "0.15", &quot;project.structure.last.edited&quot;: &quot;Libraries&quot;,
"project.structure.side.proportion": "0.24022989", &quot;project.structure.proportion&quot;: &quot;0.15&quot;,
"vue.rearranger.settings.migration": "true" &quot;project.structure.side.proportion&quot;: &quot;0.24022989&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
} }
}]]></component> }</component>
<component name="RunManager"> <component name="RunManager" selected="Application.Main">
<configuration name="GTCar" type="Application" factoryName="Application"> <configuration name="GTCar" type="Application" factoryName="Application">
<option name="MAIN_CLASS_NAME" value="Tracker" /> <option name="MAIN_CLASS_NAME" value="Tracker" />
<module name="GTCar_V2_maven" /> <module name="GTCar_V2_maven" />
@@ -67,6 +71,40 @@
<option name="Make" enabled="true" /> <option name="Make" enabled="true" />
</method> </method>
</configuration> </configuration>
<configuration name="GraphicsProgram" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="GraphicsProgram" />
<module name="GTCar_V2_maven" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="Main" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="Main" />
<module name="GTCar_V2_maven" />
<option name="VM_PARAMETERS" value="-Djava.library.path=&quot;C:\Users\paul3\OneDrive\Dokumente\Studium BME\Semester 3\Interaktion\opencv\build\java\x64&quot;" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<list>
<item itemvalue="Application.GTCar" />
<item itemvalue="Application.GraphicsProgram" />
<item itemvalue="Application.Main" />
</list>
<recent_temporary>
<list>
<item itemvalue="Application.Main" />
<item itemvalue="Application.GraphicsProgram" />
</list>
</recent_temporary>
</component>
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-jdk-9823dce3aa75-28b599e66164-intellij.indexing.shared.core-IU-242.23726.103" />
<option value="bundled-js-predefined-d6986cc7102b-5c90d61e3bab-JavaScript-IU-242.23726.103" />
</set>
</attachedChunks>
</component> </component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" /> <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager"> <component name="TaskManager">
@@ -78,6 +116,9 @@
<updated>1732108904989</updated> <updated>1732108904989</updated>
<workItem from="1732108906083" duration="758000" /> <workItem from="1732108906083" duration="758000" />
<workItem from="1732113837570" duration="20534000" /> <workItem from="1732113837570" duration="20534000" />
<workItem from="1733327375447" duration="951000" />
<workItem from="1734091457440" duration="10746000" />
<workItem from="1734364915397" duration="9202000" />
</task> </task>
<task id="LOCAL-00001" summary="First Commit Test"> <task id="LOCAL-00001" summary="First Commit Test">
<option name="closed" value="true" /> <option name="closed" value="true" />
@@ -119,7 +160,23 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1732706211714</updated> <updated>1732706211714</updated>
</task> </task>
<option name="localTasksCounter" value="6" /> <task id="LOCAL-00006" summary="Funktionierender Puffer&#10;16.12.2024 15.06&#10;Siuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu">
<option name="closed" value="true" />
<created>1734358037207</created>
<option name="number" value="00006" />
<option name="presentableId" value="LOCAL-00006" />
<option name="project" value="LOCAL" />
<updated>1734358037207</updated>
</task>
<task id="LOCAL-00007" summary="Funktionierender Puffer&#10;Bild wird nicht korrekt gespeichert&#10;16.12.2024 16:48">
<option name="closed" value="true" />
<created>1734364131101</created>
<option name="number" value="00007" />
<option name="presentableId" value="LOCAL-00007" />
<option name="project" value="LOCAL" />
<updated>1734364131101</updated>
</task>
<option name="localTasksCounter" value="8" />
<servers /> <servers />
</component> </component>
<component name="TypeScriptGeneratedFilesManager"> <component name="TypeScriptGeneratedFilesManager">
@@ -142,6 +199,8 @@
<MESSAGE value="Version 23.11 (Grafics update)" /> <MESSAGE value="Version 23.11 (Grafics update)" />
<MESSAGE value="Version 27.11" /> <MESSAGE value="Version 27.11" />
<MESSAGE value="Version 27.11 (&quot;fertiger&quot; Tracker)" /> <MESSAGE value="Version 27.11 (&quot;fertiger&quot; Tracker)" />
<option name="LAST_COMMIT_MESSAGE" value="Version 27.11 (&quot;fertiger&quot; Tracker)" /> <MESSAGE value="Funktionierender Puffer&#10;16.12.2024 15.06&#10;Siuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu" />
<MESSAGE value="Funktionierender Puffer&#10;Bild wird nicht korrekt gespeichert&#10;16.12.2024 16:48" />
<option name="LAST_COMMIT_MESSAGE" value="Funktionierender Puffer&#10;Bild wird nicht korrekt gespeichert&#10;16.12.2024 16:48" />
</component> </component>
</project> </project>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

+129
View File
@@ -0,0 +1,129 @@
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.highgui.HighGui;
import org.opencv.videoio.Videoio;
import java.util.LinkedList;
public class CamPuffer implements Runnable {
static {
try {
System.load("C:\\Users\\paul3\\OneDrive\\Dokumente\\Studium BME\\Semester 3\\Interaktion\\opencv\\build\\java\\x64\\opencv_java4100.dll");
System.out.println("OpenCV manuell geladen!");
} catch (UnsatisfiedLinkError e) {
System.err.println("Fehler beim Laden der OpenCV-Bibliothek: " + e.getMessage());
}
}
private final int CAM; // Kamera-ID (0 für Webcam, 1 für andere Cams)
private final int EXP; // Belichtungszeit
private final int FPS;
private final int THV;
private volatile boolean running = true;
private final Object lock = new Object(); // Lock für Thread-Sicherheit
private Mat currentMat = new Mat();
private final Rect roi = new Rect(200, 150, 240, 180); // Region of Interest
private boolean hasStartedCapturing = false;
private final LinkedList<Mat> frameBuffer = new LinkedList<>();
private final int MAX_BUFFER_SIZE = 10; // Maximale Anzahl an Bildern im Puffer
public CamPuffer(int CAM, int EXP, int FPS, int THV) {
this.CAM = CAM;
this.EXP = EXP;
this.FPS = FPS;
this.THV = THV;
}
@Override
public void run() {
VideoCapture capture = setUp();
if (!capture.isOpened()) {
System.out.println("Fehler: Die Webcam konnte nicht geöffnet werden.");
return;
}
Mat frame = new Mat();
capture.read(frame);
hasStartedCapturing = true;
long lastGcTime = System.currentTimeMillis();
try {
while (running) {
//long startTime = System.currentTimeMillis();
capture.read(frame); // Bild einlesen
currentMat = frame;
if (frame.empty()) {
System.out.println("Fehler: Kein Bild von der Kamera erhalten.");
break;
}
updateCurrentMat(frame);
// Speicherbereinigung alle 1000 ms (1 Sekunde)
if (System.currentTimeMillis() - lastGcTime > 1000) {
System.gc(); // Triggern des Garbage Collectors
lastGcTime = System.currentTimeMillis();
System.out.println("Garbage Collection durchgeführt.");
}
}
} finally {
// Matrizen explizit freigeben
frame.release();
capture.release();
}
}
public void updateCurrentMat(Mat img) {
Mat frameCopy = img.clone();
synchronized (frameBuffer) {
if (frameBuffer.size() >= MAX_BUFFER_SIZE) {
frameBuffer.poll().release(); // Ältesten Frame entfernen
}
frameBuffer.add(frameCopy); // Neuen Frame hinzufügen
currentMat = frameCopy;
}
}
public Mat getCurrentMat() {
synchronized (frameBuffer) {
if (!frameBuffer.isEmpty()) {
Mat resizedFrame = new Mat();
Imgproc.resize(frameBuffer.pollLast().clone(), resizedFrame, new Size(1792, 1024));
return resizedFrame; // Rückgabe des neuesten Frames
}
}
return new Mat(); // Rückgabe eines leeren Frames, falls der Puffer leer ist
}
public void stop() {
running = false;
}
private VideoCapture setUp() {
System.out.println("Laden von OpenCV");
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture capture = new VideoCapture(CAM);
if (!capture.isOpened()) {
System.out.println("Fehler: Die Webcam konnte nicht geöffnet werden.");
}
capture.set(Videoio.CAP_PROP_BUFFERSIZE, 3);
capture.set(Videoio.CAP_PROP_EXPOSURE, EXP);
capture.set(Videoio.CAP_PROP_FPS, FPS);
System.out.println("Kamera geöffnet und eingerichtet");
return capture;
}
}
+51 -12
View File
@@ -1,21 +1,60 @@
import processing.core.PApplet;
import java.awt.*; import java.awt.*;
import java.util.LinkedList;
import java.util.Queue;
public class GameLogic { public class GameLogic extends PApplet {
private final int width; public static void main(String[] args) {
private final int height; PApplet.main("GameLogic");
private int[][] pitch;
public GameLogic(int width, int height){
this.width = width;
this.height = height;
pitch = new int[width][height];
} }
public boolean checkPlayer(Point point, int id){ private static final int MAX_TRAIL_SIZE = 100; // Maximale Größe des Trails
return false; private Queue<int[]> trail = new LinkedList<>();
private Point testPoint = new Point(200, 200);
public void settings() {
size(800, 600);
} }
public void setup() {
fillTrail(); // Beispielpfad erstellen
noLoop(); // Zeichnen nur bei Bedarf
}
private void fillTrail() {
// Beispielhafte Füllung der Spur (maximale Größe beachten)
for (int i = 0; i < MAX_TRAIL_SIZE; i++) {
trail.add(new int[]{50 + i * 5, 300}); // Punkte entlang der x-Achse
}
}
// Methode zum Hinzufügen eines neuen Punkts, begrenzt auf MAX_TRAIL_SIZE
public void addToTrail(int x, int y) {
if (trail.size() >= MAX_TRAIL_SIZE) {
trail.poll(); // Entferne das älteste Element, wenn die maximale Größe erreicht ist
}
trail.add(new int[]{x, y});
}
public boolean doCheckExtern(Queue<int[]> trail, Point point) {
return doCheck(trail, point);
}
public boolean doCheck(Queue<int[]> trail, Point point) {
int particleSize = 10;
// Zeichne den Pfad auf das Canvas nur, wenn nötig
background(255); // Weißer Hintergrund
for (int[] coordinates : trail) {
int x = coordinates[0];
int y = coordinates[1];
fill(0); // Schwarz
rect(x, y, particleSize, particleSize);
}
// Überprüfe die Pixelwerte am Testpunkt
int c = get(point.x, point.y); // Farbwert abrufen
return (c == color(0)); // Schwarz bedeutet Kollision
}
} }
+54 -43
View File
@@ -1,5 +1,4 @@
import processing.core.PApplet; import processing.core.PApplet;
import java.awt.Point; import java.awt.Point;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -7,7 +6,13 @@ import java.util.List;
public class GameLoop { public class GameLoop {
int activePlayer = 0; int activePlayer = 0;
Tracker tracker; private final int CAM = 0; // Kamera-ID (0 für Webcam, 1 für andere Cams)
private final int EXP = -9; // Belichtungszeit (idealerweise: 0)
private final int FPS = 20; // FPS
private final int THV = 245; // Threshold
ImgAnalyzer tracker;
CamPuffer camPuffer;
GraphicsProgram graphics; GraphicsProgram graphics;
@@ -17,28 +22,58 @@ public class GameLoop {
Player player2; Player player2;
public GameLoop(){ public GameLoop(){
player1 = new Player(0, "ip", 9000); player1 = new Player(0, "192.168.1.1", 9000);
player2 = new Player(1, "ip", 9000); player2 = new Player(1, "192.168.1.2", 9000);
tracker = new Tracker();
graphics = new GraphicsProgram(); camPuffer = new CamPuffer(CAM, EXP, FPS, THV);
Thread pufferThread = new Thread(camPuffer);
pufferThread.start();
tracker = new ImgAnalyzer(camPuffer, THV);
Thread trackerThread = new Thread(tracker::run);
trackerThread.start();
/*graphics = new GraphicsProgram(player1, player2);
String[] args = {"GraphicsProgram"}; String[] args = {"GraphicsProgram"};
PApplet.runSketch(args, graphics); PApplet.runSketch(args, graphics);
gl = new GameLogic(1080,720);
gl = new GameLogic();
String[] args_ = {"GameLogic"};
PApplet.runSketch(args_, gl); */
run(); run();
} }
private void run(){ private void run(){
while(true){ while(true){
communicate(); //communicate();
List<Point> positions = track();
if(checkP1(positions.get(0))){ Point p1 = tracker.getP1();
//System.out.println("Player 1 is at " + p1.x + " and " + p1.y);
Point p2 = tracker.getP2();
//System.out.println("Player 2 is at " + p2.x + " and " + p2.y);
/*player1.setKoords(p1.x, p1.y);
player2.setKoords(p2.x, p2.y);
if(gl.doCheckExtern(player2.getTrail(), p1)){ //Check Position von P1 mit Spur von P2
System.out.println("Spieler 1 hat verloren");
break; break;
} }
if(checkP2(positions.get(1))){
if(gl.doCheckExtern(player1.getTrail(), p2)){ //Check Position von P2 mit Spur von P1
System.out.println("Spieler 2 hat verloren");
break; break;
} */
//draw();
try{
wait(50);
}
catch (Exception e){
} }
addPositions(positions);
draw();
} }
} }
@@ -46,44 +81,20 @@ public class GameLoop {
//offen für Auto Kommunikation //offen für Auto Kommunikation
} }
private boolean checkP1(Point point){ /*private List<Point> track(){
if(gl.checkPlayer(point, 0)){
return true;
}
else {
return false;
}
}
private boolean checkP2(Point point){
if(gl.checkPlayer(point, 0)){
return true;
}
else {
return false;
}
}
private void addPositions(List positions){
}
private List<Point> track(){
Point p1 = tracker.getP1(); Point p1 = tracker.getP1();
Point p2 = tracker.getP2(); Point p2 = tracker.getP2();
System.out.println(p1.x);
player1.setKoords(p1.x, p1.y); player1.setKoords(p1.x, p1.y);
player2.setKoords(p2.x, p2.y); player2.setKoords(p2.x, p2.y);
List<Point> output = new ArrayList<>(); List<Point> output = new ArrayList<>();
output.set(0, p1); output.add(0, p1);
output.add(p2); output.add(1, p2);
return output; return output;
} }*/
private void draw(){ private void draw(){
graphics.drawTrail(player1.getTrail(), 0);
graphics.drawTrail(player2.getTrail(), 1);
} }
} }
+66 -24
View File
@@ -2,49 +2,91 @@ import processing.core.PApplet;
import processing.core.PImage; import processing.core.PImage;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.Queue;
public class GraphicsProgram extends PApplet { public class GraphicsProgram extends PApplet {
PImage imgBlue; private LinkedList<int[]> player1Trail = new LinkedList<>(); // Liste für Spieler 1
PImage imgRed; private LinkedList<int[]> player2Trail = new LinkedList<>(); // Liste für Spieler 2
private final int TRAIL_LENGTH = 15;
private int trailCounter = 17;
private int distanceTh = 100;
PImage img1;
PImage img2;
PImage backgroundImage;
public static void main(String[] args) { public static void main(String[] args) {
PApplet.main("GraficsProgram"); PApplet.main("GraphicsProgram");
} }
public void settings() { public void settings() {
size(800, 600); fullScreen();
imgBlue = loadImage("TrailBlue");
imgRed = loadImage("TrailRed");
} }
public void setup() {
backgroundImage = loadImage("Background.png");
backgroundImage.resize(1792, 1024);
public void drawTrail(Queue<int[]> trail, int playerID){ img1 = loadImage("TrailBlue.png");
img2 = loadImage("TrailRed.png");
}
int particleSize = 5; public void draw() {
image(backgroundImage, 0, 0); // Hintergrund zeichnen
strokeWeight(20); // Linienstärke festlegen
background(255); // Linien für Spieler 1 zeichnen
stroke(0, 0, 255); // Blau
drawTrail(player1Trail);
for (int[] koordinates : new LinkedList<>(trail)) { // Linien für Spieler 2 zeichnen
int x = koordinates[0]; stroke(255, 0, 0); // Rot
int y = koordinates[1]; drawTrail(player2Trail);
}
if(playerID == 0){ // Methode, um Linien für eine gegebene Trail-Liste zu zeichnen
image(imgBlue, x, y, particleSize, particleSize); private void drawTrail(LinkedList<int[]> trail) {
} else if (playerID == 1) { if (trail.size() < 2) return; // Mindestens 2 Punkte nötig, um Linien zu zeichnen
image(imgRed, x, y, particleSize, particleSize);
}else{ for (int i = 0; i < trail.size() - 1; i++) {
fill(0, 255, 0); int[] current = trail.get(i);
rect(x, y, particleSize, particleSize); int[] next = trail.get(i + 1);
// Null-Check für die Punkte
if (current != null && next != null) {
if(current[0]-next[0]> -distanceTh && current[0]-next[0]< distanceTh && current[1]-next[1]> -distanceTh && current[1]-next[1]< distanceTh) {
line(current[0], current[1], next[0], next[1]);
}
} }
particleSize ++;
} }
} }
public void drawEvent(){
// Methode zum Aktualisieren der Trails für beide Spieler
public void updateTrail(int x1, int y1, int x2, int y2) {
if (x1 >= 0 && y1 >= 0) {
addToTrail(player1Trail, x1, y1);
}
if (x2 >= 0 && y2 >= 0) {
addToTrail(player2Trail, x2, y2);
}
} }
}
// Methode zum Hinzufügen eines Punktes zur Trail-Liste und Begrenzung auf 20 Einträge
private void addToTrail(LinkedList<int[]> trail, int x, int y) {
if(trailCounter % 21 == 0) {
if (x >= 0 && y >= 0) {
trail.add(new int[]{x, y});
if (trail.size() > TRAIL_LENGTH) {
trail.removeFirst();
}
}
}
trailCounter++;
}
}
+157
View File
@@ -0,0 +1,157 @@
import org.opencv.core.*;
import org.opencv.videoio.VideoCapture;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;
import org.opencv.videoio.Videoio;
import processing.core.PApplet;
import java.util.*;
import java.awt.Point;
public class ImgAnalyzer {
private final int THV; // Threshold
private Point currentPositionP1 = new Point(0, 0);
private Point currentPositionP2 = new Point(0, 0);
Queue<int[]> trails = new LinkedList<>();
private final int TRAIL_LENGTH = 20;
private final CamPuffer camPuffer;
private GraphicsProgram playerGraphics;
public ImgAnalyzer(CamPuffer cP, int threshold) {
THV = threshold;
camPuffer = cP;
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
playerGraphics = new GraphicsProgram();
String[] args ={"GraphicsProgram"};
PApplet.runSketch(args, playerGraphics);
}
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
public void run() {
while (camPuffer.getCurrentMat().elemSize() == 0) {
System.out.println("Warten auf das erste Bild...");
try {
Thread.sleep(3000); // Kurze Pause, um CPU-Belastung zu vermeiden
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
Mat currentImg = new Mat();
Mat grayFrame = new Mat();
Mat thresholdFrame = new Mat();
while (true) {
try {
currentImg = camPuffer.getCurrentMat();
if(currentImg.elemSize() != 0) {
// In Graustufen konvertieren
Imgproc.cvtColor(currentImg, grayFrame, Imgproc.COLOR_BGR2GRAY);
// Threshold anwenden
Imgproc.threshold(grayFrame, thresholdFrame, THV, 255, Imgproc.THRESH_BINARY);
//Ausgabe des Bildes zum Prüfen
HighGui.imshow("ThunfischHighGui", thresholdFrame);
HighGui.waitKey(1);
//Ende Bildausgabe */
}
} catch (Exception e) {
}
if (currentImg != null) {
List<Point> positions = trackPositions(thresholdFrame);
if (positions.size() >= 2) {
currentPositionP1 = positions.get(0);
currentPositionP2 = positions.get(1);
//System.out.println("currentPositionP1: " + currentPositionP1 + " currentPositionP2: " + currentPositionP2);
}
trails.add(new int[]{currentPositionP1.x, currentPositionP1.y, currentPositionP2.x, currentPositionP2.y});
if(trails.size() > TRAIL_LENGTH){
trails.poll();
}
playerGraphics.updateTrail(currentPositionP1.x, currentPositionP1.y, currentPositionP2.x, currentPositionP2.y);
//playerGraphics.draw();
}
/*org.opencv.core.Point pp1 = new org.opencv.core.Point(currentPositionP1.x, currentPositionP1.y);
Imgproc.circle(currentImg, pp1, 10, new Scalar(255,0,0), -1);
org.opencv.core.Point pp2 = new org.opencv.core.Point(currentPositionP2.x, currentPositionP2.y);
Imgproc.circle(currentImg, pp2, 10, new Scalar(0,0,255), -1);
if(currentImg.elemSize() != 0) {
HighGui.imshow("el thunfisch", currentImg);
} */
}
}
private List<Point> trackPositions(Mat thresholdFrame) {
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
// Finde Konturen
Imgproc.findContours(thresholdFrame, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
// Liste für die Positionen und zugehörige Pixelanzahl
List<Point> positions = new ArrayList<>();
List<Double> whitePixelCounts = new ArrayList<>();
for (MatOfPoint contour : contours) {
Moments moments = Imgproc.moments(contour);
if (moments.get_m00() != 0) {
// Berechne den Mittelpunkt der Kontur
int cx = (int) (moments.get_m10() / moments.get_m00());
int cy = (int) (moments.get_m01() / moments.get_m00());
// Berechne die Anzahl der weißen Pixel in der Kontur
Mat mask = Mat.zeros(thresholdFrame.size(), CvType.CV_8UC1);
Imgproc.drawContours(mask, List.of(contour), 0, new Scalar(255), -1); // Fülle die Kontur mit Weiß
double whitePixels = Core.sumElems(mask).val[0] / 255.0; // Summe der Pixelwerte durch 255 (1 Pixel = 255)
// Speichere Position und Pixelanzahl
positions.add(new Point(cx, cy));
whitePixelCounts.add(whitePixels);
}
}
// Sortiere die Positionen basierend auf der Anzahl weißer Pixel (absteigend)
List<Point> sortedPositions = new ArrayList<>();
while (!whitePixelCounts.isEmpty()) {
int maxIndex = whitePixelCounts.indexOf(Collections.max(whitePixelCounts));
sortedPositions.add(positions.get(maxIndex));
positions.remove(maxIndex);
whitePixelCounts.remove(maxIndex);
}
// Gib die Positionen der zwei größten Konturen zurück
return sortedPositions.subList(0, Math.min(sortedPositions.size(), 2));
}
public synchronized Point getP1() {
return currentPositionP1;
}
public Point getP2() {
return currentPositionP2;
}
}
+3
View File
@@ -1,2 +1,5 @@
public class Main { public class Main {
public static void main(String[] args){
GameLoop gl = new GameLoop();
}
} }
+17 -7
View File
@@ -1,3 +1,4 @@
import java.util.Arrays;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.Queue; import java.util.Queue;
@@ -6,6 +7,8 @@ public class Player {
private final int ID; private final int ID;
private int x; private int x;
private int y; private int y;
private String name = "Thunfisch";
Queue<int[]> trail = new LinkedList<>(); Queue<int[]> trail = new LinkedList<>();
ArduinoCommunication arduinoCommunicator; ArduinoCommunication arduinoCommunicator;
@@ -18,6 +21,15 @@ public class Player {
public Player(int id, String finalIpAddress, int finalPortNr) { public Player(int id, String finalIpAddress, int finalPortNr) {
this.ID = id; this.ID = id;
arduinoCommunicator = new ArduinoCommunication(finalIpAddress, finalPortNr); arduinoCommunicator = new ArduinoCommunication(finalIpAddress, finalPortNr);
trail.add(new int[]{0,0});
}
public int getX(){
return x;
}
public int getY(){
return y;
} }
@@ -26,18 +38,16 @@ public class Player {
addToTrail(x,y); addToTrail(x,y);
this.x = x; this.x = x;
this.y = y; this.y = y;
} }
private void addToTrail(int x, int y) { private void addToTrail(int x, int y) {
this.trail.add(new int[]{x, y}); trail.add(new int[]{x, y});
if (trail.size() > TRAIL_LENGTH) {
if(trail.size() > TRAIL_LENGTH){ trail.poll(); // Entfernt das älteste Element
trail.poll();
} }
} }
public Queue<int[]> getTrail(){ public Queue<int[]> getTrail(){
return trail; return trail;
} }
-135
View File
@@ -1,135 +0,0 @@
import org.opencv.core.*;
import org.opencv.videoio.VideoCapture;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;
import org.opencv.videoio.Videoio;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Comparator;
public class Tracker {
private final int CAM = 1; // Kamera-ID (0 für Webcam, 1 für andere Cams)
private final int EXP = 0; // Belichtungszeit (idealerweise: 0)
private final int FPS = 60; // FPS
private final int THV = 250;
private Point currentPositionP1 = new Point(0, 0);
private Point currentPositionP2 = new Point(0, 0);
public Tracker() {}
public static void main(String[] args) {
Tracker tracker = new Tracker();
tracker.run();
}
private void run() {
VideoCapture capture = setUp();
if (!capture.isOpened()) {
System.out.println("Fehler: Die Webcam konnte nicht geöffnet werden.");
return;
}
Mat frame = new Mat();
Mat grayFrame = new Mat();
Mat thresholdFrame = new Mat();
while (true) {
if (capture.read(frame)) {
// Konvertiere in Graustufen und wende Threshold an
Imgproc.cvtColor(frame, grayFrame, Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(grayFrame, thresholdFrame, THV, 255, Imgproc.THRESH_BINARY);
// Tracke die Positionen der beiden größten Objekte
List<Point> positions = trackPositions(thresholdFrame);
if (positions.size() >= 2) {
currentPositionP1 = positions.get(0);
currentPositionP2 = positions.get(1);
System.out.println("P1 - X: " + currentPositionP1.x + " Y: " + currentPositionP1.y + " P2 - X: " + currentPositionP2.x + " Y: " + currentPositionP2.y);
}
drawMarkers(frame);
HighGui.imshow("GTCar", frame);
if (HighGui.waitKey(1) == 27) {
break;
}
} else {
System.out.println("Fehler: Das Kamerabild konnte nicht gelesen werden.");
break;
}
}
}
private List<Point> trackPositions(Mat thresholdFrame) {
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
// Finde Konturen
Imgproc.findContours(thresholdFrame, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
// Sortiere Konturen nach Fläche (absteigend)
contours.sort((c1, c2) -> Double.compare(Imgproc.contourArea(c2), Imgproc.contourArea(c1)));
// Speichere die Positionen der zwei größten Konturen
List<Point> positions = new ArrayList<>();
for (int i = 0; i < Math.min(contours.size(), 2); i++) {
Moments moments = Imgproc.moments(contours.get(i));
if (moments.get_m00() != 0) {
int cx = (int) (moments.get_m10() / moments.get_m00());
int cy = (int) (moments.get_m01() / moments.get_m00());
positions.add(new Point(cx, cy));
}
}
return positions;
}
private void drawMarkers(Mat frame) {
// Größe der Quadrate
int size = 10;
// Blaues Quadrat an currentPositionP1
if (currentPositionP1 != null) {
Point topLeftP1 = new Point(currentPositionP1.x - size, currentPositionP1.y - size);
Point bottomRightP1 = new Point(currentPositionP1.x + size, currentPositionP1.y + size);
Imgproc.rectangle(frame, topLeftP1, bottomRightP1, new Scalar(255, 0, 0), -1); // Blau, gefüllt
}
// Rotes Quadrat an currentPositionP2
if (currentPositionP2 != null) {
Point topLeftP2 = new Point(currentPositionP2.x - size, currentPositionP2.y - size);
Point bottomRightP2 = new Point(currentPositionP2.x + size, currentPositionP2.y + size);
Imgproc.rectangle(frame, topLeftP2, bottomRightP2, new Scalar(0, 0, 255), -1); // Rot, gefüllt
}
}
private VideoCapture setUp() {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture capture = new VideoCapture(CAM);
if (!capture.isOpened()) {
System.out.println("Fehler: Die Webcam konnte nicht geöffnet werden.");
}
capture.set(Videoio.CAP_PROP_EXPOSURE, EXP);
capture.set(Videoio.CAP_PROP_FPS, FPS);
return capture;
}
}