Compare commits

19 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
Paul-1108 505b58e8e8 Version 1 des Gameloop und Logic
noch nicht voll fiunktionsfähig
4.12.24 16:19
2024-12-04 16:21:13 +01:00
Paul-1108 95fb97f847 Version 1 des Gameloop und Logic
noch nicht voll fiunktionsfähig
4.12.24 16:19
2024-12-04 16:19:33 +01:00
moeckelda95243 c5e0dec777 Version 27.11 ("neuer" Tracker) 2024-11-27 17:05:33 +01:00
moeckelda95243 c2b5dc7e96 Version 27.11 ("fertiger" Tracker) 2024-11-27 12:16:48 +01:00
Paul-1108 40229f479a Communication
GameLoop
Player
2024-11-27 12:08:41 +01:00
moeckelda95243 6bdf666188 Version 27.11 2024-11-27 11:25:00 +01:00
moeckelda95243 bd78af3b48 Version 23.11 (Grafics update) 2024-11-23 14:28:40 +01:00
moeckelda95243 c6f1afc206 Version 20.11 2024-11-20 17:06:36 +01:00
Paul-1108 93e39b11e3 Grundstrukur 2024-11-20 15:48:53 +01:00
15 changed files with 770 additions and 38 deletions
+132 -22
View File
@@ -4,7 +4,13 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="4d75e996-cee4-4ec6-b802-5b56d0c0eac4" name="Changes" comment="First Commit Test" />
<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$/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>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
@@ -20,32 +26,78 @@
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="ProjectColorInfo"><![CDATA[{
"associatedIndex": 8
}]]></component>
<component name="ProjectColorInfo">{
&quot;associatedIndex&quot;: 8
}</component>
<component name="ProjectId" id="2p7Eq8ZJM8BEjLybOnAdhzZ82uv" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RunOnceActivity.ShowReadmeOnStart": "true",
"com.codeium.enabled": "true",
"git-widget-placeholder": "master",
"kotlin-language-version-configured": "true",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"project.structure.last.edited": "Project",
"project.structure.proportion": "0.15",
"project.structure.side.proportion": "0.0",
"vue.rearranger.settings.migration": "true"
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;Application.GTCar.executor&quot;: &quot;Run&quot;,
&quot;Application.GraphicsProgram.executor&quot;: &quot;Run&quot;,
&quot;Application.Main.executor&quot;: &quot;Run&quot;,
&quot;Application.Tracker.executor&quot;: &quot;Run&quot;,
&quot;Downloaded.Files.Path.Enabled&quot;: &quot;false&quot;,
&quot;Repository.Attach.Annotations&quot;: &quot;false&quot;,
&quot;Repository.Attach.JavaDocs&quot;: &quot;false&quot;,
&quot;Repository.Attach.Sources&quot;: &quot;false&quot;,
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;com.codeium.enabled&quot;: &quot;true&quot;,
&quot;git-widget-placeholder&quot;: &quot;master&quot;,
&quot;kotlin-language-version-configured&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;C:/Users/david/Documents/Uni/GTCar/opencv/build/java/opencv-4100.jar&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
&quot;project.structure.last.edited&quot;: &quot;Libraries&quot;,
&quot;project.structure.proportion&quot;: &quot;0.15&quot;,
&quot;project.structure.side.proportion&quot;: &quot;0.24022989&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
}
}]]></component>
}</component>
<component name="RunManager" selected="Application.Main">
<configuration name="GTCar" type="Application" factoryName="Application">
<option name="MAIN_CLASS_NAME" value="Tracker" />
<module name="GTCar_V2_maven" />
<option name="VM_PARAMETERS" value="-Djava.library.path=C:\Users\david\Documents\Uni\GTCar\opencv\build\java\x64" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</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>
@@ -63,6 +115,10 @@
<option name="presentableId" value="Default" />
<updated>1732108904989</updated>
<workItem from="1732108906083" duration="758000" />
<workItem from="1732113837570" duration="20534000" />
<workItem from="1733327375447" duration="951000" />
<workItem from="1734091457440" duration="10746000" />
<workItem from="1734364915397" duration="9202000" />
</task>
<task id="LOCAL-00001" summary="First Commit Test">
<option name="closed" value="true" />
@@ -72,7 +128,55 @@
<option name="project" value="LOCAL" />
<updated>1732109548353</updated>
</task>
<option name="localTasksCounter" value="2" />
<task id="LOCAL-00002" summary="Version 20.11">
<option name="closed" value="true" />
<created>1732118799936</created>
<option name="number" value="00002" />
<option name="presentableId" value="LOCAL-00002" />
<option name="project" value="LOCAL" />
<updated>1732118799936</updated>
</task>
<task id="LOCAL-00003" summary="Version 23.11 (Grafics update)">
<option name="closed" value="true" />
<created>1732368525825</created>
<option name="number" value="00003" />
<option name="presentableId" value="LOCAL-00003" />
<option name="project" value="LOCAL" />
<updated>1732368525826</updated>
</task>
<task id="LOCAL-00004" summary="Version 27.11">
<option name="closed" value="true" />
<created>1732703104268</created>
<option name="number" value="00004" />
<option name="presentableId" value="LOCAL-00004" />
<option name="project" value="LOCAL" />
<updated>1732703104268</updated>
</task>
<task id="LOCAL-00005" summary="Version 27.11 (&quot;fertiger&quot; Tracker)">
<option name="closed" value="true" />
<created>1732706211714</created>
<option name="number" value="00005" />
<option name="presentableId" value="LOCAL-00005" />
<option name="project" value="LOCAL" />
<updated>1732706211714</updated>
</task>
<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 />
</component>
<component name="TypeScriptGeneratedFilesManager">
@@ -91,6 +195,12 @@
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="First Commit Test" />
<option name="LAST_COMMIT_MESSAGE" value="First Commit Test" />
<MESSAGE value="Version 20.11" />
<MESSAGE value="Version 23.11 (Grafics update)" />
<MESSAGE value="Version 27.11" />
<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>
</project>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

