Agrarsense
TreeHeightsFromImage.cpp
Go to the documentation of this file.
1// Copyright (c) 2024 FrostBit Software Lab at the Lapland University of Applied Sciences
2//
3// This work is licensed under the terms of the MIT license.
4// For a copy, see <https://opensource.org/licenses/MIT>.
5
7
9{
10 PrimaryActorTick.bCanEverTick = false;
11}
12
14{
15 Super::BeginPlay();
16
17#if WITH_EDITOR
18 if (treeMapImage)
19 {
20 // Lock the texture to allow access to data
21 FTexture2DMipMap& Mip = treeMapImage->GetPlatformData()->Mips[0];
22 void* Data = Mip.BulkData.Lock(LOCK_READ_ONLY);
23
24 if (Data)
25 {
26 int32 Width = treeMapImage->GetSizeX();
27 int32 Height = treeMapImage->GetSizeY();
28
29 if (Width <= 0 || Height <= 0)
30 return;
31
32 UE_LOG(LogTemp, Warning, TEXT("Image width: %i, Height: %i"), Width, Height);
33
34 uint8* Pixels = static_cast<uint8*>(Data);
35 for (int32 y = 0; y < Height; y++)
36 {
37 for (int32 x = 0; x < Width; x++)
38 {
39 int32 Index = (y * Width + x) * 4; // 4 bytes per pixel (RGBA)
40 uint8 R = Pixels[Index];
41 uint8 G = Pixels[Index + 1];
42 uint8 B = Pixels[Index + 2];
43 uint8 A = Pixels[Index + 3];
44
45 FColor pixelColor = FColor(B, G, R);
46
47 if (x == 446 && y == 353)
48 {
49 UE_LOG(LogTemp, Warning, TEXT("Coordinates RGB = %i, %i, %i"), B, G, R);
50 FColor ClosestColor = FindClosestColor(pixelColor, colorHeight);
51 UE_LOG(LogTemp, Warning, TEXT("Closest color: R=%d, G=%d, B=%d"), ClosestColor.R, ClosestColor.G, ClosestColor.B);
52
53 for (const auto& Pair : colorHeight)
54 {
55 if (Pair.Value == ClosestColor)
56 UE_LOG(LogTemp, Warning, TEXT("This should be a %im size tree"), Pair.Key);
57 }
58
59 }
60
61 if (x == Width / 2 && y == Height / 2)
62 {
63 UE_LOG(LogTemp, Warning, TEXT("Coordinates middlepoint Width: %i, Height: %i"), x, y);
64 //UE_LOG(LogTemp, Warning, TEXT("ARGB: %i,%i,%i,%i"), A,R,G,B);
65 }
66 }
67 }
68
69 // Unlock the texture
70 Mip.BulkData.Unlock();
71 }
72 }
73#endif
74}
75
76float ATreeHeightsFromImage::EuclideanDistance(const FColor& Color1, const FColor& Color2)
77{
78 float R1 = Color1.R;
79 float G1 = Color1.G;
80 float B1 = Color1.B;
81 float R2 = Color2.R;
82 float G2 = Color2.G;
83 float B2 = Color2.B;
84 return FMath::Sqrt(FMath::Square(R2 - R1) + FMath::Square(G2 - G1) + FMath::Square(B2 - B1));
85}
86
87FColor ATreeHeightsFromImage::FindClosestColor(const FColor& TargetColor, const TMap<int32, FColor>& ColorMap)
88{
89 float MinDistance = FLT_MAX;
90 FColor ClosestColor;
91
92 for (const auto& Pair : ColorMap)
93 {
94 float Distance = EuclideanDistance(TargetColor, Pair.Value);
95 if (Distance < MinDistance)
96 {
97 MinDistance = Distance;
98 ClosestColor = Pair.Value;
99 }
100 }
101
102 return ClosestColor;
103}
const TMap< int, FColor > colorHeight
virtual void BeginPlay() override
FColor FindClosestColor(const FColor &TargetColor, const TMap< int32, FColor > &ColorMap)
float EuclideanDistance(const FColor &Color1, const FColor &Color2)