Initial public release

This commit is contained in:
jhaizhou
2026-10-12 16:51:08 +08:00
commit 46578a2b5d
997 changed files with 218713 additions and 0 deletions
+59
View File
@@ -0,0 +1,59 @@
/*
* Copyright (c) 2020-2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* SPDX-FileCopyrightText: Copyright (c) 2020-2025 NVIDIA CORPORATION & AFFILIATES
* SPDX-License-Identifier: BSD-3-Clause
*/
// Visualizing and Communicating Errors in Rendered Images
// Ray Tracing Gems II, 2021,
// by Pontus Andersson, Jim Nilsson, and Tomas Akenine-Moller.
// Pointer to the chapter: https://research.nvidia.com/publication/2021-08_Visualizing-and-Communicating.
// Visualizing Errors in Rendered High Dynamic Range Images
// Eurographics 2021,
// by Pontus Andersson, Jim Nilsson, Peter Shirley, and Tomas Akenine-Moller.
// Pointer to the paper: https://research.nvidia.com/publication/2021-05_HDR-FLIP.
// FLIP: A Difference Evaluator for Alternating Images
// High Performance Graphics 2020,
// by Pontus Andersson, Jim Nilsson, Tomas Akenine-Moller,
// Magnus Oskarsson, Kalle Astrom, and Mark D. Fairchild.
// Pointer to the paper: https://research.nvidia.com/publication/2020-07_FLIP.
// Code by Pontus Ebelin (formerly Andersson), Jim Nilsson, and Tomas Akenine-Moller.
#include "../FLIP.h"
#include "FLIPToolHelpers.h"
#include "commandline.h"
int main(int argc, char** argv)
{
commandline commandLine = commandline(argc, argv, getAllowedCommandLineOptions());
FLIPTool::execute(commandLine);
}
+625
View File
@@ -0,0 +1,625 @@
/*
* Copyright (c) 2020-2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* SPDX-FileCopyrightText: Copyright (c) 2020-2025 NVIDIA CORPORATION & AFFILIATES
* SPDX-License-Identifier: BSD-3-Clause
*/
// Visualizing and Communicating Errors in Rendered Images
// Ray Tracing Gems II, 2021,
// by Pontus Andersson, Jim Nilsson, and Tomas Akenine-Moller.
// Pointer to the chapter: https://research.nvidia.com/publication/2021-08_Visualizing-and-Communicating.
// Visualizing Errors in Rendered High Dynamic Range Images
// Eurographics 2021,
// by Pontus Andersson, Jim Nilsson, Peter Shirley, and Tomas Akenine-Moller.
// Pointer to the paper: https://research.nvidia.com/publication/2021-05_HDR-FLIP.
// FLIP: A Difference Evaluator for Alternating Images
// High Performance Graphics 2020,
// by Pontus Andersson, Jim Nilsson, Tomas Akenine-Moller,
// Magnus Oskarsson, Kalle Astrom, and Mark D. Fairchild.
// Pointer to the paper: https://research.nvidia.com/publication/2020-07_FLIP.
// Code by Pontus Ebelin (formerly Andersson), Jim Nilsson, and Tomas Akenine-Moller.
#pragma once
#include <cmath>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <chrono>
#include <filesystem>
#if defined(_WIN32) && !defined(NOMINMAX)
#define NOMINMAX
#endif
#define FIXED_DECIMAL_DIGITS(x, d) std::fixed << std::setprecision(d) << (x)
#include "../FLIP.h"
#include "imagehelpers.h"
#include "commandline.h"
#include "filename.h"
#include "pooling.h"
namespace FLIPTool
{
inline std::string f2s(float value, size_t decimals = 4)
{
std::stringstream ss;
ss << std::string(value < 0.0f ? "m" : "p") << FIXED_DECIMAL_DIGITS(std::abs(value), decimals);
return ss.str();
}
// Here follows a set of helps functions for differet setups in order to avoid clutter in main().
static void setupDestinationDirectory(const bool useHDR, const commandline& commandLine, std::string& destinationDirectory)
{
if (commandLine.optionSet("directory"))
{
destinationDirectory = commandLine.getOptionValue("directory");
std::replace(destinationDirectory.begin(), destinationDirectory.end(), '\\', '/'); // Replace backslash with forwardslash.
const bool bNoExposureMap = useHDR ? commandLine.optionSet("no-exposure-map") : true;
const bool bSaveLDRImages = useHDR ? commandLine.optionSet("save-ldr-images") : false;
const bool bSaveLDRFLIP = useHDR ? commandLine.optionSet("save-ldrflip") : false;
const bool willCreateOutput = (!commandLine.optionSet("no-error-map")) || (!bNoExposureMap) || bSaveLDRImages || bSaveLDRFLIP || commandLine.optionSet("histogram");
if (!std::filesystem::exists(destinationDirectory) && willCreateOutput) // Create directories if the parameters indicate that some files will be saved.
{
std::cout << "Creating new directory(s): <" << destinationDirectory << ">.\n";
std::filesystem::create_directories(destinationDirectory);
}
}
}
static void setupPixelsPerDegree(const commandline& commandLine, FLIP::Parameters& parameters)
{
// The default value in parameters.PPD is computed as FLIP::calculatePPD(0.7f, 3840.0f, 0.7f); in FLIP.h.
if (commandLine.optionSet("pixels-per-degree"))
{
parameters.PPD = std::stof(commandLine.getOptionValue("pixels-per-degree"));
}
else if (commandLine.optionSet("viewing-conditions"))
{
const float monitorDistance = std::stof(commandLine.getOptionValue("viewing-conditions", 0));
const float monitorWidth = std::stof(commandLine.getOptionValue("viewing-conditions", 1));
const float monitorResolutionX = std::stof(commandLine.getOptionValue("viewing-conditions", 2));
parameters.PPD = FLIP::calculatePPD(monitorDistance, monitorResolutionX, monitorWidth);
}
}
static void getExposureParameters(const bool useHDR, const commandline& commandLine, FLIP::Parameters& parameters, bool& returnLDRFLIPImages, bool& returnLDRImages)
{
if (useHDR)
{
if (commandLine.optionSet("tone-mapper")) // The default in FLIP::Parameters.tonemapper is "aces".
{
std::string tonemapper = commandLine.getOptionValue("tone-mapper");
std::transform(tonemapper.begin(), tonemapper.end(), tonemapper.begin(), [](unsigned char c) { return std::tolower(c); });
if (tonemapper != "aces" && tonemapper != "reinhard" && tonemapper != "hable")
{
std::cout << "\nError: unknown tonemapper, should be one of \"ACES\", \"Reinhard\", or \"Hable\"\n";
exit(-1);
}
parameters.tonemapper = tonemapper;
}
if (commandLine.optionSet("start-exposure"))
{
parameters.startExposure = std::stof(commandLine.getOptionValue("start-exposure"));
}
if (commandLine.optionSet("stop-exposure"))
{
parameters.stopExposure = std::stof(commandLine.getOptionValue("stop-exposure"));
}
if (commandLine.optionSet("num-exposures"))
{
parameters.numExposures = atoi(commandLine.getOptionValue("num-exposures").c_str());
}
returnLDRFLIPImages = commandLine.optionSet("save-ldrflip");
returnLDRImages = commandLine.optionSet("save-ldr-images");
}
}
static void saveErrorAndExposureMaps(const bool useHDR, commandline& commandLine, const FLIP::Parameters& parameters, const std::string basename,
FLIP::image<float>& errorMapFLIP, FLIP::image<float>& maxErrorExposureMap, const std::string& destinationDirectory,
FLIP::filename& referenceFileName, FLIP::filename& testFileName, FLIP::filename& histogramFileName, FLIP::filename& txtFileName,
FLIP::filename& flipFileName, FLIP::filename& exposureFileName, const size_t verbosity, const size_t testFileCount)
{
std::string logString = commandLine.optionSet("log") ? "log_" : "";
if ((basename != "" && commandLine.getOptionValues("test").size() == 1))
{
flipFileName.setName(basename);
histogramFileName.setName(logString + basename);
txtFileName.setName(basename);
exposureFileName.setName(basename + ".exposure_map");
}
else
{
flipFileName.setName(referenceFileName.getName() + "." + testFileName.getName() + "." + std::to_string(int(std::round(parameters.PPD))) + "ppd");
if (!useHDR)
{
flipFileName.setName(flipFileName.getName() + ".ldr"); // Note that the HDR filename is not complete until after FLIP has been computed, since FLIP may update the exposure parameters.
}
}
if (useHDR) // Updating the flipFileName here, since the computation of FLIP may have updated the exposure parameters.
{
if (verbosity > 1 && testFileCount == 0)
{
std::cout << " Assumed tone mapper: " << ((parameters.tonemapper == "aces") ? "ACES" : (parameters.tonemapper == "hable" ? "Hable" : "Reinhard")) << "\n";
std::cout << " Start exposure: " << FIXED_DECIMAL_DIGITS(parameters.startExposure, 4) << "\n";
std::cout << " Stop exposure: " << FIXED_DECIMAL_DIGITS(parameters.stopExposure, 4) << "\n";
std::cout << " Number of exposures: " << parameters.numExposures << "\n\n";
}
flipFileName.setName(flipFileName.getName() + ".hdr." + parameters.tonemapper + "." + f2s(parameters.startExposure) + "_to_" + f2s(parameters.stopExposure) + "." + std::to_string(parameters.numExposures));
exposureFileName.setName("exposure_map." + flipFileName.getName());
}
if (basename != "" && commandLine.getOptionValues("test").size() == 1)
{
flipFileName.setName(basename);
exposureFileName.setName(basename + ".exposure_map");
histogramFileName.setName(basename + "." + logString + "weighted_histogram");
testFileName.setName(basename);
}
else
{
flipFileName.setName("flip." + flipFileName.getName());
histogramFileName.setName(logString + "weighted_histogram." + flipFileName.getName());
txtFileName.setName("pooled_values." + flipFileName.getName());
}
if (!commandLine.optionSet("no-error-map"))
{
FLIP::image<FLIP::color3> pngResult(errorMapFLIP.getWidth(), errorMapFLIP.getHeight());
if (!commandLine.optionSet("no-magma"))
{
pngResult.colorMap(errorMapFLIP, FLIP::magmaMap);
}
else
{
pngResult.copyFloatToColor3(errorMapFLIP);
}
ImageHelpers::pngSave(destinationDirectory + "/" + flipFileName.toString(), pngResult);
}
if (useHDR)
{
if (!commandLine.optionSet("no-exposure-map"))
{
FLIP::image<FLIP::color3> pngMaxErrorExposureMap(maxErrorExposureMap.getWidth(), maxErrorExposureMap.getHeight());
pngMaxErrorExposureMap.colorMap(maxErrorExposureMap, FLIP::viridisMap);
ImageHelpers::pngSave(destinationDirectory + "/" + exposureFileName.toString(), pngMaxErrorExposureMap);
}
}
}
static void setExposureStrings(const int exposureCount, const float exposure, std::string& expCount, std::string& expString)
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(3) << exposureCount;
expCount = ss.str();
ss.str(std::string());
ss << std::string(exposure < 0.0f ? "m" : "p") << std::to_string(std::abs(exposure));
expString = ss.str();
}
// Optionally store the intermediate LDR images and LDR-FLIP error maps produced during the evaluation of HDR-FLIP.
static void saveIntermediateHDRFLIPOutput(commandline& commandLine, const FLIP::Parameters& parameters, const std::string& basename, const FLIP::filename& flipFileName,
const FLIP::filename& referenceFileName, const FLIP::filename& testFileName, const std::string& destinationDirectory,
std::vector<FLIP::image<float>*> intermediateLDRFLIPImages, std::vector<FLIP::image<FLIP::color3>*> intermediateLDRImages)
{
if (intermediateLDRImages.size() > 0)
{
FLIP::filename rFileName(".png");
FLIP::filename tFileName(".png");
if (intermediateLDRImages.size() != size_t(parameters.numExposures * 2))
{
std::cout << "FLIP tool error: the number of LDR images from HDR-FLIP is not the expected number.\nExiting.\n";
exit(EXIT_FAILURE);
}
const float exposureStepSize = (parameters.stopExposure - parameters.startExposure) / (parameters.numExposures - 1);
for (int i = 0; i < parameters.numExposures; i++)
{
std::string expCount, expString;
setExposureStrings(i, parameters.startExposure + i * exposureStepSize, expCount, expString);
if (basename == "")
{
rFileName.setName(referenceFileName.getName() + "." + parameters.tonemapper + "." + expCount + "." + expString);
tFileName.setName(testFileName.getName() + "." + parameters.tonemapper + "." + expCount + "." + expString);
}
else
{
rFileName.setName(basename + ".reference." + "." + expCount);
tFileName.setName(basename + ".test." + "." + expCount);
}
FLIP::image<FLIP::color3>* rImage = intermediateLDRImages[0];
FLIP::image<FLIP::color3>* tImage = intermediateLDRImages[1];
intermediateLDRImages.erase(intermediateLDRImages.begin());
intermediateLDRImages.erase(intermediateLDRImages.begin());
rImage->LinearRGBTosRGB();
tImage->LinearRGBTosRGB();
ImageHelpers::pngSave(destinationDirectory + "/" + rFileName.toString(), *rImage);
ImageHelpers::pngSave(destinationDirectory + "/" + tFileName.toString(), *tImage);
delete rImage;
delete tImage;
}
}
if (intermediateLDRFLIPImages.size() > 0)
{
if (intermediateLDRFLIPImages.size() != size_t(parameters.numExposures))
{
std::cout << "FLIP tool error: the number of FLIP LDR images from HDR-FLIP is not the expected number.\nExiting.\n";
exit(EXIT_FAILURE);
}
const float exposureStepSize = (parameters.stopExposure - parameters.startExposure) / (parameters.numExposures - 1);
for (int i = 0; i < parameters.numExposures; i++)
{
std::string expCount, expString;
setExposureStrings(i, parameters.startExposure + i * exposureStepSize, expCount, expString);
FLIP::image<float>* flipImage = intermediateLDRFLIPImages[0];
intermediateLDRFLIPImages.erase(intermediateLDRFLIPImages.begin());
FLIP::image<FLIP::color3> pngResult(flipImage->getWidth(), flipImage->getHeight());
if (!commandLine.optionSet("no-magma"))
{
pngResult.colorMap(*flipImage, FLIP::magmaMap);
}
else
{
pngResult.copyFloatToColor3(*flipImage);
}
if (basename == "")
{
ImageHelpers::pngSave(destinationDirectory + "/" + "flip." + referenceFileName.getName() + "." + testFileName.getName() + "." + std::to_string(int(std::round(parameters.PPD))) + "ppd.ldr." + parameters.tonemapper + "." + expCount + "." + expString + ".png", pngResult);
}
else
{
ImageHelpers::pngSave(destinationDirectory + "/" + basename + "." + expCount + ".png", pngResult);
}
ImageHelpers::pngSave(destinationDirectory + "/" + flipFileName.toString(), pngResult);
delete flipImage;
}
}
}
static void gatherStatisticsAndSaveOutput(commandline& commandLine, FLIP::image<float>& errorMapFLIP, FLIPPooling::pooling<float>& pooledValues,
const std::string& destinationDirectory, const FLIP::filename& referenceFileName, const FLIP::filename& testFileName, const FLIP::filename& histogramFileName,
const FLIP::filename& txtFileName, const FLIP::filename& flipFileName, const FLIP::filename& exposureFileName, const std::string& FLIPString, const float time,
const uint32_t testFileCount, const bool saveOverlappedHistogram, const bool useHDR, const size_t verbosity)
{
for (int y = 0; y < errorMapFLIP.getHeight(); y++)
{
for (int x = 0; x < errorMapFLIP.getWidth(); x++)
{
pooledValues.update(x, y, errorMapFLIP.get(x, y));
}
}
if (commandLine.optionSet("histogram") && !saveOverlappedHistogram)
{
bool optionLog = commandLine.optionSet("log");
bool optionExcludeValues = commandLine.optionSet("exclude-pooled-values");
float yMax = (commandLine.optionSet("y-max") ? std::stof(commandLine.getOptionValue("y-max")) : 0.0f);
pooledValues.save(destinationDirectory + "/" + histogramFileName.toString(), errorMapFLIP.getWidth(), errorMapFLIP.getHeight(), optionLog, !optionExcludeValues, yMax);
}
// Collect pooled values and elapsed time.
float mean = pooledValues.getMean();
float weightedMedian = pooledValues.getPercentile(0.5f, true);
float firstWeightedQuartile = pooledValues.getPercentile(0.25f, true);
float thirdWeightedQuartile = pooledValues.getPercentile(0.75f, true);
float minValue = pooledValues.getMinValue();
float maxValue = pooledValues.getMaxValue();
if (commandLine.optionSet("textfile"))
{
FLIP::filename textFileName(destinationDirectory + "/" + txtFileName.toString());
std::ofstream txt;
txt.open(textFileName.toString());
if (txt.is_open())
{
txt.seekp(0, std::ios_base::end);
txt << "Mean: " << FIXED_DECIMAL_DIGITS(mean, 6) << "\n";
txt << "Weighted median: " << FIXED_DECIMAL_DIGITS(weightedMedian, 6) << "\n";
txt << "1st weighted quartile: " << FIXED_DECIMAL_DIGITS(firstWeightedQuartile, 6) << "\n";
txt << "3rd weighted quartile: " << FIXED_DECIMAL_DIGITS(thirdWeightedQuartile, 6) << "\n";
txt << "Min: " << FIXED_DECIMAL_DIGITS(minValue, 6) << "\n";
txt << "Max: " << FIXED_DECIMAL_DIGITS(maxValue, 6) << "\n";
txt.close();
}
else
{
std::cout << "\nError: Could not write txt file " << textFileName.toString() << "\n";
}
}
if (commandLine.optionSet("csv"))
{
FLIP::filename csvFileName(commandLine.getOptionValue("csv"));
std::fstream csv;
csv.open(csvFileName.toString(), std::ios::app);
if (csv.is_open())
{
csv.seekp(0, std::ios_base::end);
if (csv.tellp() <= 0)
csv << "\"Reference\",\"Test\",\"Mean\",\"Weighted median\",\"1st weighted quartile\",\"3rd weighted quartile\",\"Min\",\"Max\",\"Evaluation time\"\n";
csv << "\"" << referenceFileName.toString() << "\",";
csv << "\"" << testFileName.toString() << "\",";
csv << "\"" << FIXED_DECIMAL_DIGITS(mean, 6) << "\",";
csv << "\"" << FIXED_DECIMAL_DIGITS(weightedMedian, 6) << "\",";
csv << "\"" << FIXED_DECIMAL_DIGITS(firstWeightedQuartile, 6) << "\",";
csv << "\"" << FIXED_DECIMAL_DIGITS(thirdWeightedQuartile, 6) << "\",";
csv << "\"" << FIXED_DECIMAL_DIGITS(minValue, 6) << "\",";
csv << "\"" << FIXED_DECIMAL_DIGITS(maxValue, 6) << "\",";
csv << "\"" << FIXED_DECIMAL_DIGITS(time, 4) << "\"\n";
csv.close();
}
else
{
std::cout << "\nError: Could not write csv file " << csvFileName.toString() << "\n";
}
}
if (verbosity > 0)
{
std::cout << FLIPString << " between reference image <" << referenceFileName.toString() << "> and test image <" << testFileName.toString() << ">\n";
std::cout << " Mean: " << FIXED_DECIMAL_DIGITS(mean, 6) << "\n";
std::cout << ((testFileCount < commandLine.getOptionValues("test").size() && verbosity == 1) ? "\n" : "");
if (verbosity > 1)
{
std::cout << " Weighted median: " << FIXED_DECIMAL_DIGITS(weightedMedian, 6) << "\n";
std::cout << " 1st weighted quartile: " << FIXED_DECIMAL_DIGITS(firstWeightedQuartile, 6) << "\n";
std::cout << " 3rd weighted quartile: " << FIXED_DECIMAL_DIGITS(thirdWeightedQuartile, 6) << "\n";
std::cout << " Min: " << FIXED_DECIMAL_DIGITS(minValue, 6) << "\n";
std::cout << " Max: " << FIXED_DECIMAL_DIGITS(maxValue, 6) << "\n";
std::cout << " Evaluation time: " << FIXED_DECIMAL_DIGITS(time, 4) << " seconds\n";
if (!commandLine.optionSet("no-error-map"))
{
std::cout << " FLIP error map location: " << destinationDirectory + "/" + flipFileName.toString() << "\n";
}
if (!commandLine.optionSet("no-exposure-map") && useHDR)
{
std::cout << " FLIP exposure map location: " << destinationDirectory + "/" + exposureFileName.toString() << "\n";
}
std::cout << ((testFileCount < commandLine.getOptionValues("test").size()) ? "\n" : "");
}
}
if (commandLine.optionSet("exit-on-test"))
{
std::string exitOnTestQuantity = "mean";
float exitOnTestThresholdValue = 0.05f;
if (commandLine.optionSet("exit-test-parameters"))
{
exitOnTestQuantity = commandLine.getOptionValue("exit-test-parameters", 0);
std::transform(exitOnTestQuantity.begin(), exitOnTestQuantity.end(), exitOnTestQuantity.begin(), [](unsigned char c) { return std::tolower(c); });
if (exitOnTestQuantity != "mean" && exitOnTestQuantity != "weighted-median" && exitOnTestQuantity != "max")
{
std::cout << "For --exit-test-parameters / -etp, the first paramter needs to be {MEAN | WEIGHTED-MEDIAN | MAX}\n";
exit(EXIT_FAILURE);
}
exitOnTestThresholdValue = std::stof(commandLine.getOptionValue("exit-test-parameters", 1));
if (exitOnTestThresholdValue < 0.0f || exitOnTestThresholdValue > 1.0f)
{
std::cout << "For --exit-test-parameters / -etp, the second paramter needs to be in [0,1]\n";
exit(EXIT_FAILURE);
}
}
float testQuantity;
if (exitOnTestQuantity == "mean")
{
testQuantity = mean;
}
else if (exitOnTestQuantity == "weighted-median")
{
testQuantity = weightedMedian;
}
else if (exitOnTestQuantity == "max")
{
testQuantity = maxValue;
}
else
{
std::cout << "Exiting with failure code because exit-on-text-quantity was " << exitOnTestQuantity << ", and expects to be mean, weighted-median, or max.\n";
exit(EXIT_FAILURE); // From stdlib.h: equal to 1.
}
if (testQuantity > exitOnTestThresholdValue)
{
std::cout << "Exiting with failure code because the " << exitOnTestQuantity << " of the FLIP error map is " << FIXED_DECIMAL_DIGITS(testQuantity, 6) << ", while the threshold for success is " << FIXED_DECIMAL_DIGITS(exitOnTestThresholdValue, 6) << ".\n";
exit(EXIT_FAILURE); // From stdlib.h: equal to 1.
}
}
}
int execute(commandline commandLine)
{
auto timeStart = std::chrono::high_resolution_clock::now();
std::string FLIPString = "FLIP";
int MajorVersion = 1;
int MinorVersion = 7;
if (commandLine.optionSet("help"))
{
std::cout << "FLIP v" << MajorVersion << "." << MinorVersion << ".\n";
commandLine.print();
exit(EXIT_SUCCESS);
}
if (!commandLine.optionSet("reference"))
{
std::cout << "Error: you need to set a reference image filename.\n Typically done with '-r refimg.{png,exr}' or '--reference refimg.{png,exr}'.\n Use -h or --help for help message. Exiting.\n";
exit(EXIT_FAILURE);
}
if (!std::filesystem::exists(commandLine.getOptionValue("reference"))) // Reference does not exist?
{
std::cout << "Error: reference file <" << commandLine.getOptionValue("reference") << "> does not exist. Exiting.\n";
exit(EXIT_FAILURE);
}
if (!commandLine.optionSet("test"))
{
std::cout << "Error: you need to set a test image filename.\n Typically done with '-t testimg.{png,exr}' or '--test testimg.{png,exr}'.\n Use -h or --help for help message. Exiting.\n";
exit(EXIT_FAILURE);
}
if ((commandLine.optionSet("basename") && commandLine.getOptionValues("test").size() != 1) || commandLine.getError())
{
if (commandLine.getError())
{
std::cout << commandLine.getErrorString() << "\n";
}
std::cout << "FLIP v" << MajorVersion << "." << MinorVersion << ".\n";
commandLine.print();
exit(EXIT_FAILURE);
}
size_t verbosity = commandLine.optionSet("verbosity") ? std::stoi(commandLine.getOptionValue("verbosity")) : 2;
FLIP::Parameters parameters;
FLIP::filename referenceFileName(commandLine.getOptionValue("reference"));
bool bUseHDR = (referenceFileName.getExtension() == "exr");
std::string destinationDirectory = ".";
std::string basename = (commandLine.optionSet("basename") ? commandLine.getOptionValue("basename") : "");
FLIP::filename flipFileName(".png");
FLIP::filename histogramFileName(".py");
FLIP::filename exposureFileName(".png");
FLIP::filename txtFileName(".txt");
FLIP::filename testFileName;
bool returnLDRImages = false; // Can only happen for HDR.
bool returnLDRFLIPImages = false; // Can only happen for HDR.
setupDestinationDirectory(bUseHDR, commandLine, destinationDirectory);
setupPixelsPerDegree(commandLine, parameters);
getExposureParameters(bUseHDR, commandLine, parameters, returnLDRFLIPImages, returnLDRImages);
if (verbosity > 1)
{
std::cout << "Invoking " << (bUseHDR ? "HDR" : "LDR") << "-FLIP\n";
std::cout << " Pixels per degree: " << int(std::round(parameters.PPD)) << "\n" << (!bUseHDR ? "\n" : "");
}
FLIP::image<FLIP::color3> referenceImage;
bool refImageOk = ImageHelpers::load(referenceImage, referenceFileName.toString()); // Load reference image.
if (!refImageOk)
{
std::cout << "Error: could not read reference image file <" << referenceFileName.toString() << ">. Note that FLIP only loads png, bmp, tga, and exr images. Exiting.\n";
exit(EXIT_FAILURE);
}
if (!bUseHDR)
{
referenceImage.sRGBToLinearRGB();
}
// Save firstTestFileName and firstPooledValue for optional overlapped histogram.
const bool saveOverlappedHistogram = commandLine.optionSet("histogram") && commandLine.getOptionValues("test").size() == 2;
FLIP::filename firstTestFileName;
FLIPPooling::pooling<float> pooledValues;
FLIPPooling::pooling<float> firstPooledValues;
uint32_t testFileCount = 0;
// Loop over the test images files to be FLIP:ed against the reference image.
for (auto& testFileNameString : commandLine.getOptionValues("test"))
{
pooledValues = FLIPPooling::pooling<float>(100); // Reset pooledValues to remove accumulation issues.
std::vector<FLIP::image<float>*> intermediateLDRFLIPImages;
std::vector<FLIP::image<FLIP::color3>*> intermediateLDRImages;
testFileName = testFileNameString;
if (!std::filesystem::exists(testFileName.toString()))
{
std::cout << "Error: test image file <" << testFileName.toString() << "> does not exist. Exiting.\n";
exit(EXIT_FAILURE);
}
FLIP::image<FLIP::color3> testImage;
bool testImageOk = ImageHelpers::load(testImage, testFileName.toString()); // Load test image.
if (!testImageOk)
{
std::cout << "Error: could not read test file <" << testFileName.toString() << ">. Note that FLIP only loads png, bmp, tga, and exr images. Exiting.\n";
exit(EXIT_FAILURE);
}
if (referenceImage.getWidth() != testImage.getWidth() || referenceImage.getHeight() != testImage.getHeight())
{
std::cout << "Error: reference <" << referenceImage.getWidth() << "x" << referenceImage.getHeight() << "> and test <" << testImage.getWidth() << "x" << testImage.getHeight() << "> images must be of equal dimensions. Exiting.\n";
exit(EXIT_FAILURE);
}
if (!bUseHDR)
{
testImage.sRGBToLinearRGB();
}
FLIP::image<float> errorMapFLIP(referenceImage.getWidth(), referenceImage.getHeight(), 0.0f);
FLIP::image<float> maxErrorExposureMap(referenceImage.getWidth(), referenceImage.getHeight());
auto t0 = std::chrono::high_resolution_clock::now();
FLIP::evaluate(referenceImage, testImage, bUseHDR, parameters, errorMapFLIP, maxErrorExposureMap, returnLDRFLIPImages, intermediateLDRFLIPImages, returnLDRImages, intermediateLDRImages);
float time = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - t0).count() / 1000000.0f;
saveErrorAndExposureMaps(bUseHDR, commandLine, parameters, basename, errorMapFLIP, maxErrorExposureMap, destinationDirectory, referenceFileName, testFileName, histogramFileName, txtFileName, flipFileName, exposureFileName, verbosity, testFileCount);
saveIntermediateHDRFLIPOutput(commandLine, parameters, basename, flipFileName, referenceFileName, testFileName, destinationDirectory, intermediateLDRFLIPImages, intermediateLDRImages);
gatherStatisticsAndSaveOutput(commandLine, errorMapFLIP, pooledValues, destinationDirectory, referenceFileName, testFileName, histogramFileName, txtFileName, flipFileName, exposureFileName, FLIPString, time, ++testFileCount, saveOverlappedHistogram, bUseHDR, verbosity);
// Save first set of results for overlapped histogram.
if (saveOverlappedHistogram && testFileCount == 1)
{
firstPooledValues = pooledValues;
firstTestFileName = testFileName;
}
}
if (saveOverlappedHistogram)
{
bool optionLog = commandLine.optionSet("log");
bool optionExcludeValues = commandLine.optionSet("exclude-pooled-values");
float yMax = (commandLine.optionSet("y-max") ? std::stof(commandLine.getOptionValue("y-max")) : 0.0f);
pooledValues.saveOverlappedHistogram(firstPooledValues, destinationDirectory + "/" + histogramFileName.toString(), referenceImage.getWidth(), referenceImage.getHeight(), optionLog, referenceFileName.getName(), firstTestFileName.getName(), testFileName.getName(), !optionExcludeValues, yMax);
}
float timeTotal = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - timeStart).count() / 1000000.0f;
std::cout << "\nTotal time: " << FIXED_DECIMAL_DIGITS(timeTotal, 4) << " seconds\n";
exit(EXIT_SUCCESS); // From stdlib.h: equal to 0.
}
}
+451
View File
@@ -0,0 +1,451 @@
/*
* Copyright (c) 2020-2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* SPDX-FileCopyrightText: Copyright (c) 2020-2025 NVIDIA CORPORATION & AFFILIATES
* SPDX-License-Identifier: BSD-3-Clause
*/
// Visualizing and Communicating Errors in Rendered Images
// Ray Tracing Gems II, 2021,
// by Pontus Andersson, Jim Nilsson, and Tomas Akenine-Moller.
// Pointer to the chapter: https://research.nvidia.com/publication/2021-08_Visualizing-and-Communicating.
// Visualizing Errors in Rendered High Dynamic Range Images
// Eurographics 2021,
// by Pontus Andersson, Jim Nilsson, Peter Shirley, and Tomas Akenine-Moller.
// Pointer to the paper: https://research.nvidia.com/publication/2021-05_HDR-FLIP.
// FLIP: A Difference Evaluator for Alternating Images
// High Performance Graphics 2020,
// by Pontus Andersson, Jim Nilsson, Tomas Akenine-Moller,
// Magnus Oskarsson, Kalle Astrom, and Mark D. Fairchild.
// Pointer to the paper: https://research.nvidia.com/publication/2020-07_FLIP.
// Code by Pontus Ebelin (formerly Andersson), Jim Nilsson, and Tomas Akenine-Moller.
#pragma once
#include <map>
#include <set>
#include <vector>
#include <cassert>
#include <sstream>
#include <algorithm>
template<typename T>
class unique_vector;
template<typename T>
class unique_vector_iterator
{
private:
size_t mPosition;
const unique_vector<T>* mpUniqueVector;
public:
unique_vector_iterator(const unique_vector<T>* pVector, size_t position) : mPosition(position), mpUniqueVector(pVector) { }
bool operator!=(const unique_vector_iterator& other) const { return this->mPosition != other.mPosition; }
T operator*(void) const { return this->mpUniqueVector->at(this->mPosition); }
const unique_vector_iterator& operator++(void) { this->mPosition++; return *this; }
unique_vector_iterator operator+(size_t v) const { return unique_vector_iterator(this->mpUniqueVector, this->mPosition + v); }
};
template<typename T>
class unique_vector
{
public:
typedef unique_vector_iterator<T> iterator;
private:
std::vector<T> mVector;
public:
void push_back(T value) { if (!this->contains(value)) this->mVector.push_back(value); }
T at(size_t index) const { return this->mVector.at(index); }
T operator[](size_t index) const { return this->mVector.at(index); }
T& operator[](size_t index) { return this->mVector.at(index); }
size_t size(void) const { return this->mVector.size(); }
bool contains(T value) const { return std::find(this->mVector.begin(), this->mVector.end(), value) != mVector.end(); }
iterator begin(size_t begin = 0) const { return iterator(this, begin); }
iterator end(size_t end = std::string::npos) const { return iterator(this, (end != std::string::npos && end <= mVector.size() ? end : mVector.size())); }
// Conversion to const std::vector.
operator const std::vector<T>() const { return mVector; }
operator std::vector<T>() { return mVector; }
};
typedef struct
{
std::string longName;
std::string shortName;
int numArgs; // -1: '+' if required, '*' if not required.
bool required;
std::string meta;
std::string help;
std::string value;
} commandline_option;
typedef struct
{
std::string description;
std::vector<commandline_option> options;
} commandline_options;
static const commandline_options getAllowedCommandLineOptions(const bool cpptool = true)
{
commandline_options commandLineOptions =
{
"Compute FLIP between reference.<png|exr> and test.<png|exr>.\n"
"Reference and test(s) must have same resolution and format.\n"
"If pngs are entered, LDR-FLIP will be evaluated. If exrs are entered, HDR-FLIP will be evaluated.\n"
"For HDR-FLIP, the reference is used to automatically calculate start exposure and/or stop exposure and/or number of exposures, if they are not entered.\n",
{
{ "help", "h", 0, false, "", "show this help message and exit" },
{ "reference", "r", 1, true, "REFERENCE", "Relative or absolute path (including file name and extension) for reference image" },
{ "test", "t", -1, true, "TEST", "Relative or absolute path(s) (including file name and extension) for test image(s)" },
{ "pixels-per-degree", "ppd", 1, false, "PIXELS-PER-DEGREE", "Observer's number of pixels per degree of visual angle. Default corresponds to\nviewing the images at 0.7 meters from a 0.7 meter wide 4K display" },
{ "viewing-conditions", "vc", 3, false, "MONITOR-DISTANCE MONITOR-WIDTH MONITOR-WIDTH-PIXELS", "Distance to monitor (in meters), width of monitor (in meters), width of monitor (in pixels).\nDefault corresponds to viewing the monitor at 0.7 meters from a 0.7 meters wide 4K display" },
{ "tone-mapper", "tm", 1, false, "ACES | HABLE | REINHARD", "Tone mapper used for HDR-FLIP. Supported tone mappers are ACES, Hable, and Reinhard (default: ACES)" },
{ "num-exposures", "n", 1, false, "NUM-EXPOSURES", "Number of exposures between (and including) start and stop exposure used to compute HDR-FLIP" },
{ "start-exposure", "cstart", 1, false, "C-START", "Start exposure used to compute HDR-FLIP" },
{ "stop-exposure", "cstop", 1, false, "C-STOP", "Stop exposure used to comput HDR-FLIP" },
{ "verbosity", "v", 1, false, "VERBOSITY", "Level of verbosity (default: 2).\n0: no printed output,\n\t\t1: print mean FLIP error,\n\t\t2: print pooled FLIP errors, PPD, and evaluation time and (for HDR-FLIP) start and stop exposure and number of exposures"},
{ "basename", "b", 1, false, "BASENAME", "Basename for outfiles, e.g., error and exposure maps. Only compatible with one test image as input" },
{ "textfile", "txt", 0, false, "", "Save text file with pooled FLIP values (mean, weighted median and weighted 1st and 3rd quartiles as well as minimum and maximum error)" },
{ "csv", "c", 1, false, "CSV_FILENAME", "Write results to a csv file. Input is the desired file name (including .csv extension).\nResults are appended if the file already exists" },
{ "histogram", "hist", 0, false, "", "Save weighted histogram of the FLIP error map(s)" },
{ "y-max", "", 1, true, "", "Set upper limit of weighted histogram's y-axis" },
{ "log", "lg", 0, false, "", "Use logarithmic scale on y-axis in histogram" },
{ "exclude-pooled-values", "epv", 0, false, "", "Do not include pooled FLIP values in the weighted histogram" },
{ "save-ldr-images", "sli", 0, false, "", "Save all exposure compensated and tone mapped LDR images (png) used for HDR-FLIP" },
{ "save-ldrflip", "slf", 0, false, "", "Save all LDR-FLIP maps used for HDR-FLIP" },
{ "no-magma", "nm", 0, false, "", "Save FLIP error maps in grayscale instead of magma" },
{ "no-exposure-map", "nexm", 0, false, "", "Do not save the HDR-FLIP exposure map" },
{ "no-error-map", "nerm", 0, false, "", "Do not save the FLIP error map" },
{ "directory", "d", 1, false, "Relative or absolute path to save directory"},
} };
// Add C++ specific options.
std::vector<commandline_option> cppSpecific = {};
if (cpptool)
{
cppSpecific =
{
{ "exit-on-test", "et", 0, false, "", "Do exit(EXIT_FAILURE) if the selected FLIP QUANTITY is greater than THRESHOLD"},
{ "exit-test-parameters", "etp", 2, false, "QUANTITY = {MEAN (default) | WEIGHTED-MEDIAN | MAX} THRESHOLD (default = 0.05) ", "Test parameters for selected quantity and threshold value (in [0,1]) for exit on test"},
};
}
for (auto opt : cppSpecific)
{
commandLineOptions.options.push_back(opt);
}
return commandLineOptions;
}
class commandline
{
private:
std::string mCommand;
commandline_options mAllowedOptions;
std::map<std::string, std::vector<std::string>> mOptions;
std::vector<std::string> mArguments;
bool mError = false;
std::string mErrorString;
public:
commandline() = default;
commandline(int argc, char* argv[], const commandline_options& allowedOptions = {}) :
mAllowedOptions(allowedOptions)
{
clear();
parse(argc, argv, allowedOptions);
}
bool getError(void) const
{
return mError;
}
std::string getErrorString(void) const
{
return mErrorString;
}
void clear(void)
{
mCommand = "";
mOptions.clear();
mArguments.clear();
}
bool parse(int argc, char* argv[], const commandline_options& allowedOptions = {})
{
mCommand = argv[0];
std::string tOption = "";
int atArg = 1;
std::string longOptionName;
std::string shortOptionName;
while (atArg < argc)
{
bool atOption = false;
bool optionHasArgument = false;
int numOptionArguments = 0;
std::string arg(argv[atArg]);
if (arg[0] == '-')
{
bool bIsLong = (arg[1] == '-');
std::string optionString = arg.substr(bIsLong ? 2 : 1);
bool bFound = false;
for (auto allowedOption : allowedOptions.options)
{
longOptionName = allowedOption.longName;
shortOptionName = allowedOption.shortName;
if ((bIsLong && longOptionName == optionString) || (!bIsLong && shortOptionName == optionString))
{
bFound = true;
atOption = true;
tOption = optionString;
optionHasArgument = (allowedOption.numArgs != 0);
numOptionArguments = allowedOption.numArgs;
break;
}
}
if (atOption)
{
if (!bFound)
{
this->mError = true;
this->mErrorString = "Option not found!";
return false;
}
if (optionHasArgument)
{
// Eat option arguments.
atArg++;
while (atArg < argc && numOptionArguments != 0)
{
arg = argv[atArg];
if (arg[0] == '-' && numOptionArguments < 0)
{
break;
}
this->mOptions[longOptionName].push_back(arg);
if (numOptionArguments > 0)
{
numOptionArguments--;
}
atArg++;
}
}
else
{
this->mOptions[longOptionName].push_back("");
atArg++;
}
}
else
{
this->mArguments.push_back(arg);
atArg++;
}
}
else
{
this->mArguments.push_back(arg);
atArg++;
}
}
return true;
}
bool parse(std::string commandLine, const commandline_options& allowedOptions = {})
{
std::vector<std::string> vCommandLine;
std::string command;
std::stringstream ss(commandLine);
while (ss >> command)
vCommandLine.push_back(command);
std::vector<char*> vpCommandLine;
for (size_t i = 0; i < vCommandLine.size(); i++)
vpCommandLine.push_back(const_cast<char *>(vCommandLine[i].c_str()));
return parse(int(vpCommandLine.size()), &vpCommandLine[0], allowedOptions);
}
inline const std::string& getCommand(void) const
{
return mCommand;
}
inline size_t getNumArguments(void) const
{
return this->mArguments.size();
}
inline const std::string getArgument(size_t index) const
{
assert(index < this->mArguments.size());
return this->mArguments[index];
}
const std::vector<std::string>& getArguments(void) const
{
return this->mArguments;
}
const std::string& getOptionValue(const std::string& option, size_t n = 0) const
{
return this->mOptions.at(option)[n];
}
std::vector<std::string>& getOptionValues(const std::string& option)
{
return (std::vector<std::string>&)this->mOptions.at(option);
}
const std::string& getOption(const std::string& option, size_t index) const
{
static const std::string emptyString;
auto& options = this->mOptions.at(option);
if (index < options.size())
{
return options[index];
}
return emptyString;
}
size_t getNumOptionValues(const std::string& option) const
{
return this->mOptions.at(option).size();
}
bool optionSet(const std::string& option) const
{
return this->mOptions.find(option) != this->mOptions.end();
}
void print(void)
{
commandline_options& ao = this->mAllowedOptions;
std::string command = mCommand.substr(mCommand.find_last_of("/\\") + 1);
size_t numOptionalOptions = 0;
for (auto& o : ao.options)
{
if (o.required == false)
{
numOptionalOptions++;
}
}
std::cout << "usage: " << command;
if (numOptionalOptions > 0)
{
std::cout << " [OPTIONS]";
if (numOptionalOptions > 1)
{
std::cout << "...";
}
}
for (auto& o : ao.options)
{
if (o.required)
{
std::cout << " -" << o.shortName << "";
if (o.numArgs != 0)
{
std::cout << " " << o.meta;
if (o.numArgs == -1)
{
std::cout << " [...]";
}
}
}
}
std::cout << "\n\n";
std::cout << ao.description << "\n\n";
for (auto& o : ao.options)
{
if (o.shortName != "")
{
std::cout << " -" << o.shortName;
if (o.longName != "")
{
std::cout << ",";
}
}
if (o.longName != "")
{
std::cout << " --" << o.longName;
}
if (o.numArgs != 0)
{
std::cout << " " << o.meta;
if (o.numArgs == -1)
{
std::cout << " [...]";
}
}
std::cout << "\n";
if (o.help != "")
{
size_t loc = o.help.find("\n");
if (loc != std::string::npos)
{
o.help.replace(loc, 1, "\n\t\t");
}
std::cout << "\t\t" << o.help << "\n";
}
}
}
};
+187
View File
@@ -0,0 +1,187 @@
/*
* Copyright (c) 2020-2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* SPDX-FileCopyrightText: Copyright (c) 2020-2025 NVIDIA CORPORATION & AFFILIATES
* SPDX-License-Identifier: BSD-3-Clause
*/
// Visualizing and Communicating Errors in Rendered Images
// Ray Tracing Gems II, 2021,
// by Pontus Andersson, Jim Nilsson, and Tomas Akenine-Moller.
// Pointer to the chapter: https://research.nvidia.com/publication/2021-08_Visualizing-and-Communicating.
// Visualizing Errors in Rendered High Dynamic Range Images
// Eurographics 2021,
// by Pontus Andersson, Jim Nilsson, Peter Shirley, and Tomas Akenine-Moller.
// Pointer to the paper: https://research.nvidia.com/publication/2021-05_HDR-FLIP.
// FLIP: A Difference Evaluator for Alternating Images
// High Performance Graphics 2020,
// by Pontus Andersson, Jim Nilsson, Tomas Akenine-Moller,
// Magnus Oskarsson, Kalle Astrom, and Mark D. Fairchild.
// Pointer to the paper: https://research.nvidia.com/publication/2020-07_FLIP.
// Code by Pontus Ebelin (formerly Andersson), Jim Nilsson, and Tomas Akenine-Moller.
#pragma once
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>
#include <regex>
#include <cctype>
#ifndef MAX_PATH
#define MAX_PATH 260
#endif
namespace FLIP
{
class filename
{
private:
std::string mDirectory;
std::string mName;
std::string mExtension;
public:
filename() { init(); };
filename(const std::string& path) { parse(path); }
filename(const filename& fileName) { *this = fileName; }
~filename() {};
filename operator=(const std::string& path) { parse(path); return *this; }
bool operator==(const filename& fileName) const
{
return this->mDirectory == fileName.mDirectory &&
this->mName == fileName.mName &&
this->mExtension == fileName.mExtension;
}
bool operator!=(const filename& fileName) const { return !(*this == fileName); }
inline void setName(std::string name)
{
// Remove forbidden characters from the name.
this->mName = std::regex_replace(name, std::regex("\\\\|/|:|\\*|\\?|\\||\"|<|>"), "_");
}
inline const std::string& getName(void) const { return this->mName; }
inline void setExtension(std::string extension) { this->mExtension = extension; }
inline const std::string& getExtension(void) const { return this->mExtension; }
static const filename& empty(void)
{
static const filename emptyFileName = filename();
return emptyFileName;
}
std::string toString(bool toLower = false) const
{
if (*this == this->empty())
return "";
std::stringstream ss;
if (this->mDirectory != "")
{
#if _WIN32
ss << this->mDirectory << "\\";
#else
ss << this->mDirectory << "/";
#endif
}
ss << this->mName;
if (this->mExtension != "")
{
ss << "." << this->mExtension;
}
std::string string = ss.str();
if (toLower)
{
std::transform(string.begin(), string.end(), string.begin(), ::tolower);
}
return string;
}
void init(void)
{
this->mDirectory = "";
this->mName = "";
this->mExtension = "";
}
bool parse(std::string path)
{
init();
size_t periodCount = std::count_if(path.begin(), path.end(), [](char c) {return c == '.'; });
if (path[0] == '.' && periodCount == 1)
{
mExtension = path.substr(1);
return true;
}
// Must be at least one slash to contain a directory.
size_t iLastSlash = path.find_last_of("\\/");
if (iLastSlash != std::string::npos)
{
this->mDirectory = path.substr(0, iLastSlash);
this->mDirectory = this->mDirectory.substr(0, this->mDirectory.find_last_not_of("\\/") + 1);
// No wildcards allowed in the directory.
if (this->mDirectory.find_first_of("*?[]{}") != std::string::npos)
return false;
}
// Period, plus no later slash, constitutes an extension.
size_t iLastPeriod = path.find_last_of(".");
if (iLastPeriod != std::string::npos && (iLastSlash == std::string::npos || iLastPeriod > iLastSlash))
{
this->mExtension = path.substr(path.find_last_of(".") + 1);
}
path = path.substr(0, iLastPeriod); // Remove extension.
path = path.substr(path.find_last_of("\\/") + 1); // Remove directory.
this->mName = path;
return true;
}
};
}
+358
View File
@@ -0,0 +1,358 @@
/*
* Copyright (c) 2020-2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* SPDX-FileCopyrightText: Copyright (c) 2020-2025 NVIDIA CORPORATION & AFFILIATES
* SPDX-License-Identifier: BSD-3-Clause
*/
// Visualizing and Communicating Errors in Rendered Images
// Ray Tracing Gems II, 2021,
// by Pontus Andersson, Jim Nilsson, and Tomas Akenine-Moller.
// Pointer to the chapter: https://research.nvidia.com/publication/2021-08_Visualizing-and-Communicating.
// Visualizing Errors in Rendered High Dynamic Range Images
// Eurographics 2021,
// by Pontus Andersson, Jim Nilsson, Peter Shirley, and Tomas Akenine-Moller.
// Pointer to the paper: https://research.nvidia.com/publication/2021-05_HDR-FLIP.
// FLIP: A Difference Evaluator for Alternating Images
// High Performance Graphics 2020,
// by Pontus Andersson, Jim Nilsson, Tomas Akenine-Moller,
// Magnus Oskarsson, Kalle Astrom, and Mark D. Fairchild.
// Pointer to the paper: https://research.nvidia.com/publication/2020-07_FLIP.
// Code by Pontus Ebelin (formerly Andersson), Jim Nilsson, and Tomas Akenine-Moller.
#pragma once
#include <string>
#include <iostream>
#include <algorithm>
#define TINYEXR_IMPLEMENTATION
#include "tinyexr.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
namespace ImageHelpers
{
bool ldrLoad(const std::string& filename, int& imgWidth, int& imgHeight, float*& pixels)
{
int bpp;
unsigned char* ldrPixels = stbi_load(filename.c_str(), &imgWidth, &imgHeight, &bpp, 3);
if (!ldrPixels)
{
return false;
}
pixels = new float[3 * imgWidth * imgHeight];
#pragma omp parallel for
for (int y = 0; y < imgHeight; y++)
{
for (int x = 0; x < imgWidth; x++)
{
int linearIdx = 3 * (y * imgWidth + x);
pixels[linearIdx + 0] = ldrPixels[linearIdx + 0] / 255.0f;
pixels[linearIdx + 1] = ldrPixels[linearIdx + 1] / 255.0f;
pixels[linearIdx + 2] = ldrPixels[linearIdx + 2] / 255.0f;
}
}
delete[] ldrPixels;
return true;
}
bool hdrLoad(const std::string& fileName, int& imgWidth, int& imgHeight, float*& hdrPixels)
{
EXRVersion exrVersion;
EXRImage exrImage;
EXRHeader exrHeader;
InitEXRHeader(&exrHeader);
InitEXRImage(&exrImage);
{
int ret;
const char* errorString;
ret = ParseEXRVersionFromFile(&exrVersion, fileName.c_str());
if (ret != TINYEXR_SUCCESS || exrVersion.multipart || exrVersion.non_image)
{
std::cerr << "Unsupported EXR version or type!" << std::endl;
return false;
}
ret = ParseEXRHeaderFromFile(&exrHeader, &exrVersion, fileName.c_str(), &errorString);
if (ret != TINYEXR_SUCCESS)
{
std::cerr << "Error loading EXR header: " << errorString << std::endl;
return false;
}
for (int i = 0; i < exrHeader.num_channels; i++)
{
if (exrHeader.pixel_types[i] == TINYEXR_PIXELTYPE_HALF)
{
exrHeader.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
}
}
ret = LoadEXRImageFromFile(&exrImage, &exrHeader, fileName.c_str(), &errorString);
if (ret != TINYEXR_SUCCESS)
{
std::cerr << "Error loading EXR file: " << errorString << std::endl;
return false;
}
}
imgWidth = exrImage.width;
imgHeight = exrImage.height;
int idxR = -1;
int idxG = -1;
int idxB = -1;
int numRecognizedChannels = 0;
for (int c = 0; c < exrHeader.num_channels; c++)
{
std::string channelName = exrHeader.channels[c].name;
std::transform(channelName.begin(), channelName.end(), channelName.begin(), ::tolower);
if (channelName == "r")
{
idxR = c;
++numRecognizedChannels;
}
else if (channelName == "g")
{
idxG = c;
++numRecognizedChannels;
}
else if (channelName == "b")
{
idxB = c;
++numRecognizedChannels;
}
else if (channelName == "a")
{
++numRecognizedChannels;
}
}
auto rawImgChn = reinterpret_cast<float**>(exrImage.images);
bool loaded = false;
hdrPixels = new float[imgWidth * imgHeight * 3];
if (numRecognizedChannels == 1) // 1 channel images can be loaded into either scalar or vector formats.
{
for (int y = 0; y < imgHeight; y++)
{
for (int x = 0; x < imgWidth; x++)
{
int linearIdx = y * imgWidth + x;
float color(rawImgChn[0][linearIdx]);
hdrPixels[3 * linearIdx + 0] = color;
hdrPixels[3 * linearIdx + 1] = color;
hdrPixels[3 * linearIdx + 2] = color;
}
}
loaded = true;
}
else if (numRecognizedChannels == 2) // 2 channel images can only be loaded into vector2/3/4 formats.
{
assert(idxR != -1 && idxG != -1);
#pragma omp parallel for
for (int y = 0; y < imgHeight; y++)
{
for (int x = 0; x < imgWidth; x++)
{
int linearIdx = y * imgWidth + x;
hdrPixels[3 * linearIdx + 0] = rawImgChn[idxR][linearIdx];
hdrPixels[3 * linearIdx + 1] = rawImgChn[idxG][linearIdx];
hdrPixels[3 * linearIdx + 2] = 0.0f;
}
}
loaded = true;
}
else if (numRecognizedChannels == 3 || numRecognizedChannels == 4) // 3 or 4 channel images can only be loaded into vector3/4 formats.
{
assert(idxR != -1 && idxG != -1 && idxB != -1);
#pragma omp parallel for
for (int y = 0; y < imgHeight; y++)
{
for (int x = 0; x < imgWidth; x++)
{
int linearIdx = y * imgWidth + x;
hdrPixels[3 * linearIdx + 0] = rawImgChn[idxR][linearIdx];
hdrPixels[3 * linearIdx + 1] = rawImgChn[idxG][linearIdx];
hdrPixels[3 * linearIdx + 2] = rawImgChn[idxB][linearIdx];
}
}
loaded = true;
}
FreeEXRHeader(&exrHeader);
FreeEXRImage(&exrImage);
if (!loaded)
{
std::cerr << "Insufficient target channels when loading EXR: need " << exrHeader.num_channels << std::endl;
return false;
}
else
{
return true;
}
}
// Note that when an image us loaded, the variable pixels is allocated, and it is up to the user to deallocate it later.
bool loadImage(const std::string& fileName, int& imgWidth, int& imgHeight, float*& pixels)
{
bool bOk = false;
std::string extension = fileName.substr(fileName.find_last_of(".") + 1);
if (extension == "png" || extension == "bmp" || extension == "tga")
{
bOk = ldrLoad(fileName, imgWidth, imgHeight, pixels);
}
else if (extension == "exr")
{
bOk = hdrLoad(fileName, imgWidth, imgHeight, pixels);
}
return bOk;
}
bool load(FLIP::image<FLIP::color3>& dstImage, const std::string& fileName)
{
int imgWidth;
int imgHeight;
float* pixels;
if (loadImage(fileName, imgWidth, imgHeight, pixels))
{
dstImage.setPixels(pixels, imgWidth, imgHeight);
delete[] pixels;
return true;
}
return false;
}
bool pngSave(const std::string& filename, FLIP::image<FLIP::color3>& image)
{
unsigned char* pixels = new unsigned char[3 * image.getWidth() * image.getHeight()];
#ifdef FLIP_ENABLE_CUDA
image.synchronizeHost();
#endif
#pragma omp parallel for
for (int y = 0; y < image.getHeight(); y++)
{
for (int x = 0; x < image.getWidth(); x++)
{
int index = image.index(x, y);
FLIP::color3 color = image.get(x, y);
pixels[3 * index + 0] = (unsigned char)(255.0f * std::clamp(color.x, 0.0f, 1.0f) + 0.5f);
pixels[3 * index + 1] = (unsigned char)(255.0f * std::clamp(color.y, 0.0f, 1.0f) + 0.5f);
pixels[3 * index + 2] = (unsigned char)(255.0f * std::clamp(color.z, 0.0f, 1.0f) + 0.5f);
}
}
int ok = stbi_write_png(filename.c_str(), image.getWidth(), image.getHeight(), 3, pixels, 3 * image.getWidth());
delete[] pixels;
return (ok != 0);
}
bool exrSave(const std::string& fileName, FLIP::image<FLIP::color3>& image)
{
#ifdef FLIP_ENABLE_CUDA
image.synchronizeHost();
#endif
constexpr int channels = 3;
float* vpImage[channels] = {};
std::vector<float> vImages[channels];
for (int i = 0; i < channels; ++i)
{
vImages[i].resize(image.getWidth() * image.getHeight());
}
int pixelIndex = 0;
for (int y = 0; y < image.getHeight(); y++)
{
for (int x = 0; x < image.getWidth(); x++)
{
FLIP::color3 p = image.get(x, y);
vImages[0][pixelIndex] = p.r;
vImages[1][pixelIndex] = p.g;
vImages[2][pixelIndex] = p.b;
pixelIndex++;
}
}
vpImage[0] = &(vImages[2].at(0)); // B
vpImage[1] = &(vImages[1].at(0)); // G
vpImage[2] = &(vImages[0].at(0)); // R
EXRHeader exrHeader;
InitEXRHeader(&exrHeader);
exrHeader.num_channels = channels;
exrHeader.channels = (EXRChannelInfo*)malloc(channels * sizeof(EXRChannelInfo));
exrHeader.pixel_types = (int*)malloc(channels * sizeof(int));
exrHeader.requested_pixel_types = (int*)malloc(channels * sizeof(int));
exrHeader.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;
for (int i = 0; i < channels; i++)
{
exrHeader.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
exrHeader.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
exrHeader.channels[i].name[1] = '\0';
}
exrHeader.channels[0].name[0] = 'B';
exrHeader.channels[1].name[0] = 'G';
exrHeader.channels[2].name[0] = 'R';
EXRImage exrImage;
InitEXRImage(&exrImage);
exrImage.num_channels = channels;
exrImage.images = (unsigned char**)vpImage;
exrImage.width = image.getWidth();
exrImage.height = image.getHeight();
const char* error;
int ret = SaveEXRImageToFile(&exrImage, &exrHeader, fileName.c_str(), &error);
free(exrHeader.channels);
free(exrHeader.pixel_types);
free(exrHeader.requested_pixel_types);
if (ret != TINYEXR_SUCCESS)
{
std::cerr << "Failed to save EXR file <" << fileName << ">: " << error << "\n";
return false;
}
return true;
}
}
+561
View File
@@ -0,0 +1,561 @@
/*
* Copyright (c) 2020-2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* SPDX-FileCopyrightText: Copyright (c) 2020-2025 NVIDIA CORPORATION & AFFILIATES
* SPDX-License-Identifier: BSD-3-Clause
*/
// Visualizing and Communicating Errors in Rendered Images
// Ray Tracing Gems II, 2021,
// by Pontus Andersson, Jim Nilsson, and Tomas Akenine-Moller.
// Pointer to the chapter: https://research.nvidia.com/publication/2021-08_Visualizing-and-Communicating.
// Visualizing Errors in Rendered High Dynamic Range Images
// Eurographics 2021,
// by Pontus Andersson, Jim Nilsson, Peter Shirley, and Tomas Akenine-Moller.
// Pointer to the paper: https://research.nvidia.com/publication/2021-05_HDR-FLIP.
// FLIP: A Difference Evaluator for Alternating Images
// High Performance Graphics 2020,
// by Pontus Andersson, Jim Nilsson, Tomas Akenine-Moller,
// Magnus Oskarsson, Kalle Astrom, and Mark D. Fairchild.
// Pointer to the paper: https://research.nvidia.com/publication/2020-07_FLIP.
// Code by Pontus Ebelin (formerly Andersson), Jim Nilsson, and Tomas Akenine-Moller.
#pragma once
#include <cmath>
#include <vector>
#include <string>
#include <cstdint>
#include <sstream>
#include <fstream>
#include <iostream>
#include <algorithm>
namespace FLIPPooling
{
template <typename T>
class histogram
{
private:
T mMinValue, mMaxValue;
size_t mValueCount, mErrorValueCount;
T mBucketSize;
std::vector<size_t> mvBuckets;
size_t mBucketIdRange[2];
size_t mBucketIdMax;
public:
histogram(size_t buckets, T minValue = 0.0, T maxValue = 1.0)
{
this->init(buckets, minValue, maxValue);
}
void init(size_t buckets, T minValue, T maxValue, size_t value = 0)
{
this->mMinValue = minValue;
this->mMaxValue = maxValue;
this->mValueCount = 0;
this->mErrorValueCount = 0;
this->mBucketIdRange[0] = std::string::npos;
this->mBucketIdRange[1] = 0;
this->resize(buckets);
this->mvBuckets.resize(buckets, value);
}
T getBucketSize() const { return mBucketSize; }
size_t getBucketIdMin() const { return mBucketIdRange[0]; }
size_t getBucketIdMax() const { return mBucketIdRange[1]; }
size_t getBucketValue(size_t bucketId) const { return mvBuckets[bucketId]; }
size_t size() const { return mvBuckets.size(); }
T getMinValue() const { return this->mMinValue; }
T getMaxValue() const { return this->mMaxValue; }
T getBucketStep() const { return (this->mMaxValue - this->mMinValue) / this->mvBuckets.size(); }
void clear()
{
this->mvBuckets.resize(mvBuckets.size(), 0);
}
void resize(size_t buckets)
{
this->mBucketSize = (this->mMaxValue - this->mMinValue) / buckets;
this->mvBuckets.resize(buckets);
}
size_t valueBucketId(T value) const
{
if (value < this->mMinValue || value > this->mMaxValue)
return std::string::npos;
size_t bucketId = size_t(double(value) / this->mBucketSize);
if (bucketId == this->mvBuckets.size())
{
bucketId--;
}
return bucketId;
}
void inc(T value, size_t amount = 1)
{
size_t bucketId = valueBucketId(value);
if (bucketId != std::string::npos)
{
this->mvBuckets[bucketId] += amount;
this->mValueCount += amount;
this->mBucketIdRange[0] = std::min(this->mBucketIdRange[0], bucketId);
this->mBucketIdRange[1] = std::max(this->mBucketIdRange[1], bucketId);
}
else
{
mErrorValueCount += amount;
}
}
std::string toPython(const std::string fileName, const size_t numPixels, const T meanValue, const T maxValue, const T minValue, const T weightedMedian, const T firstWeightedQuartile, const T thirdWeightedQuartile, const bool optionLog, const bool includeValues, const float yMax) const
{
std::stringstream ss;
T bucketStep = getBucketStep();
// imports
ss << "import matplotlib.pyplot as plt\n";
ss << "import os\n";
ss << "import sys\n";
ss << "import numpy as np\n";
ss << "from matplotlib.ticker import (MultipleLocator)\n\n";
ss << "dimensions = (25, 15) # centimeters\n\n";
ss << "lineColor = 'blue'\n";
ss << "fillColor = 'lightblue'\n";
ss << "meanLineColor = 'red'\n";
ss << "weightedMedianLineColor = 'gray'\n";
ss << "quartileLineColor = 'purple'\n";
ss << "fontSize = 14\n";
ss << "numPixels = " << numPixels << "\n\n";
ss << "meanValue = " << meanValue << "\n";
ss << "maxValue = " << maxValue << "\n";
ss << "minValue = " << minValue << "\n\n";
ss << "weightedMedianValue = " << weightedMedian << "\n\n";
ss << "firstWeightedQuartileValue = " << firstWeightedQuartile << "\n\n";
ss << "thirdWeightedQuartileValue = " << thirdWeightedQuartile << "\n\n";
// X-axis
ss << "dataX = [";
for (size_t bucketId = 0; bucketId < this->mvBuckets.size(); bucketId++)
{
ss << (bucketId > 0 ? ", " : "");
ss << bucketStep * bucketId + 0.5 * bucketStep;
}
ss << "]\n\n";
// FLIP histogram.
ss << "dataFLIP = [";
for (size_t bucketId = 0; bucketId < this->mvBuckets.size(); bucketId++)
{
ss << (bucketId > 0 ? ", " : "");
ss << this->mvBuckets[bucketId];
}
ss << "]\n\n";
// Weighted FLIP histogram.
ss << "bucketStep = " << bucketStep << "\n";
ss << "weightedDataFLIP = np.empty(" << this->mvBuckets.size() << ")\n";
ss << "moments = np.empty(" << this->mvBuckets.size() << ")\n";
ss << "for i in range(" << this->mvBuckets.size() << ") :\n";
ss << "\tweight = (i + 0.5) * bucketStep\n";
ss << "\tweightedDataFLIP[i] = dataFLIP[i] * weight\n";
ss << "weightedDataFLIP /= (numPixels /(1024 * 1024)) # normalized with the number of megapixels in the image\n\n";
if (optionLog)
{
ss << "for i in range(" << this->mvBuckets.size() << ") :\n";
ss << "\tif weightedDataFLIP[i] > 0 :\n";
ss << "\t\tweightedDataFLIP[i] = np.log10(weightedDataFLIP[i]) # avoid log of zero\n\n";
}
if (yMax != 0.0f)
{
ss << "maxY = " << yMax << "\n\n";
}
else
{
ss << "maxY = max(weightedDataFLIP)\n\n";
}
ss << "sumWeightedDataFLIP = sum(weightedDataFLIP)\n\n";
ss << "font = { 'family' : 'serif', 'style' : 'normal', 'weight' : 'normal', 'size' : fontSize }\n";
ss << "lineHeight = fontSize / (dimensions[1] * 15)\n";
ss << "plt.rc('font', **font)\n";
ss << "fig = plt.figure()\n";
ss << "axes = plt.axes()\n";
ss << "axes.xaxis.set_minor_locator(MultipleLocator(0.1))\n";
ss << "axes.xaxis.set_major_locator(MultipleLocator(0.2))\n\n";
ss << "fig.set_size_inches(dimensions[0] / 2.54, dimensions[1] / 2.54)\n";
if (optionLog)
{
ss << "axes.set(title = 'Weighted \\uA7FBLIP Histogram', xlabel = '\\uA7FBLIP error', ylabel = 'log(weighted \\uA7FBLIP sum per megapixel)')\n\n";
}
else
{
ss << "axes.set(title = 'Weighted \\uA7FBLIP Histogram', xlabel = '\\uA7FBLIP error', ylabel = 'Weighted \\uA7FBLIP sum per megapixel')\n\n";
}
ss << "plt.bar(dataX, weightedDataFLIP, width = " << bucketStep << ", color = fillColor, edgecolor = lineColor)\n\n";
if (includeValues)
{
ss << "plt.text(0.99, 1.0 - 1 * lineHeight, 'Mean: ' + str(f'{meanValue:.4f}'), ha = 'right', fontsize = fontSize, transform = axes.transAxes, color=meanLineColor)\n\n";
ss << "plt.text(0.99, 1.0 - 2 * lineHeight, 'Weighted median: ' + str(f'{weightedMedianValue:.4f}'), ha = 'right', fontsize = fontSize, transform = axes.transAxes, color=weightedMedianLineColor)\n\n";
ss << "plt.text(0.99, 1.0 - 3 * lineHeight, '1st weighted quartile: ' + str(f'{firstWeightedQuartileValue:.4f}'), ha = 'right', fontsize = fontSize, transform = axes.transAxes, color=quartileLineColor)\n\n";
ss << "plt.text(0.99, 1.0 - 4 * lineHeight, '3rd weighted quartile: ' + str(f'{thirdWeightedQuartileValue:.4f}'), ha = 'right', fontsize = fontSize, transform = axes.transAxes, color=quartileLineColor)\n\n";
ss << "plt.text(0.99, 1.0 - 5 * lineHeight, 'Min: ' + str(f'{minValue:.4f}'), ha = 'right', fontsize = fontSize, transform = axes.transAxes)\n";
ss << "plt.text(0.99, 1.0 - 6 * lineHeight, 'Max: ' + str(f'{maxValue:.4f}'), ha = 'right', fontsize = fontSize, transform = axes.transAxes)\n";
}
ss << "axes.set_xlim(0.0, 1.0)\n";
ss << "axes.set_ylim(0.0, maxY * 1.05)\n";
if (includeValues)
{
ss << "axes.axvline(x = meanValue, color = meanLineColor, linewidth = 1.5)\n\n";
ss << "axes.axvline(x = weightedMedianValue, color = weightedMedianLineColor, linewidth = 1.5)\n\n";
ss << "axes.axvline(x = firstWeightedQuartileValue, color = quartileLineColor, linewidth = 1.5)\n\n";
ss << "axes.axvline(x = thirdWeightedQuartileValue, color = quartileLineColor, linewidth = 1.5)\n\n";
ss << "axes.axvline(x = minValue, color='black', linestyle = ':', linewidth = 1.5)\n\n";
ss << "axes.axvline(x = maxValue, color='black', linestyle = ':', linewidth = 1.5)\n\n";
}
ss << "plt.savefig(\"" << fileName.substr(0, fileName.size() - 3) << ".pdf\")";
ss << std::endl;
return ss.str();
}
};
template <typename T>
class pooling
{
private:
size_t mValueCount;
T mValueSum;
T mSquareValueSum;
T mMinValue;
T mMaxValue;
uint32_t mMinCoord[2];
uint32_t mMaxCoord[2];
histogram<T> mHistogram = histogram<T>(100);
bool mDataSorted = false;
std::vector<T> mvData;
public:
pooling() { clear(); }
pooling(size_t buckets) { mHistogram.resize(buckets); clear(); }
histogram<T>& getHistogram() { return mHistogram; }
T getMinValue(void) const { return mMinValue; }
T getMaxValue(void) const { return mMaxValue; }
T getMean(void) const { return mValueSum / mValueCount; }
double getWeightedPercentile(const double percent) const
{
double weight;
double weightedValue;
double bucketStep = mHistogram.getBucketStep();
double sumWeightedDataValue = 0.0;
for (size_t bucketId = 0; bucketId < mHistogram.size(); bucketId++)
{
weight = (bucketId + 0.5) * bucketStep;
weightedValue = mHistogram.getBucketValue(bucketId) * weight;
sumWeightedDataValue += weightedValue;
}
double sum = 0;
size_t weightedMedianIndex = 0;
for (size_t bucketId = 0; bucketId < mHistogram.size(); bucketId++)
{
weight = (bucketId + 0.5) * bucketStep;
weightedValue = mHistogram.getBucketValue(bucketId) * weight;
weightedMedianIndex = bucketId;
if (sum + weightedValue > percent * sumWeightedDataValue)
break;
sum += weightedValue;
}
weight = (weightedMedianIndex + 0.5) * bucketStep;
weightedValue = mHistogram.getBucketValue(weightedMedianIndex) * weight;
double discrepancy = percent * sumWeightedDataValue - sum;
double linearWeight = discrepancy / weightedValue; // In [0,1].
double percentile = (weightedMedianIndex + linearWeight) * bucketStep;
return percentile;
}
T getPercentile(const float percent, const bool bWeighted = false)
{
if (!mDataSorted)
{
std::sort(mvData.begin(), mvData.end());
mDataSorted = true;
}
T percentile = T(0);
if (bWeighted)
{
T runningSum = T(0);
for (size_t i = 0; i < mvData.size(); i++)
{
runningSum += mvData[i];
if (runningSum > percent * mValueSum)
{
percentile = mvData[i];
break;
}
}
}
else
{
// Using the nearest-rank method.
percentile = mvData[size_t(std::ceil(mvData.size() * percent))];
}
return percentile;
}
void clear()
{
mValueCount = 0;
mValueSum = T(0);
mSquareValueSum = T(0);
mMinValue = std::numeric_limits<T>::max();
mMaxValue = std::numeric_limits<T>::min();
mvData.clear();
mHistogram.clear();
}
void update(uint32_t xcoord, uint32_t ycoord, T value)
{
mValueCount++;
mValueSum += value;
mSquareValueSum += (value * value);
mHistogram.inc(value);
mvData.push_back(value);
mDataSorted = false;
if (value < mMinValue)
{
mMinValue = value;
mMinCoord[0] = xcoord;
mMinCoord[1] = ycoord;
}
if (value > mMaxValue)
{
mMaxValue = value;
mMaxCoord[0] = xcoord;
mMaxCoord[1] = ycoord;
}
}
void save(const std::string& fileName, size_t imgWidth, size_t imgHeight, const bool optionLog, const bool includeValues, const float yMax)
{
std::ofstream file;
std::string pyFileName = fileName;
size_t area = size_t(imgWidth) * size_t(imgHeight);
// Python output.
std::ofstream pythonHistogramFile;
pythonHistogramFile.open(pyFileName);
pythonHistogramFile << mHistogram.toPython(pyFileName, area, getMean(), getMaxValue(), getMinValue(), getPercentile(0.5f, true), getPercentile(0.25f, true), getPercentile(0.75f, true), optionLog, includeValues, yMax);
pythonHistogramFile.close();
}
void saveOverlappedHistogram(pooling firstPooledValues, const std::string& fileName, const size_t imgWidth, const size_t imgHeight, const bool optionLog, const std::string referenceFileName, const std::string firstTestFileName, const std::string testFileName, const bool includeValues, const float yMax) const
{
// Create histogram.
size_t numPixels = size_t(imgWidth) * size_t(imgHeight);
size_t bucketsSize = firstPooledValues.getHistogram().size();
T bucketStep = this->mHistogram.getBucketStep();
float firstPooledValuesMean = firstPooledValues.getMean();
float meanValue = this->getMean();
std::stringstream ss;
// Imports.
ss << "import matplotlib.pyplot as plt\n";
ss << "import sys\n";
ss << "import numpy as np\n";
ss << "from matplotlib.ticker import (MultipleLocator)\n\n";
ss << "dimensions = (25, 15) # centimeters\n\n";
ss << "lineColor = 'green'\n";
ss << "lineColor2 = 'blue'\n";
ss << "fillColorBelow = [118 / 255, 185 / 255, 0]\n";
ss << "fillColorAbove = 'lightblue'\n";
ss << "meanLineColor = [107 / 255, 168 / 255, 0]\n";
ss << "meanLineColor2 = [113 / 255, 171 / 255, 189 / 255]\n";
ss << "fontSize = 14\n\n";
ss << "numPixels = " << numPixels << "\n\n";
ss << "font = { 'family' : 'serif', 'style' : 'normal', 'weight' : 'normal', 'size' : fontSize }\n";
ss << "lineHeight = fontSize / (dimensions[1] * 15)\n";
ss << "plt.rc('font', **font)\n\n";
ss << "fig = plt.figure()\n";
ss << "fig.set_size_inches(dimensions[0] / 2.54, dimensions[1] / 2.54)\n";
ss << "meanValue = " << firstPooledValuesMean << "\n";
ss << "meanValue2 = " << meanValue << "\n";
// X-axis.
ss << "dataX = [";
for (size_t bucketId = 0; bucketId < bucketsSize; bucketId++)
{
ss << (bucketId > 0 ? ", " : "");
ss << bucketStep * bucketId + 0.5 * bucketStep;
}
ss << "]\n\n";
// FLIP histogram.
ss << "dataFLIP = [";
for (size_t bucketId = 0; bucketId < bucketsSize; bucketId++)
{
ss << (bucketId > 0 ? ", " : "");
ss << firstPooledValues.getHistogram().getBucketValue(bucketId);
}
ss << "]\n\n";
ss << "dataFLIP2 = [";
for (size_t bucketId = 0; bucketId < bucketsSize; bucketId++)
{
ss << (bucketId > 0 ? ", " : "");
ss << this->mHistogram.getBucketValue(bucketId);
}
ss << "]\n\n";
// Weighted FLIP histogram.
ss << "bucketStep = " << bucketStep << "\n";
ss << "weightedDataFLIP = np.empty(" << bucketsSize << ")\n";
ss << "weightedDataFLIP2 = np.empty(" << bucketsSize << ")\n";
ss << "for i in range(" << bucketsSize << ") :\n";
ss << "\tweight = (i + 0.5) * bucketStep\n";
ss << "\tweightedDataFLIP[i] = dataFLIP[i] * weight\n";
ss << "\tweightedDataFLIP2[i] = dataFLIP2[i] * weight\n";
ss << "weightedDataFLIP /= (numPixels /(1024 * 1024)) # normalized with the number of megapixels in the image\n";
ss << "weightedDataFLIP2 /= (numPixels /(1024 * 1024)) # normalized with the number of megapixels in the image\n\n";
if (optionLog)
{
ss << "for i in range(" << bucketsSize << ") :\n";
ss << "\tif weightedDataFLIP[i] > 0 :\n";
ss << "\t\tweightedDataFLIP[i] = np.log10(weightedDataFLIP[i]) # avoid log of zero\n";
ss << "\tif weightedDataFLIP2[i] > 0 :\n";
ss << "\t\tweightedDataFLIP2[i] = np.log10(weightedDataFLIP2[i]) # avoid log of zero\n\n";
}
if (yMax != 0.0f)
{
ss << "maxY = " << yMax << "\n\n";
}
else
{
ss << "maxY = 1.05 * max(max(weightedDataFLIP), max(weightedDataFLIP2))\n\n";
}
ss << "axes = plt.axes()\n";
ss << "axes.xaxis.set_minor_locator(MultipleLocator(0.1))\n";
ss << "axes.xaxis.set_major_locator(MultipleLocator(0.2))\n";
ss << "axes.set_xlim(0.0, 1.0)\n";
ss << "axes.set_ylim(0.0, maxY)\n\n";
if (optionLog)
{
ss << "axes.set(title = 'Weighted \\uA7FBLIP Histogram', xlabel = '\\uA7FBLIP error', ylabel = 'log(weighted \\uA7FBLIP sum per megapixel)')\n";
}
else
{
ss << "axes.set(title = 'Weighted \\uA7FBLIP Histogram', xlabel = '\\uA7FBLIP error', ylabel = 'Weighted \\uA7FBLIP sum per megapixel')\n";
}
if (includeValues)
{
ss << "if " << includeValues << ":\n";
ss << "\taxes.axvline(x = meanValue, color = meanLineColor, linewidth = 1.5)\n";
ss << "\taxes.axvline(x = meanValue2, color = meanLineColor2, linewidth = 1.5)\n";
ss << "\tplt.text(0.99, 1.0 - 1 * lineHeight, 'Mean (" << firstTestFileName << "): ' + str(f'{meanValue:.4f}'), ha = 'right', fontsize = fontSize, transform = axes.transAxes, color = meanLineColor)\n";
ss << "\tplt.text(0.99, 1.0 - 2 * lineHeight, 'Mean (" << testFileName << "): ' + str(f'{meanValue2:.4f}'), ha = 'right', fontsize = fontSize, transform = axes.transAxes, color = meanLineColor2)\n";
}
ss << "sumWeightedDataFLIP = sum(weightedDataFLIP)\n\n";
ss << "sumWeightedDataFLIP2 = sum(weightedDataFLIP2)\n\n";
ss << "bins = np.arange(101) / 100\n";
ss << "plt.hist(bins[:-1], bins = bins, weights = weightedDataFLIP, ec = lineColor, alpha = 0.5, color = fillColorBelow)\n";
ss << "plt.hist(bins[:-1], bins = bins, weights = weightedDataFLIP2, ec = lineColor2, alpha = 0.5, color = fillColorAbove)\n\n";
// Construct final histogram filename.
std::string finalFileName;
std::string subFileName = fileName;
size_t lastIndex = subFileName.find_last_of("/");
finalFileName = subFileName.substr(0, lastIndex) + "/" + (optionLog ? "log_" : "") + "overlapping_weighted_histogram.flip." + referenceFileName + ".";
subFileName = subFileName.substr(lastIndex + 1);
size_t firstIndex;
for (int q = 0; q < 3; q++)
{
firstIndex = subFileName.find_first_of(".");
subFileName = subFileName.substr(firstIndex + 1);
}
finalFileName.append(firstTestFileName).append(".").append(subFileName);
ss << "plt.savefig(\"" << finalFileName.substr(0, finalFileName.size() - 3) << ".pdf\")";
ss << std::endl;
// Save histogram (see save() above).
std::ofstream file;
std::string pyFileName = finalFileName;
std::ofstream pythonHistogramFile;
pythonHistogramFile.open(pyFileName);
pythonHistogramFile << ss.str();
pythonHistogramFile.close();
}
};
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+15187
View File
File diff suppressed because it is too large Load Diff