-9
View File
@@ -14,13 +14,4 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>nu.pattern</groupId>
<artifactId>opencv</artifactId>
<version>2.4.9-4</version>
</dependency>
</dependencies>
</project>
+34
View File
@@ -0,0 +1,34 @@
import com.illposed.osc.OSCMessage;
import com.illposed.osc.transport.OSCPortOut;
import java.net.InetAddress;
import java.util.Arrays;
public class ArduinoCommunication {
private InetAddress address;
private int port;
private OSCPortOut oscPortOut;
public ArduinoCommunication(String ipAdress, int portNr) {
try{
address = InetAddress.getByName(ipAdress);
port = portNr;
oscPortOut = new OSCPortOut(address, port);
}
catch (Exception e){
e.printStackTrace();
}
}
public void sendMessage(int a, double x, double y){
String oscAddress = "/arduino/command"; // OSC-Adresse für die Nachricht
OSCMessage message = new OSCMessage(oscAddress, Arrays.asList(a, x, y));
try {
oscPortOut.send(message);
}
catch (Exception e){
e.printStackTrace();
}
System.out.println("OSC Nachricht gesendet: " + message);
}
}
-2
View File
@@ -1,2 +0,0 @@
public class ArduinoCommunicator {
}
+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;
}
}
+59 -1
View File
@@ -1,2 +1,60 @@
public class GameLogic {
import processing.core.PApplet;
import java.awt.*;
import java.util.LinkedList;
import java.util.Queue;
public class GameLogic extends PApplet {
public static void main(String[] args) {
PApplet.main("GameLogic");
}
private static final int MAX_TRAIL_SIZE = 100; // Maximale Größe des Trails
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
}
}
+100
View File
@@ -0,0 +1,100 @@
import processing.core.PApplet;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
public class GameLoop {
int activePlayer = 0;
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;
GameLogic gl;
Player player1;
Player player2;
public GameLoop(){
player1 = new Player(0, "192.168.1.1", 9000);
player2 = new Player(1, "192.168.1.2", 9000);
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"};
PApplet.runSketch(args, graphics);
gl = new GameLogic();
String[] args_ = {"GameLogic"};
PApplet.runSketch(args_, gl); */
run();
}
private void run(){
while(true){
//communicate();
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;
}
if(gl.doCheckExtern(player1.getTrail(), p2)){ //Check Position von P2 mit Spur von P1
System.out.println("Spieler 2 hat verloren");
break;
} */
//draw();
try{
wait(50);
}
catch (Exception e){
}
}
}
private void communicate() {
//offen für Auto Kommunikation
}
/*private List<Point> track(){
Point p1 = tracker.getP1();
Point p2 = tracker.getP2();
System.out.println(p1.x);
player1.setKoords(p1.x, p1.y);
player2.setKoords(p2.x, p2.y);
List<Point> output = new ArrayList<>();
output.add(0, p1);
output.add(1, p2);
return output;
}*/
private void draw(){
}
}
+91 -1
View File
@@ -1,2 +1,92 @@
public class GraphicsProgram {
import processing.core.PApplet;
import processing.core.PImage;
import java.util.LinkedList;
public class GraphicsProgram extends PApplet {
private LinkedList<int[]> player1Trail = new LinkedList<>(); // Liste für Spieler 1
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) {
PApplet.main("GraphicsProgram");
}
public void settings() {
fullScreen();
}
public void setup() {
backgroundImage = loadImage("Background.png");
backgroundImage.resize(1792, 1024);
img1 = loadImage("TrailBlue.png");
img2 = loadImage("TrailRed.png");
}
public void draw() {
image(backgroundImage, 0, 0); // Hintergrund zeichnen
strokeWeight(20); // Linienstärke festlegen
// Linien für Spieler 1 zeichnen
stroke(0, 0, 255); // Blau
drawTrail(player1Trail);
// Linien für Spieler 2 zeichnen
stroke(255, 0, 0); // Rot
drawTrail(player2Trail);
}
// Methode, um Linien für eine gegebene Trail-Liste zu zeichnen
private void drawTrail(LinkedList<int[]> trail) {
if (trail.size() < 2) return; // Mindestens 2 Punkte nötig, um Linien zu zeichnen
for (int i = 0; i < trail.size() - 1; i++) {
int[] current = trail.get(i);
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]);
}
}
}
}
// 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 static void main(String[] args){
GameLoop gl = new GameLoop();
}
}
+64
View File
@@ -1,2 +1,66 @@
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class Player {
// Attribute für die x- und y-Koordinaten
private final int ID;
private int x;
private int y;
private String name = "Thunfisch";
Queue<int[]> trail = new LinkedList<>();
ArduinoCommunication arduinoCommunicator;
private final int TRAIL_LENGTH = 30;
// Konstruktor
public Player(int id, String finalIpAddress, int finalPortNr) {
this.ID = id;
arduinoCommunicator = new ArduinoCommunication(finalIpAddress, finalPortNr);
trail.add(new int[]{0,0});
}
public int getX(){
return x;
}
public int getY(){
return y;
}
//fügt 2 Koordinaten zum Trail hinzu nd verhindert, dass dieser zulang wird
public void setKoords(int x, int y){
addToTrail(x,y);
this.x = x;
this.y = y;
}
private void addToTrail(int x, int y) {
trail.add(new int[]{x, y});
if (trail.size() > TRAIL_LENGTH) {
trail.poll(); // Entfernt das älteste Element
}
}
public Queue<int[]> getTrail(){
return trail;
}
public void sendToCar(int light, double steer, double speed){
arduinoCommunicator.sendMessage(light, steer, speed);
}
//gibt aktuelle Position aus
public void printPosition() {
System.out.println(trail);
}
}
-2
View File
@@ -1,2 +0,0 @@
public class Tracker {
}