build system and module refactoring + simple histogram scratch (#20)
MegaLinter / MegaLinter (push) Has been cancelled
CI Workflow / build-ubuntu (push) Has been cancelled
CI Workflow / build-windows (push) Has been cancelled
CI Workflow / generate-docs (push) Has been cancelled

* scratch adding histogram to image views

Histograms should come from some sort of histogram service. This is
currently just a POC.

* custom logger implementation w/o spdlog

* missing cmake file

* fix tests

* use operator<< over direct stream exposure

* rm print header

* add threading test + refactor towards interface libraries

omits the need for =target_include_directories= calls /everywhere/

* rm print header

* rm constexpr

* templated thread_pool

* fix doxyfile

* default enable doc building

* czi reader refactor

* rm erroneous include expression

* clang-format

* single lib include with PUBLIC visibility

* compile imgui stdlib

* clang format

* documentation update

centralize `LogLevelToString` to `ILog.hpp`

update docs and examples
This commit is contained in:
m-aXimilian
2026-02-08 12:09:02 +01:00
committed by Maximilian Kueffner
parent b37814204f
commit c00c2c71ac
60 changed files with 797 additions and 416 deletions
+3 -16
View File
@@ -5,7 +5,7 @@
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include "imgui_internal.h"
#include "utilities/simple_thread_pool.hpp"
#include "simple_thread_pool.hpp"
// see https://github.com/ocornut/imgui/issues/3518
bool PixelBeginStatusBar()
@@ -214,20 +214,7 @@ void pixelarium::application::AppGLFW::MenuBar()
// main menu
if (ImGui::BeginMenu(MAINMENUNAME))
{
if (ImGui::BeginCombo(LOGLEVELSELECT, LOGLEVELS[log_level_].data()))
{
for (int n = 0; n < static_cast<int>(LOGLEVELS.size()); n++)
{
bool is_selected = (LOGLEVELS[log_level_] == LOGLEVELS[n]);
if (ImGui::Selectable(LOGLEVELS[n].data(), is_selected))
{
log_level_ = n;
this->logger_.ChangeLevel(static_cast<utils::log::LogLevel>(1 << log_level_));
}
if (is_selected) ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
LogLevelSelect();
// consumer main menu bar entries
this->MenuBarOptionsColumn1();
@@ -279,7 +266,7 @@ void pixelarium::application::AppGLFW::LogLevelSelect()
void pixelarium::application::AppGLFW::SetStatusTimed(const std::string& status, size_t seconds)
{
SetStatus(status);
utils::simple_thread_pool::run_asynch(
utils::pixelarium_pool::enqueue(
[this, seconds]()
{
std::this_thread::sleep_for(std::chrono::seconds(seconds));
+48 -26
View File
@@ -1,45 +1,65 @@
# Fetch implot
include(implot)
message(STATUS "IMPLOT sources at ${IMPLOT_DIR}")
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/app_resources_default.h.in
${CMAKE_BINARY_DIR}/app_resources_default.h @ONLY)
set(IMPLOTSRC
"${IMPLOT_DIR}/implot.h"
"${IMPLOT_DIR}/implot_internal.h"
"${IMPLOT_DIR}/implot_items.cpp"
"${IMPLOT_DIR}/implot.cpp"
"${IMPLOT_DIR}/implot_demo.cpp"
)
set(IMGUISRC
"${imgui_DIR}/imgui.cpp"
"${imgui_DIR}/misc/cpp/imgui_stdlib.cpp"
"${imgui_DIR}/imgui_demo.cpp"
"${imgui_DIR}/imgui_draw.cpp"
"${imgui_DIR}/imgui_tables.cpp"
"${imgui_DIR}/imgui_widgets.cpp"
"${imgui_DIR}/backends/imgui_impl_opengl3.cpp"
"${imgui_DIR}/backends/imgui_impl_glfw.cpp")
set(APPLIBSRC
AppGLFW.hpp
include/imgui_proxy.hpp
include/AppGLFW.hpp
include/DefaultApp.hpp
include/PixelariumGallery.hpp
AppGLFW.cpp
DefaultApp.hpp
DefaultApp.cpp
PixelariumGallery.hpp
PixelariumGallery.cpp
${imgui_DIR}/imgui.cpp
${imgui_DIR}/imgui_demo.cpp
${imgui_DIR}/imgui_draw.cpp
${imgui_DIR}/imgui_tables.cpp
${imgui_DIR}/imgui_widgets.cpp
${imgui_DIR}/backends/imgui_impl_opengl3.cpp
${imgui_DIR}/backends/imgui_impl_glfw.cpp)
PixelariumGallery.cpp)
set(RENDERSRC
rendering/RenderHelpers.hpp
rendering/include/RenderHelpers.hpp
rendering/include/RenderImageManager.hpp
rendering/include/CvMatRender.hpp
rendering/include/IPixelariumImageView.hpp
rendering/include/PixelariumImageViewDefault.hpp
rendering/include/PixelariumImageViewCzi.hpp
rendering/include/ImageViewFactory.hpp
rendering/RenderHelpers.cpp
rendering/CvMatRender.hpp
rendering/CvMatRender.cpp
rendering/RenderImageManager.hpp
rendering/RenderImageManager.cpp
rendering/IPixelariumImageView.hpp
rendering/IPixelariumImageView.cpp
rendering/PixelariumImageViewDefault.hpp
rendering/RenderImageManager.cpp
rendering/PixelariumImageViewDefault.cpp
rendering/PixelariumImageViewCzi.hpp
rendering/PixelariumImageViewCzi.cpp
rendering/ImageViewFactory.hpp
rendering/ImageViewFactory.cpp)
set(APPLIBNAME pixelariumapplicationlib)
add_library(${APPLIBNAME}
STATIC ${APPLIBSRC} ${RENDERSRC})
STATIC ${APPLIBSRC} ${IMGUISRC} ${IMPLOTSRC} ${RENDERSRC})
add_library(pixelarium::lib::application_static ALIAS ${APPLIBNAME})
target_link_libraries(${APPLIBNAME}
PRIVATE pixelariumutilslib
PRIVATE pixelariumimagelib)
PUBLIC
pixelarium::lib::utilities_static
pixelarium::lib::imaging_static
pixelarium::lib::resources_static)
# This needs to be public to let the consumer know about it.
if(WIN32)
@@ -59,10 +79,12 @@ if(APPLE)
endif()
target_include_directories(${APPLIBNAME}
INTERFACE
PRIVATE ${CMAKE_BINARY_DIR}
PRIVATE ${PROJECT_SOURCE_DIR}/lib
PRIVATE ${PROJECT_SOURCE_DIR}/lib/imaging
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/rendering
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/rendering/include
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
PUBLIC ${pfd_DIR}
PUBLIC ${imgui_DIR}
PUBLIC ${imgui_DIR}/backends)
PUBLIC ${imgui_DIR}/misc/cpp
PUBLIC ${imgui_DIR}/backends
${IMPLOT_DIR})
+2 -2
View File
@@ -3,12 +3,12 @@
#include <cstddef>
#include <format>
#include "ILog.hpp"
#include "PixelariumImageFactory.hpp"
#include "app_resources_default.h"
#include "imgui.h"
#include "portable-file-dialogs.h"
#include "resources/resource.hpp"
#include "utilities/ILog.hpp"
#include "resource.hpp"
using namespace pixelarium::imaging;
using namespace pixelarium::application;
@@ -4,7 +4,8 @@
#include <format>
#include "utilities/ILog.hpp"
#include "ILog.hpp"
#include "imgui_proxy.hpp"
namespace pixelarium::application
{
@@ -13,7 +14,18 @@ namespace pixelarium::application
class AppGLFW
{
public:
explicit AppGLFW(const utils::log::ILog& log) : logger_(log) { this->InitMainWindow(); }
explicit AppGLFW(const utils::log::ILog& log) : logger_(log), plot_context_(ImPlot::CreateContext())
{
this->InitMainWindow();
}
~AppGLFW() { ImPlot::DestroyContext(plot_context_); }
AppGLFW(AppGLFW&) = delete;
AppGLFW(const AppGLFW&) = delete;
AppGLFW(AppGLFW&&) = delete;
AppGLFW& operator=(AppGLFW&) = delete;
AppGLFW& operator=(AppGLFW&&) = delete;
/// @brief Start the main render loop
void Start() { this->RunLoop(); }
@@ -61,6 +73,7 @@ class AppGLFW
void LogLevelSelect();
int log_level_{0};
GLFWwindow* window = nullptr;
ImPlotContext* plot_context_ = nullptr;
bool show_status_{false};
std::string status_message_{};
};
@@ -3,10 +3,10 @@
#include <cstddef>
#include "AppGLFW.hpp"
#include "app/PixelariumGallery.hpp"
#include "imgui.h"
#include "resources/resource.hpp"
#include "utilities/ILog.hpp"
#include "ILog.hpp"
#include "PixelariumGallery.hpp"
#include "imgui_proxy.hpp"
#include "resource.hpp"
namespace pixelarium::application
{
@@ -1,8 +1,8 @@
#pragma once
#include "rendering/RenderImageManager.hpp"
#include "resources/resource.hpp"
#include "utilities/ILog.hpp"
#include "ILog.hpp"
#include "RenderImageManager.hpp"
#include "resource.hpp"
namespace pixelarium::application
{
+5
View File
@@ -0,0 +1,5 @@
#pragma once
#include "imgui.h"
#include "imgui_stdlib.h"
#include "implot.h"
+1 -1
View File
@@ -3,7 +3,7 @@
#include <opencv2/core/mat.hpp>
#include <opencv2/imgproc.hpp>
#include "imaging/IPixelariumImage.hpp"
#include "IPixelariumImage.hpp"
using namespace pixelarium::imaging;
+15 -7
View File
@@ -3,22 +3,30 @@
#include <opencv2/imgcodecs.hpp>
#include "app_resources_default.h"
#include "imgui.h"
#include "portable-file-dialogs.h"
auto pixelarium::application::IPixelariumImageView::ImageViewMenuBar() -> void
{
if (ImGui::BeginMenuBar())
{
if (ImGui::MenuItem(SAVEAS))
if (ImGui::BeginMenu("File"))
{
auto dest = pfd::save_file("Save File", ".", {"Image Files", "*.png *.jpg *.jpeg *.tiff"},
pfd::opt::force_overwrite)
.result();
if (!dest.empty())
if (ImGui::MenuItem(SAVEAS))
{
// this->img_->SaveImage(dest);
cv::imwrite(dest, cached_image_);
auto dest = pfd::save_file("Save File", ".", {"Image Files", "*.png *.jpg *.jpeg *.tiff"},
pfd::opt::force_overwrite)
.result();
if (!dest.empty())
{
// this->img_->SaveImage(dest);
cv::imwrite(dest, cached_image_);
}
}
ImageViewMenuBarAdditions();
ImGui::EndMenu();
}
ImGui::EndMenuBar();
+21 -6
View File
@@ -3,11 +3,11 @@
#include <format>
#include <memory>
#include "IPixelariumImage.hpp"
#include "IPixelariumImageView.hpp"
#include "PixelariumImageFactory.hpp"
#include "PixelariumImageViewCzi.hpp"
#include "PixelariumImageViewDefault.hpp"
#include "imaging/IPixelariumImage.hpp"
#include "imaging/PixelariumImageFactory.hpp"
/// @brief Creates a PixelariumImageView from a resource image.
/// @param image_id The ID of the image resource to render.
@@ -19,7 +19,7 @@ std::unique_ptr<pixelarium::application::IPixelariumImageView> pixelarium::appli
using ImageType = imaging::ImageFileType;
auto res{this->image_pool_.GetResource(image_id)};
auto img{res.lock()};
const auto img{res.lock()};
if (img == nullptr)
{
@@ -48,11 +48,26 @@ std::unique_ptr<pixelarium::application::IPixelariumImageView> pixelarium::appli
case ImageType::kMemory:
log_.Info(std::format("{}: Creating a Default View", __PRETTY_FUNCTION__));
// beware: here we copy the actual image resource over to the new image
return std::make_unique<PixelariumImageViewDefault>(img);
try
{
auto view{std::make_unique<PixelariumImageViewDefault>(img)};
return view;
}
catch (const std::exception& ex)
{
log_.Error(std::format("{}: Creating view failed: {}", __PRETTY_FUNCTION__, ex.what()));
}
case ImageType::kCzi:
log_.Info(std::format("{}: Creating a CZI View", __PRETTY_FUNCTION__));
// beware: here we copy the actual image resource over to the new image
return std::make_unique<PixelariumImageViewCzi>(img, log_);
try
{
auto view{std::make_unique<PixelariumImageViewCzi>(img, log_)};
return view;
}
catch (const std::exception& ex)
{
log_.Error(std::format("{}: Creating view failed: {}", __PRETTY_FUNCTION__, ex.what()));
}
default:
return {};
}
+16 -3
View File
@@ -2,11 +2,12 @@
#include <format>
#include <memory>
#include <stdexcept>
#include "CvMatRender.hpp"
#include "IPixelariumImage.hpp"
#include "PixelariumCzi.hpp"
#include "RenderHelpers.hpp"
#include "imaging/IPixelariumImage.hpp"
#include "imaging/impl/PixelariumCzi.hpp"
#include "imgui.h"
void pixelarium::application::PixelariumImageViewCzi::RefreshCachedImage()
@@ -26,7 +27,7 @@ void pixelarium::application::PixelariumImageViewCzi::RefreshCachedImage()
}
pixelarium::application::PixelariumImageViewCzi::PixelariumImageViewCzi(std::shared_ptr<Image> img, const Log& log)
: log_(log), render_(std::make_unique<CvMatRender>(*img->TryGetImage()))
: log_(log)
{
img_ = img;
auto czi_img = std::static_pointer_cast<imaging::PixelariumCzi>(this->img_);
@@ -39,6 +40,18 @@ pixelarium::application::PixelariumImageViewCzi::PixelariumImageViewCzi(std::sha
return true;
});
auto render_mat = img->TryGetImage();
if (render_mat.has_value())
{
this->render_ = std::make_unique<CvMatRender>(render_mat.value());
}
else
{
auto msg{std::format("{}: fetching image failed: {}", __PRETTY_FUNCTION__, img->Name())};
log_.Error(msg);
throw std::runtime_error(msg);
}
// this->SetInitialSize();
log_.Info(std::format("{}: dimension map size: {}", __PRETTY_FUNCTION__, dimension_map_.size()));
}
@@ -1,11 +1,22 @@
#include "PixelariumImageViewDefault.hpp"
#include <format>
#include <opencv2/core/hal/interface.h>
#include <cstdio>
#include <format>
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <ostream>
#include <ranges>
#include <utility>
#include "IPixelariumImage.hpp"
#include "RenderHelpers.hpp"
#include "app_resources_default.h"
#include "imaging/IPixelariumImage.hpp"
#include "imgui.h"
#include "implot.h"
#include "simple_thread_pool.hpp"
void pixelarium::application::PixelariumImageViewDefault::RefreshCachedImage()
{
@@ -16,6 +27,11 @@ void pixelarium::application::PixelariumImageViewDefault::RefreshCachedImage()
}
}
void pixelarium::application::PixelariumImageViewDefault::ImageViewMenuBarAdditions()
{
ImGui::MenuItem("Histogram", NULL, &this->show_hists_);
}
/// @brief Displays the image in an ImGui window.
///
/// If the image is null, empty, or has an empty name, the function returns immediately. Otherwise, it creates an ImGui
@@ -40,6 +56,7 @@ void pixelarium::application::PixelariumImageViewDefault::ShowImage()
const auto cached_heigth{cached_image_.rows};
const auto ratio{static_cast<float>(cached_heigth) / cached_width};
SetInitialSize(kInitialWindowWidth, (kInitialWindowWidth * ratio + 100));
utils::pixelarium_pool::enqueue([this]() { GenerateHistogram(); });
}
ImGui::Begin(this->img_->Name().c_str(), &this->open_p,
@@ -62,8 +79,67 @@ void pixelarium::application::PixelariumImageViewDefault::ShowImage()
aspect_const_dimensions(dim, new_dim));
ImGui::Separator();
if (show_hists_ && hist_available_)
{
if (ImPlot::BeginPlot("Histogram"))
{
ImPlot::SetupAxes(nullptr, nullptr, ImPlotAxisFlags_AutoFit, ImPlotAxisFlags_AutoFit);
using style_pair = std::pair<const char*, ImVec4>;
constexpr std::array<style_pair, 3> names = {
{{"Blue", ImVec4(0, 0, 1, 1)}, {"Green", ImVec4(0, 1, 0, 1)}, {"Red", ImVec4(1, 0, 0, 1)}}};
// for (auto& e : hist_planes_)
// {
// ImPlot::PlotHistogram(name.c_str(), e.data, e.rows * e.cols, 16);
// for (auto& e : name)
// {
// e++;
// }
// }
for (size_t i{0}; i < hist_planes_.size(); ++i)
{
if (hist_planes_.at(i).type() == CV_32F)
{
// ImPlot::PlotHistogram(names.at(i % 3), reinterpret_cast<float*>(hist_planes_[i].data),
// hist_planes_[i].rows * hist_planes_[i].cols, 16, 1.0, ImPlotRange(),
// ImPlotHistogramFlags_Horizontal);
ImPlot::PushStyleColor(ImPlotCol_Line, names.at(i % 3).second);
ImPlot::PlotLine(std::format("{}-line", names.at(i % 3).first).c_str(),
reinterpret_cast<float*>(hist_planes_[i].data),
hist_planes_[i].rows * hist_planes_[i].cols);
ImPlot::PopStyleColor();
}
}
ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f);
ImPlot::SetNextMarkerStyle(ImPlotMarker_Square, 6, ImPlot::GetColormapColor(1), IMPLOT_AUTO,
ImPlot::GetColormapColor(1));
ImPlot::EndPlot();
}
}
ImGui::Text("%s", std::format(" Raw Dimensions W : {}, H: {}", dim.x, dim.y).c_str());
ImGui::Text("%s", std::format("Render Dimensions W : {}, H: {}", curr_dim_.x, curr_dim_.y).c_str());
ImGui::End();
}
auto pixelarium::application::PixelariumImageViewDefault::GenerateHistogram() -> void
{
cv::split(cached_image_, bgr_planes_);
hist_planes_.resize(bgr_planes_.size());
int histSize = 256;
float range[] = {0, 256}; // the upper boundary is exclusive
const float* histRange[] = {range};
for (auto [bgr, hist] : std::ranges::views::zip(bgr_planes_, hist_planes_))
{
cv::calcHist(&bgr, 1, 0, cv::Mat(), hist, 1, &histSize, histRange, true, false);
// cv::normalize(hist, hist);
}
hist_available_ = true;
}
+6 -3
View File
@@ -46,9 +46,10 @@ bool pixelarium::application::RenderImageManager::Remove(resources::ResourceKey
/// @return void. No exception is thrown.
void pixelarium::application::RenderImageManager::Add(resources::ResourceKey key) noexcept
{
// we don't want to add what's already there
// or empty render images
if (this->render_image_map_.contains(key))
// we don't want to add what's already there, render empty images, or failed keys
if (this->render_image_map_.contains(key)
// || this->failed_keys_cache_.contains(key)
)
{
return;
}
@@ -56,6 +57,8 @@ void pixelarium::application::RenderImageManager::Add(resources::ResourceKey key
auto current_view = this->view_factory_->RenderImage(key);
if (current_view == nullptr)
{
// failed to create view, cache this key to avoid repeated attempts
this->failed_keys_cache_.insert(key);
return;
}
@@ -2,7 +2,7 @@
#include <memory>
#include "imaging/IPixelariumImage.hpp"
#include "IPixelariumImage.hpp"
#include "imgui.h"
namespace pixelarium::application
@@ -29,6 +29,7 @@ class IPixelariumImageView
protected:
virtual void ImageViewMenuBar();
virtual void ImageViewMenuBarAdditions() {};
protected:
std::shared_ptr<imaging::IPixelariumImageCvMat> img_{};
@@ -1,8 +1,8 @@
#pragma once
#include "ILog.hpp"
#include "IPixelariumImageView.hpp"
#include "resources/resource.hpp"
#include "utilities/ILog.hpp"
#include "resource.hpp"
namespace pixelarium::application
{
@@ -4,11 +4,11 @@
#include <unordered_map>
#include "CvMatRender.hpp"
#include "ILog.hpp"
#include "IPixelariumImage.hpp"
#include "IPixelariumImageView.hpp"
#include "imaging/IPixelariumImage.hpp"
#include "imgui.h"
#include "libCZI_DimCoordinate.h"
#include "utilities/ILog.hpp"
namespace pixelarium::application
{
@@ -1,10 +1,11 @@
#pragma once
#include <memory>
#include <vector>
#include "CvMatRender.hpp"
#include "IPixelariumImage.hpp"
#include "IPixelariumImageView.hpp"
#include "imaging/IPixelariumImage.hpp"
#include "imgui.h"
namespace pixelarium::application
@@ -16,11 +17,8 @@ class PixelariumImageViewDefault : public IPixelariumImageView
using Image = imaging::IPixelariumImageCvMat;
public:
explicit PixelariumImageViewDefault(std::shared_ptr<Image> img) : render_(*img->TryGetImage())
{
img_ = img;
// this->SetInitialSize();
}
explicit PixelariumImageViewDefault(std::shared_ptr<Image> img) : render_(*img->TryGetImage()) { img_ = img; }
PixelariumImageViewDefault() = delete;
PixelariumImageViewDefault(PixelariumImageViewDefault&) = delete;
PixelariumImageViewDefault(const PixelariumImageViewDefault&) = delete;
@@ -30,9 +28,17 @@ class PixelariumImageViewDefault : public IPixelariumImageView
void ShowImage() override;
void ImageViewMenuBarAdditions() override;
void GenerateHistogram();
private:
ImVec2 curr_dim_{};
CvMatRender render_;
bool show_hists_{false};
bool hist_available_{false};
std::vector<cv::Mat> bgr_planes_;
std::vector<cv::Mat> hist_planes_;
private:
void RefreshCachedImage();
@@ -4,10 +4,10 @@
#include <unordered_map>
#include <unordered_set>
#include "ILog.hpp"
#include "IPixelariumImageView.hpp"
#include "ImageViewFactory.hpp"
#include "resources/resource.hpp"
#include "utilities/ILog.hpp"
#include "resource.hpp"
// This is intended as an additional abstraction
// aggregating views that should be rendered (or not)
@@ -68,6 +68,7 @@ class RenderImageManager
std::unique_ptr<ImageViewFactory> view_factory_;
std::mutex mut_;
std::unordered_set<resources::ResourceKey> keys_to_delete_;
std::unordered_set<resources::ResourceKey> failed_keys_cache_;
const utils::log::ILog& log_;
};
+14 -10
View File
@@ -1,4 +1,4 @@
include(${CMAKE_SOURCE_DIR}/cmake/libCZI.cmake)
include(libCZI)
find_package(OpenCV REQUIRED)
@@ -6,19 +6,19 @@ message(STATUS "Found opencv: " ${OpenCV_INCLUDE_DIRS})
message(STATUS "OpenCV_LIBs from: " ${OpenCV_LIBS})
set(IMAGELIBSRC
IPixelariumImage.hpp
include/IPixelariumImage.hpp
include/PixelariumImageFactory.hpp
impl/include/PixelariumJpg.hpp
impl/include/PixelariumPng.hpp
impl/include/PixelariumCzi.hpp
impl/include/PixelariumTiff.hpp
impl/include/PixelariumMem.hpp
IPixelariumImage.cpp
PixelariumImageFactory.hpp
PixelariumImageFactory.cpp
impl/PixelariumJpg.hpp
impl/PixelariumJpg.cpp
impl/PixelariumPng.hpp
impl/PixelariumPng.cpp
impl/PixelariumCzi.hpp
impl/PixelariumCzi.cpp
impl/PixelariumTiff.hpp
impl/PixelariumTiff.cpp
impl/PixelariumMem.hpp
impl/PixelariumMem.cpp
)
@@ -27,15 +27,19 @@ set(IMAGELIBLIBNAME pixelariumimagelib)
add_library(${IMAGELIBLIBNAME}
STATIC ${IMAGELIBSRC})
add_library(pixelarium::lib::imaging_static ALIAS ${IMAGELIBLIBNAME})
target_compile_definitions(${IMAGELIBLIBNAME} PUBLIC _LIBCZISTATICLIB)
target_link_libraries(${IMAGELIBLIBNAME}
PUBLIC ${OpenCV_LIBS}
PUBLIC pixelariumutilslib
PUBLIC pixelarium::lib::utilities_static
PRIVATE libCZIStatic)
target_include_directories(${IMAGELIBLIBNAME}
PRIVATE ${CMAKE_SOURCE_DIR}/lib
INTERFACE
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/impl/include
PUBLIC ${OpenCV_INCLUDE_DIRS}
PUBLIC ${LIBCZI_INCLUDE_DIR})
+6 -6
View File
@@ -3,12 +3,12 @@
#include <cctype>
#include <memory>
#include "imaging/IPixelariumImage.hpp"
#include "imaging/impl/PixelariumMem.hpp"
#include "impl/PixelariumCzi.hpp"
#include "impl/PixelariumJpg.hpp"
#include "impl/PixelariumPng.hpp"
#include "impl/PixelariumTiff.hpp"
#include "IPixelariumImage.hpp"
#include "PixelariumCzi.hpp"
#include "PixelariumJpg.hpp"
#include "PixelariumMem.hpp"
#include "PixelariumPng.hpp"
#include "PixelariumTiff.hpp"
/*static*/ std::unique_ptr<pixelarium::imaging::IPixelariumImageCvMat>
pixelarium::imaging::PixelariumImageFactory::CreateImage(const std::string& uri, const Log& log)
+42 -72
View File
@@ -7,11 +7,13 @@
#include <opencv2/imgcodecs.hpp>
#include <optional>
#include <stdexcept>
#include <utility>
#include "ILog.hpp"
#include "libCZI.h"
#include "utilities/ILog.hpp"
#include "libCZI_Pixels.h"
namespace
{
bool comp_blockinfo_params(const pixelarium::imaging::CziParams& params, const libCZI::SubBlockInfo& info)
{
bool res{true};
@@ -50,94 +52,62 @@ constexpr int try_get_index_match(const pixelarium::imaging::CziParams& params,
return index;
}
} // namespace
std::optional<cv::Mat> CZISubBlockToCvMat(std::shared_ptr<libCZI::IBitmapData> bitmap, libCZI::PixelType pixeltype,
const pixelarium::utils::log::ILog& log)
{
size_t pixel_size{0};
int target_type;
std::pair<std::string, std::string> pixel_pair;
const auto cv_pixel = GetCVPixelTypeAndSize(pixeltype);
switch (pixeltype)
{
case libCZI::PixelType::Gray8:
pixel_pair.first = "Gray8";
pixel_pair.second = "CV_8U";
pixel_size = 1;
target_type = CV_8U;
break;
case libCZI::PixelType::Gray16:
pixel_pair.first = "Gray16";
pixel_pair.second = "CV_16U";
pixel_size = 2;
target_type = CV_16U;
break;
case libCZI::PixelType::Bgr24:
pixel_pair.first = "Bgr24";
pixel_pair.second = "CV_8UC3";
pixel_size = 3;
target_type = CV_8UC3;
break;
case libCZI::PixelType::Bgra32:
pixel_pair.first = "Bgra32";
pixel_pair.second = "CV_8CU4";
target_type = CV_8UC4;
case libCZI::PixelType::Gray32:
pixel_pair.first = "Gray32";
pixel_pair.second = "CV_32S";
target_type = CV_32S;
case libCZI::PixelType::Gray32Float:
pixel_pair.first = "Gray32Float";
pixel_pair.second = "CV_32F";
target_type = CV_32F;
pixel_size = 4;
break;
default:
pixel_size = -1;
break;
}
if (pixel_size < 0) return std::nullopt;
// ToDo(MAK): fix this makeshift pixel-type-catch
if (cv_pixel.size < 0 || cv_pixel.size > 4) return std::nullopt;
log.Info(std::format("{}: source pixel type {}, target cv pixel type {}, pixel size {}", __PRETTY_FUNCTION__,
pixel_pair.first, pixel_pair.second, pixel_size));
static_cast<uint8_t>(pixeltype), cv_pixel.type, cv_pixel.size));
size_t height{bitmap->GetHeight()};
size_t width{bitmap->GetWidth()};
auto fill_mat = cv::Mat(height, width, target_type);
auto fill_mat = cv::Mat(height, width, cv_pixel.type);
auto bitmap_info = bitmap->Lock();
for (size_t h{0}; h < height; ++h)
if (const auto bitmap_info = bitmap->Lock(); bitmap_info.ptrDataRoi)
{
unsigned char* source_row = ((unsigned char*)bitmap_info.ptrDataRoi) + bitmap_info.stride * h;
unsigned char* target_row = fill_mat.ptr(h);
for (size_t w{0}; w < width; ++w)
for (size_t h{0}; h < height; ++h)
{
switch (pixel_size)
unsigned char* source_row = ((unsigned char*)bitmap_info.ptrDataRoi) + bitmap_info.stride * h;
unsigned char* target_row = fill_mat.ptr(h);
for (size_t w{0}; w < width; ++w)
{
case 1:
target_row[w] = source_row[w];
break;
case 2:
reinterpret_cast<unsigned short*>(target_row)[w] = reinterpret_cast<unsigned short*>(source_row)[w];
break;
case 3:
target_row[3 * w] = source_row[3 * w];
target_row[3 * w + 1] = source_row[3 * w + 1];
target_row[3 * w + 2] = source_row[3 * w + 2];
break;
case 4:
reinterpret_cast<std::int32_t*>(target_row)[w] = reinterpret_cast<std::int32_t*>(source_row)[w];
break;
default:
throw std::runtime_error("Unknown pixel type requested!");
break;
switch (cv_pixel.size)
{
case 1:
target_row[w] = source_row[w];
break;
case 2:
reinterpret_cast<unsigned short*>(target_row)[w] =
reinterpret_cast<unsigned short*>(source_row)[w];
break;
case 3:
target_row[3 * w] = source_row[3 * w];
target_row[3 * w + 1] = source_row[3 * w + 1];
target_row[3 * w + 2] = source_row[3 * w + 2];
break;
case 4:
reinterpret_cast<std::int32_t*>(target_row)[w] = reinterpret_cast<std::int32_t*>(source_row)[w];
break;
default:
throw std::runtime_error("Unknown pixel type requested!");
break;
}
}
}
}
// this is outside of the previous if-clause on purpose:
// no matter if we reach the inner scope of this clause, we locked the bitmap,
// so here it has to be unlocked.
bitmap->Unlock();
return fill_mat;
}
@@ -3,9 +3,41 @@
#include <memory>
#include <string>
#include "../IPixelariumImage.hpp"
#include "ILog.hpp"
#include "IPixelariumImage.hpp"
#include "libCZI.h"
#include "utilities/ILog.hpp"
#include "libCZI_Pixels.h"
namespace
{
struct CvPixelTypeAndSize
{
int size{-1};
int type{-1};
};
template <typename P>
[[nodiscard]] constexpr auto GetCVPixelTypeAndSize(P p) noexcept -> CvPixelTypeAndSize
{
switch (p)
{
case libCZI::PixelType::Gray8:
return {1, CV_8U};
case libCZI::PixelType::Gray16:
return {2, CV_16U};
case libCZI::PixelType::Bgr24:
return {3, CV_8UC3};
case libCZI::PixelType::Bgra32:
return {4, CV_8UC4};
case libCZI::PixelType::Gray32:
return {4, CV_32S};
case libCZI::PixelType::Gray32Float:
return {4, CV_32F};
default:
return {};
}
}
} // namespace
namespace pixelarium::imaging
{
@@ -3,7 +3,7 @@
#include <stdexcept>
#include <string>
#include "../IPixelariumImage.hpp"
#include "IPixelariumImage.hpp"
namespace pixelarium::imaging
{
@@ -3,8 +3,8 @@
#include <stdexcept>
#include <string>
#include "../IPixelariumImage.hpp"
#include "utilities/ILog.hpp"
#include "ILog.hpp"
#include "IPixelariumImage.hpp"
namespace pixelarium::imaging
{
@@ -3,7 +3,7 @@
#include <stdexcept>
#include <string>
#include "../IPixelariumImage.hpp"
#include "IPixelariumImage.hpp"
namespace pixelarium::imaging
{
@@ -3,8 +3,8 @@
#include <stdexcept>
#include <string>
#include "../IPixelariumImage.hpp"
#include "utilities/ILog.hpp"
#include "ILog.hpp"
#include "IPixelariumImage.hpp"
namespace pixelarium::imaging
{
@@ -93,6 +93,8 @@ class IPixelariumImage
std::filesystem::path uri_;
};
/// @brief Interface template specialization of IPixelariumImage
/// using cv::Mat as the wrapped data type.
class IPixelariumImageCvMat : public IPixelariumImage<cv::Mat>
{
public:
@@ -2,8 +2,9 @@
#include <memory>
#include "ILog.hpp"
#include "IPixelariumImage.hpp"
#include "utilities/ILog.hpp"
namespace pixelarium::imaging
{
constexpr pixelarium::imaging::ImageFileType ExtensionToType(const std::string& extension)
+6 -3
View File
@@ -1,14 +1,17 @@
set(RESOURCELIBNAME pixelariumresourcelib)
set(RESOURCELIBSRC
resource.hpp
include/resource.hpp
resource.cpp)
add_library(${RESOURCELIBNAME} STATIC
${RESOURCELIBSRC})
add_library(pixelarium::lib::resources_static ALIAS ${RESOURCELIBNAME})
target_link_libraries(${RESOURCELIBNAME}
PRIVATE pixelariumimagelib)
PRIVATE pixelarium::lib::imaging_static)
target_include_directories(${RESOURCELIBNAME}
PRIVATE ${CMAKE_SOURCE_DIR}/lib)
INTERFACE
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
@@ -6,7 +6,7 @@
#include <mutex>
#include <unordered_map>
#include "imaging/IPixelariumImage.hpp"
#include "IPixelariumImage.hpp"
namespace pixelarium::resources
{
+1 -1
View File
@@ -5,7 +5,7 @@
#include <functional>
#include <mutex>
#include "imaging/IPixelariumImage.hpp"
#include "IPixelariumImage.hpp"
using Image = pixelarium::imaging::IPixelariumImageCvMat;
using namespace std;
+10 -5
View File
@@ -1,14 +1,17 @@
set(UTILSLIBNAME pixelariumutilslib)
set(UTILSLIBSRC
ILog.hpp
SpdLogger.hpp
include/ILog.hpp
include/SpdLogger.hpp
include/PixelariumLogger.hpp
include/simple_thread_pool.hpp
SpdLogger.cpp
simple_thread_pool.hpp
simple_thread_pool.cpp)
PixelariumLogger.cpp)
add_library(${UTILSLIBNAME} STATIC ${UTILSLIBSRC})
add_library(pixelarium::lib::utilities_static ALIAS ${UTILSLIBNAME})
# won't work
# target_compile_options(${UTILSLIBNAME}
# PRIVATE
@@ -16,7 +19,9 @@ add_library(${UTILSLIBNAME} STATIC ${UTILSLIBSRC})
# "$<$<CXX_COMPILER_ID:MSVC>:/utf-8>")
target_include_directories(${UTILSLIBNAME}
INTERFACE
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
PRIVATE ${spdlog_DIR}/include)
target_link_libraries(${UTILSLIBNAME}
PRIVATE spdlog::spdlog_header_only)
PUBLIC spdlog::spdlog_header_only)
+73
View File
@@ -0,0 +1,73 @@
#include "PixelariumLogger.hpp"
#include <chrono>
#include <fstream>
#include <memory>
#include <ostream>
#include <stdexcept>
using namespace pixelarium::utils::log;
struct PixelariumLogger::LogStream
{
LogStream(const std::string& sink)
{
out_stream_ = std::ofstream(sink, std::ios::app);
if (!out_stream_)
{
throw std::runtime_error("Failed to open log stream");
}
}
~LogStream()
{
if (out_stream_.is_open())
{
out_stream_.close();
}
}
LogStream& operator<<(const std::string& str)
{
this->out_stream_ << str;
return *this;
}
private:
std::ofstream out_stream_;
};
PixelariumLogger::PixelariumLogger(const std::string& name, const std::string& file_sink)
: name_(name), file_sink_(file_sink)
{
log_stream_ = std::make_unique<LogStream>(file_sink_);
}
PixelariumLogger::~PixelariumLogger() = default;
auto PixelariumLogger::Write(LogLevel lvl, const std::string& msg) const -> void
{
if (lvl < this->level_)
{
return;
}
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
std::tm tm;
#ifdef _WIN32
localtime_s(&tm, &time_t);
#else
localtime_r(&time_t, &tm);
#endif
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
auto timestamp = std::format("{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}", tm.tm_year + 1900, tm.tm_mon + 1,
tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count());
{
std::lock_guard<std::mutex> guard(mutex_);
*log_stream_ << std::format("[{}] [{}] [{}] {}\n", timestamp, name_, LogLevelToString(lvl), msg);
}
}
@@ -15,6 +15,24 @@ enum class LogLevel
kWarn = 1 << 3,
kError = 1 << 4,
};
constexpr auto LogLevelToString(LogLevel lvl) -> std::string
{
switch (lvl)
{
case LogLevel::kTrace:
return "Trace";
case LogLevel::kDebug:
return "Debug";
case LogLevel::kInfo:
return "Info";
case LogLevel::kWarn:
return "Warning";
case LogLevel::kError:
return "Error";
}
}
/// @brief Interface for logging implementations.
class ILog
{
@@ -0,0 +1,36 @@
#pragma once
#include <memory>
#include <mutex>
#include <string>
#include "ILog.hpp"
namespace pixelarium::utils::log
{
class PixelariumLogger : public ILog
{
private:
struct LogStream;
public:
explicit PixelariumLogger(const std::string& name, const std::string& file_sink);
~PixelariumLogger();
void Info(const std::string& msg) const override { this->Write(LogLevel::kInfo, msg); }
void Debug(const std::string& msg) const override { this->Write(LogLevel::kDebug, msg); }
void Warn(const std::string& msg) const override { this->Write(LogLevel::kWarn, msg); }
void Error(const std::string& msg) const override { this->Write(LogLevel::kError, msg); }
void ChangeLevel(LogLevel lvl) const override { this->level_ = lvl; }
private:
void Write(LogLevel, const std::string&) const;
private:
std::mutex mutable mutex_;
std::string name_;
std::string file_sink_;
std::unique_ptr<LogStream> log_stream_{};
LogLevel mutable level_{LogLevel::kDebug};
};
} // namespace pixelarium::utils::log
@@ -0,0 +1,128 @@
#pragma once
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
namespace pixelarium::utils
{
template <size_t N>
class simple_thread_pool
{
public:
simple_thread_pool()
{
static_assert(N > 0, "Pool must have at least one thread.");
for (size_t i{0}; i < N; ++i)
{
workers_.emplace_back(
[this]()
{
while (true)
{
std::function<void()> job;
{
std::unique_lock<std::mutex> lck(thread_mutex_);
cv_.wait(lck, [this]() -> bool { return shutdown_ || !task_queue_.empty(); });
if (shutdown_ && task_queue_.empty()) return;
job = std::move(task_queue_.front());
task_queue_.pop();
++running_tasks_;
}
job();
--running_tasks_;
}
});
}
}
simple_thread_pool(simple_thread_pool&) = delete;
simple_thread_pool(const simple_thread_pool&) = delete;
simple_thread_pool(simple_thread_pool&&) = delete;
simple_thread_pool& operator=(simple_thread_pool&) = delete;
simple_thread_pool& operator=(simple_thread_pool&&) = delete;
~simple_thread_pool()
{
{
std::unique_lock<std::mutex> lck(thread_mutex_);
shutdown_ = true;
}
cv_.notify_all();
for (auto& th : workers_)
{
th.join();
}
}
public:
template <typename Callable>
requires std::invocable<Callable>
auto enqueue(Callable&& fun) -> void
{
{
std::unique_lock<std::mutex> lck(thread_mutex_);
task_queue_.emplace(std::forward<Callable>(fun));
}
cv_.notify_one();
}
[[nodiscard]]
decltype(auto) RunningTasks() const
{
return running_tasks_.load();
}
decltype(auto) Joinable() const
{
std::unique_lock<std::mutex> lck(thread_mutex_);
return task_queue_.empty() && RunningTasks() == 0;
}
private:
std::vector<std::thread> workers_;
std::condition_variable cv_;
std::mutex mutable thread_mutex_;
std::queue<std::function<void()>> task_queue_;
bool shutdown_{false};
std::atomic_size_t running_tasks_{0};
};
class pixelarium_pool
{
public:
[[nodiscard]]
static decltype(auto) RunningTasks()
{
return pixelarium_pool::instance().RunningTasks();
}
static decltype(auto) Joinable() { return pixelarium_pool::instance().Joinable(); }
template <typename Callable>
requires std::invocable<Callable>
static auto enqueue(Callable&& fun) -> void
{
pixelarium_pool::instance().enqueue(std::forward<Callable>(fun));
}
private:
static constexpr auto kThreadCount{20};
static simple_thread_pool<kThreadCount>& instance()
{
static simple_thread_pool<kThreadCount> pixelarium_pool_instance;
return pixelarium_pool_instance;
}
};
} // namespace pixelarium::utils
-47
View File
@@ -1,47 +0,0 @@
#include "simple_thread_pool.hpp"
#include <functional>
#include <mutex>
using namespace pixelarium::utils;
simple_thread_pool::simple_thread_pool(size_t num_threads)
{
for (size_t i{0}; i < num_threads; ++i)
{
workers_.emplace_back(
[this]()
{
while (true)
{
std::function<void()> job;
{
std::unique_lock<std::mutex> lck(thread_mutex_);
cv_.wait(lck, [this]() -> bool { return shutdown_ || !task_queue_.empty(); });
if (shutdown_ && task_queue_.empty()) return;
job = std::move(task_queue_.front());
task_queue_.pop();
}
job();
}
});
}
}
simple_thread_pool::~simple_thread_pool()
{
{
std::unique_lock<std::mutex> lck(thread_mutex_);
shutdown_ = true;
}
cv_.notify_all();
for (auto& th : workers_)
{
th.join();
}
}
-56
View File
@@ -1,56 +0,0 @@
#pragma once
#include <condition_variable>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
namespace pixelarium::utils
{
class simple_thread_pool
{
public:
explicit simple_thread_pool(size_t);
simple_thread_pool(simple_thread_pool&) = delete;
simple_thread_pool(const simple_thread_pool&) = delete;
simple_thread_pool(simple_thread_pool&&) = delete;
simple_thread_pool& operator=(simple_thread_pool&) = delete;
simple_thread_pool& operator=(simple_thread_pool&&) = delete;
~simple_thread_pool();
template <typename Callable>
requires std::invocable<Callable>
static auto run_asynch(Callable&& fun) -> void
{
simple_thread_pool::Global().enqueue(std::forward<Callable>(fun));
}
public:
template <typename Callable>
requires std::invocable<Callable>
auto enqueue(Callable&& fun) -> void
{
{
std::unique_lock<std::mutex> lck(thread_mutex_);
task_queue_.emplace(std::forward<Callable>(fun));
}
cv_.notify_one();
}
private:
static auto Global() -> simple_thread_pool&
{
const auto kThreadCount{std::thread::hardware_concurrency() * 2};
static simple_thread_pool global_instance(kThreadCount == 0 ? 5 : kThreadCount);
return global_instance;
}
std::vector<std::thread> workers_;
std::condition_variable cv_;
std::mutex thread_mutex_;
std::queue<std::function<void()>> task_queue_;
bool shutdown_{false};
};
} // namespace pixelarium::utils