使用C++编写一个UE5的actor蓝图中可用的节点功能是根据输入的图片逐像素读取灰度并将灰度值输出到一个数组请提供完整的cpp和头文件代码
以下是一个简单的实现:
MyActor.h:
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyActor.generated.h"
UCLASS()
class MYPROJECT_API AMyActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AMyActor();
// Called every frame
virtual void Tick(float DeltaTime) override;
// Input image to read from
UPROPERTY(EditAnywhere, Category = "MyActor")
UTexture2D* InputImage;
// Output array to store grayscale values
UPROPERTY(BlueprintReadOnly, Category = "MyActor")
TArray<float> GrayscaleValues;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
private:
// Helper function to convert color to grayscale
float ConvertToGrayscale(FColor Color) const;
};
MyActor.cpp:
#include "MyActor.h"
#include "Engine/Texture2D.h"
#include "Engine/TextureRenderTarget2D.h"
#include "Engine/TextureRenderTarget.h"
// Sets default values
AMyActor::AMyActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Initialize input image and output array
InputImage = nullptr;
GrayscaleValues.Empty();
}
// Called when the game starts or when spawned
void AMyActor::BeginPlay()
{
Super::BeginPlay();
// Check if input image is valid
if (InputImage)
{
// Get the texture size
const int32 Width = InputImage->GetSizeX();
const int32 Height = InputImage->GetSizeY();
// Lock the texture data for reading
FColor* TextureData = static_cast<FColor*>(InputImage->PlatformData->Mips[0].BulkData.LockReadOnly());
// Iterate over each pixel and convert to grayscale
for (int32 Y = 0; Y < Height; ++Y)
{
for (int32 X = 0; X < Width; ++X)
{
// Get the color value at this pixel
const FColor Color = TextureData[Y * Width + X];
// Convert to grayscale and add to the output array
const float GrayscaleValue = ConvertToGrayscale(Color);
GrayscaleValues.Add(GrayscaleValue);
}
}
// Unlock the texture data
InputImage->PlatformData->Mips[0].BulkData.Unlock();
}
}
// Called every frame
void AMyActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Helper function to convert color to grayscale
float AMyActor::ConvertToGrayscale(FColor Color) const
{
const float Red = static_cast<float>(Color.R);
const float Green = static_cast<float>(Color.G);
const float Blue = static_cast<float>(Color.B);
const float GrayscaleValue = 0.2989f * Red + 0.5870f * Green + 0.1140f * Blue;
return GrayscaleValue;
}
在UE5的蓝图中,您可以将此Actor作为一个组件来使用,并且可以通过蓝图实现访问InputImage和GrayscaleValues属性。
原文地址: https://www.cveoy.top/t/topic/bMjX 著作权归作者所有。请勿转载和采集!