Add project files.

This commit is contained in:
whoswhip
2025-06-16 19:10:19 -04:00
parent 34ba7f9a5f
commit f21fb431e9
6 changed files with 696 additions and 0 deletions
+246
View File
@@ -0,0 +1,246 @@
using OpenCvSharp;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Spectrum
{
public static class AutoLabeling
{
private static int imageCount = 0;
private static int detectionAttemps = 0;
private static readonly object lockObject = new object();
private static CancellationTokenSource? cancellationTokenSource;
private static Task? backgroundTask;
private static readonly ConcurrentQueue<LabelingData> labelingQueue = new ConcurrentQueue<LabelingData>();
private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new ConcurrentQueue<BackgroundImageData>();
private static List<YoloBoundingBox> GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight)
{
var boundingBoxes = new List<YoloBoundingBox>();
foreach (var contour in contours)
{
if (contour.Length < 3) continue; // probably not an actual enemy
int minX = contour.Min(p => p.X);
int minY = contour.Min(p => p.Y);
int maxX = contour.Max(p => p.X);
int maxY = contour.Max(p => p.Y);
double centerX = (minX + maxX) / 2.0;
double centerY = (minY + maxY) / 2.0;
double width = maxX - minX;
double height = maxY - minY;
boundingBoxes.Add(new YoloBoundingBox
{
ClassId = 0,
CenterX = centerX / imageWidth,
CenterY = centerY / imageHeight,
Width = width / imageWidth,
Height = height / imageHeight,
PixelMinX = minX,
PixelMinY = minY,
PixelMaxX = maxX,
PixelMaxY = maxY
});
}
return boundingBoxes;
}
private static void SaveLabels(string path, List<YoloBoundingBox> boundingBoxes)
{
try
{
var labelContent = new StringBuilder();
foreach (var box in boundingBoxes)
{
labelContent.AppendLine($"{box.ClassId} {box.CenterX} {box.CenterY} {box.Width} {box.Height}");
}
File.WriteAllText(path, labelContent.ToString());
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Failed to save labels to " + path);
Console.ResetColor();
}
}
private static void SaveMatAsImage(Mat mat, string path)
{
try
{
Cv2.ImWrite(path, mat);
}
catch (Exception ex)
{
Console.WriteLine($"Error saving image: {ex.Message}");
}
}
private static async Task LabelingLoop(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
if (labelingQueue.TryDequeue(out LabelingData? data))
{
try
{
await ProcessImageAsync(data);
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Failed to process labeling data.");
Console.ResetColor();
}
}
if (backgroundQueue.TryDequeue(out BackgroundImageData? backgroundData))
{
try
{
await ProcessBackgroundImageAsync(backgroundData);
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Failed to process background image data.");
Console.ResetColor();
}
}
await Task.Delay(10, cancellationToken);
}
}
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
{
if (!Config.AutoLabel || filteredContours.Length == 0)
return;
Mat clone = mat.Clone();
labelingQueue.Enqueue(new LabelingData
{
Mat = clone,
Bounds = bounds,
FilteredContours = filteredContours
});
}
public static void AddBackgroundImage(Mat mat, bool detected)
{
if (!Config.AutoLabel)
return;
detectionAttemps++;
if (detectionAttemps < Config.BackgroundImageInterval || detected)
return;
Mat clone = mat.Clone();
backgroundQueue.Enqueue(new BackgroundImageData
{
Mat = clone
});
}
private static async Task ProcessImageAsync(LabelingData data)
{
await Task.Run(() =>
{
try
{
var boundingBoxes = GetBoundingBoxes(data.FilteredContours, data.Mat.Width, data.Mat.Height);
if (boundingBoxes.Count == 0)
return;
lock (lockObject)
{
string imageFileName = $"image_{imageCount:D6}.jpg";
string labelFileName = $"image_{imageCount:D6}.txt";
string imagePath = Path.Combine("dataset/images", imageFileName);
string labelPath = Path.Combine("dataset/labels", labelFileName);
SaveMatAsImage(data.Mat, imagePath);
SaveLabels(labelPath, boundingBoxes);
imageCount++;
}
}
finally
{
data.Mat?.Dispose();
}
});
}
private static async Task ProcessBackgroundImageAsync(BackgroundImageData data)
{
await Task.Run(() =>
{
try
{
lock (lockObject)
{
string imageFileName = $"image_{imageCount:D6}.jpg";
string imagePath = Path.Combine("dataset/images", imageFileName);
SaveMatAsImage(data.Mat, imagePath);
imageCount++;
}
}
finally
{
data.Mat?.Dispose();
}
});
}
public static void StartLabeling()
{
if (cancellationTokenSource != null)
return;
cancellationTokenSource = new CancellationTokenSource();
backgroundTask = Task.Run(() => LabelingLoop(cancellationTokenSource.Token));
}
public static void StopLabeling()
{
if (cancellationTokenSource == null)
return;
cancellationTokenSource.Cancel();
backgroundTask?.Wait();
cancellationTokenSource.Dispose();
cancellationTokenSource = null;
backgroundTask = null;
}
public class YoloBoundingBox
{
public int ClassId { get; set; }
public double CenterX { get; set; }
public double CenterY { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public int PixelMinX { get; set; }
public int PixelMinY { get; set; }
public int PixelMaxX { get; set; }
public int PixelMaxY { get; set; }
}
public class LabelingData
{
public Mat Mat { get; set; } = null!;
public Rectangle Bounds { get; set; }
public OpenCvSharp.Point[][] FilteredContours { get; set; } = null!;
}
public class BackgroundImageData
{
public Mat Mat { get; set; } = null!;
}
}
}
+148
View File
@@ -0,0 +1,148 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenCvSharp;
namespace Spectrum
{
public static class Config
{
#region Variables
public static int ImageWidth { get; set; } = 640;
public static int ImageHeight { get; set; } = 640;
public static double YOffsetPercent { get; set; } = 0.8;
public static double XOffsetPercent { get; set; } = 0.5;
public static bool EnableAim { get; set; } = true;
public static bool ClosestToMouse { get; set; } = true; // if false it will use the center of the screen
public static int Keybind { get; set; } = 0x06; // first side button on mouse
public static double Sensitivity { get; set; } = 0.5;
public static bool ShowDetectionWindow { get; set; } = true;
public static bool CollectData { get; set; } = false;
public static bool AutoLabel { get; set; } = false; // collect data needs to be enabled
public static int BackgroundImageInterval { get; set; } = 10; // after 10 loops with no detection, save a background image
public static Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229);
public static Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229);
#endregion
public static void LoadConfig(bool silent = false)
{
if (File.Exists("config.json"))
{
string config_content = File.ReadAllText("config.json");
try
{
var config = JObject.Parse(config_content);
ImageWidth = config["ImageWidth"]?.Value<int>() ?? ImageWidth;
ImageHeight = config["ImageHeight"]?.Value<int>() ?? ImageHeight;
YOffsetPercent = config["YOffsetPercent"]?.Value<double>() ?? YOffsetPercent;
XOffsetPercent = config["XOffsetPercent"]?.Value<double>() ?? XOffsetPercent;
EnableAim = config["EnableAim"]?.Value<bool>() ?? EnableAim;
ClosestToMouse = config["ClosestToMouse"]?.Value<bool>() ?? ClosestToMouse;
Keybind = config["Keybind"]?.Value<int>() ?? Keybind;
Sensitivity = config["Sensitivity"]?.Value<double>() ?? Sensitivity;
ShowDetectionWindow = config["ShowDetectionWindow"]?.Value<bool>() ?? ShowDetectionWindow;
CollectData = config["CollectData"]?.Value<bool>() ?? CollectData;
AutoLabel = config["AutoLabel"]?.Value<bool>() ?? AutoLabel;
BackgroundImageInterval = config["BackgroundImageInterval"]?.Value<int>() ?? BackgroundImageInterval;
UpperHSV = config["UpperHSV"]?.ToObject<Scalar>() ?? UpperHSV;
LowerHSV = config["LowerHSV"]?.ToObject<Scalar>() ?? LowerHSV;
if (ImageWidth <= 0 || ImageHeight <= 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Invalid image dimensions in config.json, using default values.");
Console.ResetColor();
ImageWidth = 640;
ImageHeight = 640;
}
if (YOffsetPercent < 0 || YOffsetPercent > 1 || XOffsetPercent < 0 || XOffsetPercent > 1)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Invalid offset percentages in config.json, using default values.");
Console.ResetColor();
YOffsetPercent = 0.8;
XOffsetPercent = 0.5;
}
if (Keybind < 0 || Keybind > 255)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Invalid keybind in config.json, using default value.");
Console.ResetColor();
Keybind = 0x06;
}
if (Sensitivity < 0 || Sensitivity > 1)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Invalid sensitivity in config.json, using default value.");
Console.ResetColor();
Sensitivity = 0.5;
}
if (AutoLabel && !CollectData )
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[WARNING] AutoLabel is enabled but CollectData is not. Disabling AutoLabel.");
Console.ResetColor();
AutoLabel = false;
}
if (BackgroundImageInterval <= 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Invalid BackgroundImageInterval in config.json, using default value.");
Console.ResetColor();
}
SaveConfig();
if (!silent)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Configuration loaded successfully.");
Console.ResetColor();
}
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Error parsing config.json, using default values.");
Console.ResetColor();
SaveConfig();
}
}
else
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[WARNING] config.json not found, using default values.");
Console.ResetColor();
SaveConfig();
}
}
public static void SaveConfig()
{
var config = new JObject
{
["ImageWidth"] = ImageWidth,
["ImageHeight"] = ImageHeight,
["YOffsetPercent"] = YOffsetPercent,
["XOffsetPercent"] = XOffsetPercent,
["EnableAim"] = EnableAim,
["ClosestToMouse"] = ClosestToMouse,
["Keybind"] = Keybind,
["Sensitivity"] = Sensitivity,
["ShowDetectionWindow"] = ShowDetectionWindow,
["CollectData"] = CollectData,
["AutoLabel"] = AutoLabel,
["BackgroundImageInterval"] = BackgroundImageInterval,
["UpperHSV"] = JToken.FromObject(UpperHSV),
["LowerHSV"] = JToken.FromObject(LowerHSV)
};
File.WriteAllText("config.json", config.ToString(Formatting.Indented));
}
}
}
+61
View File
@@ -0,0 +1,61 @@
using System.Drawing;
using System.Runtime.InteropServices;
namespace Spectrum
{
public static class InputManager
{
[DllImport("user32.dll")]
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
[DllImport("user32.dll")]
private static extern bool GetCursorPos(out POINT lpPoint);
private struct POINT
{
public int X;
public int Y;
}
// AIMMY V2 CODE - https://github.com/babyhamsta/Aimmy/blob/Aimmy-V2/Aimmy2/InputLogic/MouseManager.cs Line 34 - 50
private static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t)
{
double u = 1 - t;
double tt = t * t;
double uu = u * u;
double x = uu * u * start.X + 3 * uu * t * control1.X + 3 * u * tt * control2.X + tt * t * end.X;
double y = uu * u * start.Y + 3 * uu * t * control1.Y + 3 * u * tt * control2.Y + tt * t * end.Y;
return new Point((int)x, (int)y);
}
public static void MoveMouse(Point target)
{
POINT reference = new POINT();
if (Config.ClosestToMouse)
{
GetCursorPos(out reference);
}
else
{
// center of the screen
reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
}
Point start = new Point(reference.X, reference.Y);
Point end = new Point(target.X, target.Y);
Point control1 = new(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3);
Point control2 = new(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3);
Point newPosition = CubicBezier(start, end, control1, control2, Config.Sensitivity);
int deltaX = newPosition.X - reference.X;
int deltaY = newPosition.Y - reference.Y;
mouse_event(0x0001, (uint)(deltaX), (uint)(deltaY), 0, 0);
}
}
}
+195
View File
@@ -0,0 +1,195 @@
using OpenCvSharp;
using OpenCvSharp.Internal.Vectors;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace Spectrum
{
class Program
{
static Rectangle bounds = new Rectangle(0, 0, 0, 0);
static void Main()
{
Config.LoadConfig();
var screenSize = SystemHelper.GetPrimaryScreenSize();
bounds = new Rectangle(
(screenSize.Width - Config.ImageWidth) / 2,
(screenSize.Height - Config.ImageHeight) / 2,
Config.ImageWidth,
Config.ImageHeight
);
if (Config.ShowDetectionWindow)
{
Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize);
Cv2.WaitKey(1);
}
if (Config.AutoLabel)
{
AutoLabeling.StartLabeling();
}
Directory.CreateDirectory("dataset");
Directory.CreateDirectory("dataset/images");
Directory.CreateDirectory("dataset/labels");
while (true)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true).Key;
if (key == ConsoleKey.Escape)
{
if (Config.ShowDetectionWindow)
{
Cv2.DestroyAllWindows();
}
}
else if (key == ConsoleKey.F5 || key == ConsoleKey.R)
{
Config.LoadConfig(true);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Configuration reloaded.");
Console.ResetColor();
}
}
if (SystemHelper.GetAsyncKeyState(Config.Keybind) < 0)
{
var screenshot = CaptureScreenshot(bounds);
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
Mat drawing = mat.Clone(); // clone for drawing
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV); // convert to hsv
Cv2.InRange(mat, Config.LowerHSV, Config.UpperHSV, mat); // apply mask
Cv2.Dilate(mat, mat, null, iterations: 2); // dilate to fill gaps
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary); // threshold to binary
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 100).ToArray();
if (filteredContours.Length > 0)
{
int refX = bounds.X + bounds.Width / 2;
int refY = bounds.Y + (int)(bounds.Height * Config.YOffsetPercent);
double minDist = double.MaxValue;
OpenCvSharp.Point[]? closestContour = null;
int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0;
foreach (var contour in filteredContours)
{
int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
foreach (var point in contour)
{
if (point.X < minX) minX = point.X;
if (point.Y < minY) minY = point.Y;
if (point.X > maxX) maxX = point.X;
if (point.Y > maxY) maxY = point.Y;
}
int centerX = (minX + maxX) / 2;
int centerY = (minY + maxY) / 2;
int absCenterX = centerX + bounds.X;
int absCenterY = centerY + bounds.Y;
double dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2));
if (dist < minDist)
{
minDist = dist;
closestContour = contour;
bestMinX = minX;
bestMinY = minY;
bestMaxX = maxX;
bestMaxY = maxY;
}
}
if (closestContour != null)
{
int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - Config.XOffsetPercent));
int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - Config.YOffsetPercent));
int targetX = groupX + bounds.X;
int targetY = groupY + bounds.Y;
if (Config.AutoLabel)
{
AutoLabeling.AddToQueue(drawing, bounds, filteredContours);
AutoLabeling.AddBackgroundImage(drawing, true);
}
if (Config.EnableAim)
{
InputManager.MoveMouse(new System.Drawing.Point(targetX, targetY));
}
if (Config.ShowDetectionWindow)
{
Cv2.DrawContours(drawing, filteredContours, -1, Scalar.Red, 2);
Cv2.Rectangle(drawing, new OpenCvSharp.Point(bestMinX, bestMinY), new OpenCvSharp.Point(bestMaxX, bestMaxY), Scalar.Blue, 2);
Cv2.ImShow("Spectrum Detection", drawing);
Cv2.WaitKey(1);
}
}
}
else if (Config.ShowDetectionWindow)
{
Cv2.ImShow("Spectrum Detection", drawing);
Cv2.WaitKey(1);
}
}
else
{
if (Config.ShowDetectionWindow)
{
Cv2.WaitKey(1);
}
else
{
Thread.Sleep(1);
}
}
}
}
public static Bitmap CaptureScreenshot(Rectangle bounds)
{
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(bounds.Location, System.Drawing.Point.Empty, bounds.Size);
}
return bitmap;
}
}
public static class SystemHelper
{
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int nIndex);
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private const int SM_XVIRTUALSCREEN = 76;
private const int SM_YVIRTUALSCREEN = 77;
private const int SM_CXVIRTUALSCREEN = 78;
private const int SM_CYVIRTUALSCREEN = 79;
public static (int Width, int Height) GetPrimaryScreenSize()
{
return (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
}
public static (int X, int Y, int Width, int Height) GetVirtualScreenBounds()
{
return (
GetSystemMetrics(SM_XVIRTUALSCREEN),
GetSystemMetrics(SM_YVIRTUALSCREEN),
GetSystemMetrics(SM_CXVIRTUALSCREEN),
GetSystemMetrics(SM_CYVIRTUALSCREEN)
);
}
}
}
+21
View File
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="OpenCvSharp4" Version="4.11.0.20250507" />
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.11.0.20250507" />
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.11.0.20250507" />
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
<PackageReference Include="System.Drawing.Common" Version="9.0.6" />
</ItemGroup>
</Project>
+25
View File
@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36203.30 d17.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spectrum", "ConsoleApp1\Spectrum.csproj", "{96A01B58-894F-4DFB-97D9-49563FD4BB75}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Debug|Any CPU.Build.0 = Debug|Any CPU
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Release|Any CPU.ActiveCfg = Release|Any CPU
{96A01B58-894F-4DFB-97D9-49563FD4BB75}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C822A282-1513-4D67-98A0-9FE52932E13C}
EndGlobalSection
EndGlobal