3
0

Histogram.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <Atom/ImageProcessing/PixelFormats.h>
  9. #include <Atom/ImageProcessing/ImageObject.h>
  10. #include <Converters/PixelOperation.h>
  11. #include <Processing/PixelFormatInfo.h>
  12. #include <Converters/Histogram.h>
  13. ///////////////////////////////////////////////////////////////////////////////////
  14. namespace ImageProcessingAtom
  15. {
  16. float GetLuminance(const float& r, const float& g, const float& b)
  17. {
  18. return (r * 0.30f + g * 0.59f + b * 0.11f);
  19. }
  20. bool ComputeLuminanceHistogram(IImageObjectPtr imageObject, Histogram<256>& histogram)
  21. {
  22. EPixelFormat pixelFormat = imageObject->GetPixelFormat();
  23. if (!(CPixelFormats::GetInstance().IsPixelFormatUncompressed(pixelFormat)))
  24. {
  25. AZ_Assert(false, "%s function only works with uncompressed pixel format", __FUNCTION__);
  26. return false;
  27. }
  28. //create pixel operation function
  29. IPixelOperationPtr pixelOp = CreatePixelOperation(pixelFormat);
  30. //setup histogram bin
  31. static const size_t binCount = 256;
  32. Histogram<binCount>::Bins bins;
  33. Histogram<binCount>::clearBins(bins);
  34. //get count of bytes per pixel
  35. AZ::u32 pixelBytes = CPixelFormats::GetInstance().GetPixelFormatInfo(pixelFormat)->bitsPerBlock / 8;
  36. const AZ::u32 mipCount = imageObject->GetMipCount();
  37. float color[4];
  38. for (uint32 mip = 0; mip < mipCount; ++mip)
  39. {
  40. AZ::u8* pixelBuf;
  41. AZ::u32 pitch;
  42. imageObject->GetImagePointer(mip, pixelBuf, pitch);
  43. const uint32 pixelCount = imageObject->GetPixelCount(mip);
  44. for (uint32 i = 0; i < pixelCount; ++i, pixelBuf += pixelBytes)
  45. {
  46. pixelOp->GetRGBA(pixelBuf, color[0], color[1], color[2], color[3]);
  47. const float luminance = AZ::GetClamp(GetLuminance(color[0], color[1], color[2]), 0.0f, 1.0f);
  48. const float f = luminance * binCount;
  49. if (f <= 0)
  50. {
  51. ++bins[0];
  52. }
  53. else
  54. {
  55. const int bin = int(f);
  56. ++bins[(bin < binCount) ? bin : binCount - 1];
  57. }
  58. }
  59. }
  60. histogram.set(bins);
  61. return true;
  62. }
  63. } // end namespace ImageProcessingAtom