Przeglądaj źródła

Harden image and inference PSRAM call sites

SybexXx 3 dni temu
rodzic
commit
8037b09a26

+ 14 - 3
code/components/jomjol_flowcontroll/ClassFlowCNNGeneral.cpp

@@ -1,7 +1,8 @@
 #include "ClassFlowCNNGeneral.h"
 
 #include <math.h>
-#include <iomanip> 
+#include <iomanip>
+#include <new> 
 #include <sys/types.h>
 #include <sstream>      // std::stringstream
 
@@ -597,7 +598,12 @@ bool ClassFlowCNNGeneral::getNetworkParameter() {
         return true;
     }
 
-    CTfLiteClass *tflite = new CTfLiteClass;  
+    CTfLiteClass *tflite = new (std::nothrow) CTfLiteClass;
+    if (tflite == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate CTfLiteClass object");
+        LogFile.WriteHeapInfo("CTfLiteClass object allocation");
+        return false;
+    }  
     string zwcnn = "/sdcard" + cnnmodelfile;
     zwcnn = FormatFileName(zwcnn);
     ESP_LOGD(TAG, "%s", zwcnn.c_str());
@@ -671,7 +677,12 @@ bool ClassFlowCNNGeneral::doNeuralNetwork(string time) {
 
     string logPath = CreateLogFolder(time);
 
-    CTfLiteClass *tflite = new CTfLiteClass;  
+    CTfLiteClass *tflite = new (std::nothrow) CTfLiteClass;
+    if (tflite == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate CTfLiteClass object");
+        LogFile.WriteHeapInfo("CTfLiteClass object allocation");
+        return false;
+    }  
     string zwcnn = "/sdcard" + cnnmodelfile;
     zwcnn = FormatFileName(zwcnn);
     ESP_LOGD(TAG, "%s", zwcnn.c_str());

+ 126 - 82
code/components/jomjol_image_proc/CAlignAndCutImage.cpp

@@ -4,6 +4,10 @@
 
 #include <math.h>
 #include <algorithm>
+#include <cstring>
+#include <stdint.h>
+#include <limits.h>
+#include <new>
 #include <esp_log.h>
 #include "psram.h"
 
@@ -12,6 +16,34 @@
 
 static const char* TAG = "c_align_and_cut_image";
 
+static bool getCutRectangle(int imageWidth, int imageHeight,
+                             int x, int y, int requestedWidth, int requestedHeight,
+                             int* right, int* bottom)
+{
+    if (right == NULL || bottom == NULL || imageWidth <= 0 || imageHeight <= 0 ||
+        x < 0 || y < 0 || requestedWidth <= 0 || requestedHeight <= 0 ||
+        x >= imageWidth || y >= imageHeight) return false;
+
+    const int64_t requestedRight = static_cast<int64_t>(x) + requestedWidth;
+    const int64_t requestedBottom = static_cast<int64_t>(y) + requestedHeight;
+    *right = static_cast<int>(std::min<int64_t>(requestedRight, imageWidth));
+    *bottom = static_cast<int>(std::min<int64_t>(requestedBottom, imageHeight));
+    return *right > x && *bottom > y;
+}
+
+static bool getCutBufferSize(int width, int height, int channels, size_t* size)
+{
+    if (size == NULL || width <= 0 || height <= 0 || channels <= 0) return false;
+    const size_t w = static_cast<size_t>(width);
+    const size_t h = static_cast<size_t>(height);
+    const size_t c = static_cast<size_t>(channels);
+    if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return false;
+    const size_t total = w * h * c;
+    if (total > static_cast<size_t>(INT_MAX)) return false;
+    *size = total;
+    return true;
+}
+
 CAlignAndCutImage::CAlignAndCutImage(std::string _name, CImageBasis *_org, CImageBasis *_temp) : CImageBasis(_name)
 {
     name = _name;
@@ -94,76 +126,82 @@ bool CAlignAndCutImage::Align(RefInfo *_temp1, RefInfo *_temp2)
 
 void CAlignAndCutImage::CutAndSave(std::string _template1, int x1, int y1, int dx, int dy)
 {
-    int x2, y2;
-
-    x2 = x1 + dx;
-    y2 = y1 + dy;
-    x2 = std::min(x2, width - 1);
-    y2 = std::min(y2, height - 1);
-
-    dx = x2 - x1;
-    dy = y2 - y1;
-
-    int memsize = dx * dy * channels;
-    uint8_t* odata = (unsigned char*) malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
+    if (rgb_image == NULL || channels <= 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: source image is not available");
+        return;
+    }
 
-    stbi_uc* p_target;
-    stbi_uc* p_source;
+    int x2 = 0, y2 = 0;
+    if (!getCutRectangle(width, height, x1, y1, dx, dy, &x2, &y2)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: invalid crop rectangle");
+        return;
+    }
+    const int cropWidth = x2 - x1;
+    const int cropHeight = y2 - y1;
+    size_t bufferSize = 0;
+    if (!getCutBufferSize(cropWidth, cropHeight, channels, &bufferSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: crop size overflow");
+        return;
+    }
 
-    RGBImageLock();
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: source image is locked");
+        return;
+    }
+    uint8_t* output = static_cast<uint8_t*>(malloc_psram_heap(
+        std::string(TAG) + "->odata", bufferSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (output == NULL) {
+        RGBImageRelease();
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: PSRAM allocation failed");
+        return;
+    }
 
-    for (int x = x1; x < x2; ++x)
-        for (int y = y1; y < y2; ++y)
-        {
-            p_target = odata + (channels * ((y - y1) * dx + (x - x1)));
-            p_source = rgb_image + (channels * (y * width + x));
-            for (int _channels = 0; _channels < channels; ++_channels)
-                p_target[_channels] = p_source[_channels];
-        }
+    const size_t rowBytes = static_cast<size_t>(cropWidth) * static_cast<size_t>(channels);
+    for (int row = 0; row < cropHeight; ++row) {
+        const size_t sourceOffset = (static_cast<size_t>(y1 + row) * static_cast<size_t>(width) +
+                                     static_cast<size_t>(x1)) * static_cast<size_t>(channels);
+        std::memcpy(output + static_cast<size_t>(row) * rowBytes, source + sourceOffset, rowBytes);
+    }
 
 #ifdef STBI_ONLY_JPEG
-    stbi_write_jpg(_template1.c_str(), dx, dy, channels, odata, 100);
+    stbi_write_jpg(_template1.c_str(), cropWidth, cropHeight, channels, output, 100);
 #else
-    stbi_write_bmp(_template1.c_str(), dx, dy, channels, odata);
+    stbi_write_bmp(_template1.c_str(), cropWidth, cropHeight, channels, output);
 #endif
-    
-    RGBImageRelease();
 
-    free_psram_heap(std::string(TAG) + "->odata", odata);
+    RGBImageRelease();
+    free_psram_heap(std::string(TAG) + "->odata", output);
 }
 
 void CAlignAndCutImage::CutAndSave(int x1, int y1, int dx, int dy, CImageBasis *_target)
 {
-    int x2, y2;
-
-    x2 = x1 + dx;
-    y2 = y1 + dy;
-    x2 = std::min(x2, width - 1);
-    y2 = std::min(y2, height - 1);
-
-    dx = x2 - x1;
-    dy = y2 - y1;
-
-    if ((_target->height != dy) || (_target->width != dx) || (_target->channels != channels))
-    {
+    if (_target == NULL || rgb_image == NULL || channels <= 0) return;
+
+    int x2 = 0, y2 = 0;
+    if (!getCutRectangle(width, height, x1, y1, dx, dy, &x2, &y2)) return;
+    const int cropWidth = x2 - x1;
+    const int cropHeight = y2 - y1;
+    if (_target->height != cropHeight || _target->width != cropWidth ||
+        _target->channels != channels || !_target->ImageOkay()) {
         ESP_LOGD(TAG, "CAlignAndCutImage::CutAndSave - Image size does not match!");
         return;
     }
 
-    uint8_t* odata = _target->RGBImageLock();
-    RGBImageLock();
-
-    stbi_uc* p_target;
-    stbi_uc* p_source;
+    uint8_t* output = _target->RGBImageLock();
+    if (output == NULL) return;
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        _target->RGBImageRelease();
+        return;
+    }
 
-    for (int x = x1; x < x2; ++x)
-        for (int y = y1; y < y2; ++y)
-        {
-            p_target = odata + (channels * ((y - y1) * dx + (x - x1)));
-            p_source = rgb_image + (channels * (y * width + x));
-            for (int _channels = 0; _channels < channels; ++_channels)
-                p_target[_channels] = p_source[_channels];
-        }
+    const size_t rowBytes = static_cast<size_t>(cropWidth) * static_cast<size_t>(channels);
+    for (int row = 0; row < cropHeight; ++row) {
+        const size_t sourceOffset = (static_cast<size_t>(y1 + row) * static_cast<size_t>(width) +
+                                     static_cast<size_t>(x1)) * static_cast<size_t>(channels);
+        std::memcpy(output + static_cast<size_t>(row) * rowBytes, source + sourceOffset, rowBytes);
+    }
 
     RGBImageRelease();
     _target->RGBImageRelease();
@@ -171,35 +209,41 @@ void CAlignAndCutImage::CutAndSave(int x1, int y1, int dx, int dy, CImageBasis *
 
 CImageBasis* CAlignAndCutImage::CutAndSave(int x1, int y1, int dx, int dy)
 {
-    int x2, y2;
-
-    x2 = x1 + dx;
-    y2 = y1 + dy;
-    x2 = std::min(x2, width - 1);
-    y2 = std::min(y2, height - 1);
-
-    dx = x2 - x1;
-    dy = y2 - y1;
-
-    int memsize = dx * dy * channels;
-    uint8_t* odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
-
-    stbi_uc* p_target;
-    stbi_uc* p_source;
-
-    RGBImageLock();
-
-    for (int x = x1; x < x2; ++x)
-        for (int y = y1; y < y2; ++y)
-        {
-            p_target = odata + (channels * ((y - y1) * dx + (x - x1)));
-            p_source = rgb_image + (channels * (y * width + x));
-            for (int _channels = 0; _channels < channels; ++_channels)
-                p_target[_channels] = p_source[_channels];
-        }
+    if (rgb_image == NULL || channels <= 0) return NULL;
+    int x2 = 0, y2 = 0;
+    if (!getCutRectangle(width, height, x1, y1, dx, dy, &x2, &y2)) return NULL;
+    const int cropWidth = x2 - x1;
+    const int cropHeight = y2 - y1;
+    size_t bufferSize = 0;
+    if (!getCutBufferSize(cropWidth, cropHeight, channels, &bufferSize)) return NULL;
+
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) return NULL;
+    uint8_t* output = static_cast<uint8_t*>(malloc_psram_heap(
+        std::string(TAG) + "->odata", bufferSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (output == NULL) {
+        RGBImageRelease();
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CutAndSave: PSRAM allocation failed");
+        return NULL;
+    }
 
-    CImageBasis* rs = new CImageBasis("CutAndSave", odata, channels, dx, dy, bpp);
+    const size_t rowBytes = static_cast<size_t>(cropWidth) * static_cast<size_t>(channels);
+    for (int row = 0; row < cropHeight; ++row) {
+        const size_t sourceOffset = (static_cast<size_t>(y1 + row) * static_cast<size_t>(width) +
+                                     static_cast<size_t>(x1)) * static_cast<size_t>(channels);
+        std::memcpy(output + static_cast<size_t>(row) * rowBytes, source + sourceOffset, rowBytes);
+    }
     RGBImageRelease();
-    rs->SetIndepended();
-    return rs;
+
+    CImageBasis* result = new (std::nothrow) CImageBasis("CutAndSave", output, channels, cropWidth, cropHeight, bpp);
+    if (result == NULL) {
+        free_psram_heap(std::string(TAG) + "->odata (unowned)", output);
+        return NULL;
+    }
+    if (!result->SetIndepended()) {
+        delete result;
+        free_psram_heap(std::string(TAG) + "->odata (invalid result)", output);
+        return NULL;
+    }
+    return result;
 }

+ 87 - 111
code/components/jomjol_image_proc/CFindTemplate.cpp

@@ -9,159 +9,144 @@
 #include "freertos/FreeRTOS.h"
 #include "freertos/task.h"
 #include <cstdint>
+#include <limits.h>
 
 static const char* TAG = "C FIND TEMPL";
 
+static bool getTemplateBufferSize(int width, int height, int channels, size_t* size)
+{
+    if (size == NULL || width <= 0 || height <= 0 || channels <= 0) return false;
+    const size_t w = static_cast<size_t>(width);
+    const size_t h = static_cast<size_t>(height);
+    const size_t c = static_cast<size_t>(channels);
+    if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return false;
+    const size_t total = w * h * c;
+    if (total > static_cast<size_t>(INT_MAX)) return false;
+    *size = total;
+    return true;
+}
+
 // #define DEBUG_DETAIL_ON  
 
 
 bool CFindTemplate::FindTemplate(RefInfo *_ref)
 {
-    uint8_t* rgb_template;
-
+    if (_ref == NULL || rgb_image == NULL || width <= 0 || height <= 0 || channels <= 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: source image or reference is unavailable");
+        return false;
+    }
     if (file_size(_ref->image_file.c_str()) == 0) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, _ref->image_file + " is empty!");
         return false;
     }
-   
-    rgb_template = stbi_load(_ref->image_file.c_str(), &tpl_width, &tpl_height, &tpl_bpp, channels);
 
+    uint8_t* rgb_template = stbi_load(_ref->image_file.c_str(), &tpl_width, &tpl_height, &tpl_bpp, channels);
     if (rgb_template == NULL) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to load " + _ref->image_file + "! Is it corrupted?");
         return false;
     }
 
-//    ESP_LOGD(TAG, "FindTemplate 01");
+    size_t templateBytes = 0;
+    if (!getTemplateBufferSize(tpl_width, tpl_height, channels, &templateBytes) ||
+        tpl_width > width || tpl_height > height) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: template dimensions are invalid or exceed source image");
+        stbi_image_free(rgb_template);
+        return false;
+    }
 
-    int ow, ow_start, ow_stop;
-    int oh, oh_start, oh_stop;
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: source image is locked");
+        stbi_image_free(rgb_template);
+        return false;
+    }
 
-    if (_ref->search_x == 0)
-    {
+    if (_ref->search_x == 0) {
         _ref->search_x = width;
         _ref->found_x = 0;
     }
-
-    if (_ref->search_y == 0)
-    {
+    if (_ref->search_y == 0) {
         _ref->search_y = height;
         _ref->found_y = 0;
     }
 
-
-    ow_start = _ref->target_x - _ref->search_x;
-    ow_start = std::max(ow_start, 0);
-    ow_stop = _ref->target_x + _ref->search_x;
-    if ((ow_stop + tpl_width) > width)
-        ow_stop = width - tpl_width;
-    ow = ow_stop - ow_start + 1;
-
-    oh_start = _ref->target_y - _ref->search_y;
-    oh_start = std::max(oh_start, 0);
-    oh_stop = _ref->target_y + _ref->search_y;
-    if ((oh_stop + tpl_height) > height)
-        oh_stop = height - tpl_height;
-    oh = oh_stop - oh_start + 1;
+    const int64_t leftCandidate = static_cast<int64_t>(_ref->target_x) - _ref->search_x;
+    const int64_t rightCandidate = static_cast<int64_t>(_ref->target_x) + _ref->search_x;
+    const int64_t topCandidate = static_cast<int64_t>(_ref->target_y) - _ref->search_y;
+    const int64_t bottomCandidate = static_cast<int64_t>(_ref->target_y) + _ref->search_y;
+    const int ow_start = static_cast<int>(std::max<int64_t>(0, leftCandidate));
+    const int ow_stop = static_cast<int>(std::min<int64_t>(rightCandidate, width - tpl_width));
+    const int oh_start = static_cast<int>(std::max<int64_t>(0, topCandidate));
+    const int oh_stop = static_cast<int>(std::min<int64_t>(bottomCandidate, height - tpl_height));
+
+    if (ow_stop < ow_start || oh_stop < oh_start) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "FindTemplate: search window does not intersect source image");
+        RGBImageRelease();
+        stbi_image_free(rgb_template);
+        return false;
+    }
 
     float avg = 0, SAD = 0;
     int min = 0, max = 0;
     bool isSimilar = false;
-
-//    ESP_LOGD(TAG, "FindTemplate 02");
-
-    if ((_ref->alignment_algo == 2) && (_ref->fastalg_x > -1) && (_ref->fastalg_y > -1))     // für Testzwecke immer Berechnen
-    {
-        isSimilar = CalculateSimularities(rgb_template, _ref->fastalg_x, _ref->fastalg_y, min, avg, max, SAD, _ref->fastalg_SAD, _ref->fastalg_SAD_criteria);
-/*#ifdef DEBUG_DETAIL_ON
-        std::string zw = "\t" + _ref->image_file + "\tt1_x_y:\t" + std::to_string(_ref->fastalg_x) + "\t" + std::to_string(_ref->fastalg_y);
-        zw = zw + "\tpara1_found_min_avg_max_SAD:\t" + std::to_string(min) + "\t" + std::to_string(avg) + "\t" + std::to_string(max) + "\t"+ std::to_string(SAD);
-        LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", zw);
-#endif*/
+    if ((_ref->alignment_algo == 2) && (_ref->fastalg_x > -1) && (_ref->fastalg_y > -1)) {
+        isSimilar = CalculateSimularities(rgb_template, _ref->fastalg_x, _ref->fastalg_y,
+                                          min, avg, max, SAD, _ref->fastalg_SAD,
+                                          _ref->fastalg_SAD_criteria);
     }
-
-//    ESP_LOGD(TAG, "FindTemplate 03");
-
-
-    if (isSimilar)
-    {
-#ifdef DEBUG_DETAIL_ON  
-        LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Use FastAlignment sucessfull");
+    if (isSimilar) {
+#ifdef DEBUG_DETAIL_ON
+        LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Use FastAlignment successful");
 #endif
         _ref->found_x = _ref->fastalg_x;
         _ref->found_y = _ref->fastalg_y;
-
+        RGBImageRelease();
         stbi_image_free(rgb_template);
-        
         return true;
     }
 
-//    ESP_LOGD(TAG, "FindTemplate 04");
-
-
-    // Sum of squared differences in integer arithmetic: the ESP32 FPU is single precision only,
-    // so the former double/pow() version ran in software emulation and took several seconds per reference.
-    // The result is identical: the sum is exact either way and the search order / tie-breaking is unchanged.
     uint64_t aktSAD;
     uint64_t minSAD = UINT64_MAX;
-
-    RGBImageLock();
-
-//    ESP_LOGD(TAG, "FindTemplate 05");
-    int xouter, youter, tpl_x, tpl_y, _ch;
-    int _anzchannels = channels;
-    if (_ref->alignment_algo == 0)  // 0 = "Default" (nur R-Kanal)
-        _anzchannels = 1;
-
-    // PSRAM-Zugriffe auf Core 0 verdrängen den WiFi-Stack. Spätestens alle 50 ms
-    // den Core abgeben, damit Beacons weiter verarbeitet werden (Tick = 10 ms).
+    const int anzChannels = (_ref->alignment_algo == 0) ? 1 : channels;
+    const size_t templateRowLength = static_cast<size_t>(tpl_width) * static_cast<size_t>(channels);
     int64_t nextYieldUs = esp_timer_get_time() + 50000;
-    const int tpl_row_len = tpl_width * channels;
 
-    for (xouter = ow_start; xouter <= ow_stop; xouter++)
-        for (youter = oh_start; youter <= oh_stop; ++youter)
-        {
+    for (int xouter = ow_start; xouter <= ow_stop; ++xouter) {
+        for (int youter = oh_start; youter <= oh_stop; ++youter) {
             aktSAD = 0;
-            // Walk the template row by row so that image accesses stay sequential in (PSRAM) memory
-            for (tpl_y = 0; tpl_y < tpl_height; tpl_y++)
-            {
-                const stbi_uc* p_org = rgb_image + (channels * ((youter + tpl_y) * width + xouter));
-                const stbi_uc* p_tpl = rgb_template + (tpl_y * tpl_row_len);
-                uint32_t rowSAD = 0;
-                for (tpl_x = 0; tpl_x < tpl_row_len; tpl_x += channels)
-                {
-                    for (_ch = 0; _ch < _anzchannels; ++_ch)
-                    {
-                        int dif = p_tpl[tpl_x + _ch] - p_org[tpl_x + _ch];
-                        rowSAD += dif * dif;
+            for (int tpl_y = 0; tpl_y < tpl_height; ++tpl_y) {
+                const stbi_uc* p_org = source +
+                    (static_cast<size_t>(youter + tpl_y) * static_cast<size_t>(width) +
+                     static_cast<size_t>(xouter)) * static_cast<size_t>(channels);
+                const stbi_uc* p_tpl = rgb_template + static_cast<size_t>(tpl_y) * templateRowLength;
+                uint64_t rowSAD = 0;
+                for (size_t tpl_x = 0; tpl_x < templateRowLength; tpl_x += static_cast<size_t>(channels)) {
+                    for (int ch = 0; ch < anzChannels; ++ch) {
+                        const int diff = static_cast<int>(p_tpl[tpl_x + static_cast<size_t>(ch)]) -
+                                         static_cast<int>(p_org[tpl_x + static_cast<size_t>(ch)]);
+                        rowSAD += static_cast<uint64_t>(diff * diff);
                     }
                 }
                 aktSAD += rowSAD;
-                if (aktSAD >= minSAD)   // can no longer become the new minimum
-                    break;
+                if (aktSAD >= minSAD) break;
             }
-            if (aktSAD < minSAD)
-            {
+            if (aktSAD < minSAD) {
                 minSAD = aktSAD;
                 _ref->found_x = xouter;
                 _ref->found_y = youter;
             }
-
-            if (esp_timer_get_time() >= nextYieldUs)
-            {
+            if (esp_timer_get_time() >= nextYieldUs) {
                 vTaskDelay(1);
                 nextYieldUs = esp_timer_get_time() + 50000;
             }
         }
+    }
 
-//    ESP_LOGD(TAG, "FindTemplate 06");
-
-
-    if (_ref->alignment_algo == 2)
-        CalculateSimularities(rgb_template, _ref->found_x, _ref->found_y, min, avg, max, SAD, _ref->fastalg_SAD, _ref->fastalg_SAD_criteria);
-
-
-//    ESP_LOGD(TAG, "FindTemplate 07");
-
+    if (_ref->alignment_algo == 2) {
+        CalculateSimularities(rgb_template, _ref->found_x, _ref->found_y,
+                              min, avg, max, SAD, _ref->fastalg_SAD,
+                              _ref->fastalg_SAD_criteria);
+    }
     _ref->fastalg_x = _ref->found_x;
     _ref->fastalg_y = _ref->found_y;
     _ref->fastalg_min = min;
@@ -169,23 +154,12 @@ bool CFindTemplate::FindTemplate(RefInfo *_ref)
     _ref->fastalg_max = max;
     _ref->fastalg_SAD = SAD;
 
-    
-/*#ifdef DEBUG_DETAIL_ON
-    std::string zw = "\t" + _ref->image_file + "\tt1_x_y:\t" + std::to_string(_ref->fastalg_x) + "\t" + std::to_string(_ref->fastalg_y);
-    zw = zw + "\tpara1_found_min_avg_max_SAD:\t" + std::to_string(min) + "\t" + std::to_string(avg) + "\t" + std::to_string(max) + "\t"+ std::to_string(SAD);
-    LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", zw);
-#endif*/
-
     RGBImageRelease();
     stbi_image_free(rgb_template);
-    
-//    ESP_LOGD(TAG, "FindTemplate 08");
-
     return false;
 }
 
 
-
 // Compares the template with the image at (_startx, _starty) and reports whether the match is still as
 // good as the stored one. Used by the "Fast" alignment to skip the full search.
 bool CFindTemplate::CalculateSimularities(uint8_t* _rgb_tmpl, int _startx, int _starty, int &min, float &avg, int &max, float &SAD, float _SADold, float _SADcrit)
@@ -199,10 +173,11 @@ bool CFindTemplate::CalculateSimularities(uint8_t* _rgb_tmpl, int _startx, int _
 
     int xouter, youter, _ch;
 
-    // The template has to lie completely inside the image at this position. The stored position comes
-    // from /config/align.txt and may belong to an older reference image.
-    if ((_startx < 0) || (_starty < 0) || ((_startx + tpl_width) > width) || ((_starty + tpl_height) > height))
-        return false;
+    // The template has to lie completely inside the image at this position.
+    if (_rgb_tmpl == NULL || rgb_image == NULL || width <= 0 || height <= 0 ||
+        channels <= 0 || tpl_width <= 0 || tpl_height <= 0 ||
+        _startx < 0 || _starty < 0 || tpl_width > width || tpl_height > height ||
+        _startx > width - tpl_width || _starty > height - tpl_height) return false;
 
     // Walk the template, not the search area: the former loop ran over the search area size (plus one)
     // and so read past the end of the template buffer and compared pixels that are not part of the marker.
@@ -222,6 +197,7 @@ bool CFindTemplate::CalculateSimularities(uint8_t* _rgb_tmpl, int _startx, int _
             }
         }
 
+    if (anz == 0) return false;
     avg = avgDifSum / anz;
     min = minDif;
     max = maxDif;

+ 176 - 95
code/components/jomjol_image_proc/CImageBasis.cpp

@@ -20,6 +20,28 @@ using namespace std;
 
 static const char *TAG = "C IMG BASIS";
 
+static bool getImageBufferSize(int width, int height, int channels, size_t* size)
+{
+    if (size == nullptr || width <= 0 || height <= 0 || channels <= 0) return false;
+    const size_t w = static_cast<size_t>(width);
+    const size_t h = static_cast<size_t>(height);
+    const size_t c = static_cast<size_t>(channels);
+    if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return false;
+    const size_t total = w * h * c;
+    if (total > static_cast<size_t>(INT_MAX)) return false;
+    *size = total;
+    return true;
+}
+
+static void releaseOwnedImageBuffer(const std::string& tag, const std::string& name,
+                                    uint8_t* image, int size, bool sharedLease)
+{
+    if (image == nullptr) return;
+    if (sharedLease) psram_free_shared_temp_image_memory();
+    else if (size == 0) stbi_image_free(image);
+    else free_psram_heap(tag + " (" + name + ", " + std::to_string(size) + ")", image);
+}
+
 
 
 //#define DEBUG_DETAIL_ON
@@ -60,6 +82,16 @@ uint8_t * CImageBasis::RGBImageGet()
     return rgb_image;
 }
 
+bool CImageBasis::SetIndepended()
+{
+    size_t size = 0;
+    if (rgb_image == nullptr || !getImageBufferSize(width, height, channels, &size)) return false;
+    externalImage = false;
+    memsize = static_cast<int>(size);
+    ownsSharedTempImageLease = false;
+    return true;
+}
+
 
 void writejpghelp(void *context, void *data, int size)
 {
@@ -411,27 +443,35 @@ void CImageBasis::EmptyImage()
 
 void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
 {
-    RGBImageLock();
+    if (_buffer == NULL || len <= 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadFromMemory: invalid input buffer");
+        return;
+    }
+
+    int newWidth = 0, newHeight = 0, sourceChannels = 0;
+    uint8_t* decoded = stbi_load_from_memory(_buffer, len, &newWidth, &newHeight,
+                                              &sourceChannels, STBI_rgb);
+    size_t decodedSize = 0;
+    if (decoded == NULL || !getImageBufferSize(newWidth, newHeight, STBI_rgb, &decodedSize)) {
+        if (decoded != NULL) stbi_image_free(decoded);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadFromMemory: image decode failed or returned invalid dimensions");
+        LogFile.WriteHeapInfo("LoadFromMemory");
+        return;
+    }
+
     if (rgb_image != NULL && !externalImage) {
-        if (name == "tmpImage" && memsize > 0) {
-            psram_free_shared_temp_image_memory();
-        } else if (memsize == 0) {
-            stbi_image_free(rgb_image);
-        } else {
-            free_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ", " + std::to_string(memsize) + ")", rgb_image);
-        }
+        releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis", name,
+                                rgb_image, memsize, ownsSharedTempImageLease);
     }
-    rgb_image = stbi_load_from_memory(_buffer, len, &width, &height, &channels, STBI_rgb);
+    rgb_image = decoded;
+    width = newWidth;
+    height = newHeight;
+    channels = STBI_rgb;
+    bpp = sourceChannels;
     memsize = 0;
     externalImage = false;
-    bpp = channels;
+    ownsSharedTempImageLease = false;
     ESP_LOGD(TAG, "Image loaded from memory: %d, %d, %d", width, height, channels);
-    if ((width * height * channels) == 0) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image with size 0 loaded --> reboot to be done! Check that your camera module is working and connected properly.");
-        LogFile.WriteHeapInfo("LoadFromMemory");
-        doReboot();
-    }
-    RGBImageRelease();
 }
 
 
@@ -458,46 +498,65 @@ void CImageBasis::crop_image(unsigned short cropLeft, unsigned short cropRight,
 }
 
 
-CImageBasis::CImageBasis(string _name, CImageBasis *_copyfrom) 
+CImageBasis::CImageBasis(string _name, CImageBasis *_copyfrom)
 {
     name = _name;
     islocked = false;
     externalImage = false;
-    channels = _copyfrom->channels;
+    rgb_image = NULL;
+    width = height = channels = bpp = 0;
+    memsize = 0;
+    ownsSharedTempImageLease = false;
+
+    if (_copyfrom == NULL || !_copyfrom->ImageOkay()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: source image is not available");
+        return;
+    }
+
+    size_t imageSize = 0;
+    if (!getImageBufferSize(_copyfrom->width, _copyfrom->height, _copyfrom->channels, &imageSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: invalid source dimensions");
+        return;
+    }
     width = _copyfrom->width;
     height = _copyfrom->height;
+    channels = _copyfrom->channels;
     bpp = _copyfrom->bpp;
 
-    RGBImageLock();
-
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_copyfrom - Start");
-    #endif
-
-    memsize = width * height * channels;
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CImageBasis_copyfrom - Start");
+#endif
 
+    uint8_t* source = _copyfrom->RGBImageLock();
+    if (source == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: source image is locked");
+        return;
+    }
 
     if (name == "tmpImage") {
-        rgb_image = (unsigned char*)psram_reserve_shared_tmp_image_memory();
-    }
-    else {
-        rgb_image = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ")", memsize, MALLOC_CAP_SPIRAM);
+        rgb_image = static_cast<uint8_t*>(psram_reserve_shared_tmp_image_memory());
+        ownsSharedTempImageLease = (rgb_image != NULL);
+        memsize = (rgb_image != NULL) ? static_cast<int>(imageSize) : 0;
+    } else {
+        rgb_image = static_cast<uint8_t*>(malloc_psram_heap(
+            std::string(TAG) + "->CImageBasis (" + name + ")", imageSize,
+            MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+        memsize = (rgb_image != NULL) ? static_cast<int>(imageSize) : 0;
     }
 
-    if (rgb_image == NULL)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: Can't allocate enough memory: " + std::to_string(memsize));
+    if (rgb_image == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: PSRAM allocation failed (" + std::to_string(imageSize) + " bytes)");
         LogFile.WriteHeapInfo("CImageBasis-Copyfrom");
-        RGBImageRelease();
+        _copyfrom->RGBImageRelease();
         return;
     }
 
-    memCopy(_copyfrom->rgb_image, rgb_image, memsize);
-    RGBImageRelease();
+    memCopy(source, rgb_image, static_cast<int>(imageSize));
+    _copyfrom->RGBImageRelease();
 
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_copyfrom - done");
-    #endif
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CImageBasis_copyfrom - done");
+#endif
 }
 
 
@@ -506,34 +565,39 @@ CImageBasis::CImageBasis(string _name, int _width, int _height, int _channels)
     name = _name;
     islocked = false;
     externalImage = false;
-    channels = _channels;
-    width = _width;
-    height = _height;
-    bpp = _channels;
-
-    RGBImageLock();
-
-     #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_width,height,ch - Start");
-    #endif
+    ownsSharedTempImageLease = false;
+    rgb_image = NULL;
+    width = height = channels = bpp = 0;
+    memsize = 0;
 
-    memsize = width * height * channels;
+    size_t imageSize = 0;
+    if (!getImageBufferSize(_width, _height, _channels, &imageSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-width,height,ch: invalid image dimensions");
+        return;
+    }
 
-    rgb_image = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ")", memsize, MALLOC_CAP_SPIRAM);
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CImageBasis_width,height,ch - Start");
+#endif
 
-    if (rgb_image == NULL)
-    {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-width,height,ch: Can't allocate enough memory: " + std::to_string(memsize));
+    rgb_image = static_cast<uint8_t*>(malloc_psram_heap(
+        std::string(TAG) + "->CImageBasis (" + name + ")", imageSize,
+        MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (rgb_image == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-width,height,ch: PSRAM allocation failed (" + std::to_string(imageSize) + " bytes)");
         LogFile.WriteHeapInfo("CImageBasis-width,height,ch");
-        RGBImageRelease();
         return;
     }
 
-    RGBImageRelease();
+    width = _width;
+    height = _height;
+    channels = _channels;
+    bpp = _channels;
+    memsize = static_cast<int>(imageSize);
 
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CImageBasis_width,height,ch - done");
-    #endif
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CImageBasis_width,height,ch - done");
+#endif
 }
 
 
@@ -632,15 +696,12 @@ void CImageBasis::Contrast(float _contrast)
 
 CImageBasis::~CImageBasis()
 {
-    RGBImageLock();
-    if (!externalImage) {
-        if (name == "tmpImage") {
-            if (memsize == 0) stbi_image_free(rgb_image);
-            else psram_free_shared_temp_image_memory();
-        } else if (memsize == 0) stbi_image_free(rgb_image);
-        else free_psram_heap(std::string(TAG) + "->CImageBasis (" + name + ", " + to_string(memsize) + ")", rgb_image);
+    if (!externalImage && rgb_image != NULL) {
+        releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis", name,
+                                rgb_image, memsize, ownsSharedTempImageLease);
     }
-    RGBImageRelease();
+    rgb_image = NULL;
+    ownsSharedTempImageLease = false;
 }
 
 
@@ -660,57 +721,77 @@ void CImageBasis::SaveToFile(std::string _imageout)
 
 void CImageBasis::Resize(int _new_dx, int _new_dy)
 {
-    // tmpImage lives in the shared PSRAM region and its destructor relies on that; never resize it in place
-    if ((rgb_image == NULL) || (name == "tmpImage")) {
+    if (rgb_image == NULL || name == "tmpImage") {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: not possible for image " + name);
         return;
     }
-
-    int new_memsize = _new_dx * _new_dy * channels;
-    uint8_t* odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->CImageBasis Resize (" + name + ")", new_memsize, MALLOC_CAP_SPIRAM);
-
-    if (odata == NULL) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: Can't allocate enough memory: " + std::to_string(new_memsize));
+    size_t newSize = 0;
+    if (!getImageBufferSize(_new_dx, _new_dy, channels, &newSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: invalid target dimensions");
         return;
     }
 
-    RGBImageLock();
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) return;
+    uint8_t* output = static_cast<uint8_t*>(malloc_psram_heap(
+        std::string(TAG) + "->CImageBasis Resize (" + name + ")", newSize,
+        MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (output == NULL) {
+        RGBImageRelease();
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: PSRAM allocation failed: " + std::to_string(newSize));
+        return;
+    }
 
-    stbir_resize_uint8(rgb_image, width, height, 0, odata, _new_dx, _new_dy, 0, channels);
+    const int resized = stbir_resize_uint8(source, width, height, 0,
+                                            output, _new_dx, _new_dy, 0, channels);
+    RGBImageRelease();
+    if (resized == 0) {
+        free_psram_heap(std::string(TAG) + "->CImageBasis Resize (failed)", output);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Resize: stb resize failed");
+        return;
+    }
 
-    // Release the old buffer with the allocator it came from (same rule as the destructor)
     if (!externalImage) {
-        if (memsize == 0) { // Loaded via STBI (STBI_MALLOC)
-            stbi_image_free(rgb_image);
-        }
-        else {
-            free_psram_heap(std::string(TAG) + "->CImageBasis Resize old (" + name + ")", rgb_image);
-        }
+        releaseOwnedImageBuffer(std::string(TAG) + "->CImageBasis Resize old", name,
+                                rgb_image, memsize, ownsSharedTempImageLease);
     }
-
-    rgb_image = odata;
-    memsize = new_memsize;
-    externalImage = false; // The image now owns a normal PSRAM buffer
+    rgb_image = output;
+    memsize = static_cast<int>(newSize);
+    externalImage = false;
+    ownsSharedTempImageLease = false;
     width = _new_dx;
     height = _new_dy;
-
-    RGBImageRelease();
 }
 
 
 void CImageBasis::Resize(int _new_dx, int _new_dy, CImageBasis *_target)
 {
-    if ((_target->height != _new_dy) || (_target->width != _new_dx) || (_target->channels != channels))
-    {
-        ESP_LOGE(TAG, "Resize - Target image size does not fit!");
+    if (_target == NULL || rgb_image == NULL || !_target->ImageOkay() ||
+        _target->height != _new_dy || _target->width != _new_dx ||
+        _target->channels != channels) {
+        ESP_LOGE(TAG, "Resize - Target image size does not fit or is unavailable!");
         return;
     }
 
-    RGBImageLock();
+    size_t sourceSize = 0, targetSize = 0;
+    if (!getImageBufferSize(width, height, channels, &sourceSize) ||
+        !getImageBufferSize(_new_dx, _new_dy, channels, &targetSize)) {
+        ESP_LOGE(TAG, "Resize - Invalid source or target dimensions");
+        return;
+    }
 
-    uint8_t* odata = _target->rgb_image;
-    stbir_resize_uint8(rgb_image, width, height, 0, odata, _new_dx, _new_dy, 0, channels);
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) return;
+    uint8_t* target = _target->RGBImageLock();
+    if (target == NULL) {
+        RGBImageRelease();
+        return;
+    }
 
+    const int resized = stbir_resize_uint8(source, width, height, 0,
+                                            target, _new_dx, _new_dy, 0, channels);
+    _target->RGBImageRelease();
     RGBImageRelease();
+    if (resized == 0) ESP_LOGE(TAG, "Resize - stb resize failed");
 }
 

+ 2 - 1
code/components/jomjol_image_proc/CImageBasis.h

@@ -43,6 +43,7 @@ class CImageBasis
 {
     protected:
         bool externalImage;
+        bool ownsSharedTempImageLease = false;
         std::string filename;
         std::string name; // Just used for diagnostics
         int memsize = 0;
@@ -75,7 +76,7 @@ class CImageBasis
         bool ImageOkay();
         bool CopyFromMemory(uint8_t* _source, int _size);
 
-        void SetIndepended(){externalImage = false; memsize = width * height * channels;};
+        bool SetIndepended();
 
         void CreateEmptyImage(int _width, int _height, int _channels);
         void EmptyImage();

+ 409 - 326
code/components/jomjol_image_proc/CRotateImage.cpp

@@ -1,326 +1,409 @@
-#include <string>
-#include "CRotateImage.h"
-#include "psram.h"
-
-static const char *TAG = "C ROTATE IMG";
-
-// Value written to target pixels whose source lies outside the image (the gaps left by a rotation or
-// translation). It has to be black: the reference image is rotated in the browser (edit_reference.html),
-// which exports the uncovered canvas area as black. The alignment markers are cut from that reference,
-// so a marker that reaches into the gap would otherwise be matched against the wrong colour (#4169).
-static const stbi_uc FILL_VALUE = 0;
-
-CRotateImage::CRotateImage(std::string _name, CImageBasis *_org, CImageBasis *_temp, bool _flip) : CImageBasis(_name)
-{
-    rgb_image = _org->rgb_image;
-    channels = _org->channels;
-    width = _org->width;
-    height = _org->height;
-    bpp = _org->bpp;
-    externalImage = true;   
-    ImageTMP = _temp;   
-    ImageOrg = _org; 
-    islocked = false;
-    doflip = _flip;
-}
-
-void CRotateImage::Rotate(float _angle, int _centerx, int _centery)
-{
-    if ((_angle == 0) && !doflip) {  // identity transform, the copy would leave the image unchanged
-        return;
-    }
-
-    int org_width, org_height;
-    float m[2][3];
-
-    float x_center = _centerx;
-    float y_center = _centery;
-    _angle = _angle / 180 * M_PI;
-
-    if (doflip)
-    {
-        org_width = width;
-        org_height = height;
-        height = org_width;
-        width = org_height;
-        x_center =  x_center - (org_width/2) + (org_height/2);
-        y_center =  y_center + (org_width/2) - (org_height/2);
-        if (ImageOrg)
-        {
-            ImageOrg->height = height;
-            ImageOrg->width = width;
-        }
-    }
-    else
-    {
-        org_width = width;
-        org_height = height;
-    }
-
-    m[0][0] = cos(_angle);
-    m[0][1] = sin(_angle);
-    m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
-
-    m[1][0] = -m[0][1];
-    m[1][1] = m[0][0];
-    m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
-
-    if (doflip)
-    {
-        m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
-        m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
-    }
-
-    int memsize = width * height * channels;
-    uint8_t* odata;
-    if (ImageTMP)
-    {
-        odata = ImageTMP->RGBImageLock();
-    }
-    else
-    {
-        odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
-    }
-    
-
-    int x_source, y_source;
-    stbi_uc* p_target;
-    stbi_uc* p_source;
-
-    RGBImageLock();
-
-    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
-    for (int y = 0; y < height; ++y)
-        for (int x = 0; x < width; ++x)
-        {
-            p_target = odata + (channels * (y * width + x));
-
-            x_source = int(m[0][0] * x + m[0][1] * y);
-            y_source = int(m[1][0] * x + m[1][1] * y);
-
-            x_source += int(m[0][2]);
-            y_source += int(m[1][2]);
-
-            if ((x_source >= 0) && (x_source < org_width) && (y_source >= 0) && (y_source < org_height))
-            {
-                p_source = rgb_image + (channels * (y_source * org_width + x_source));
-                for (int _channels = 0; _channels < channels; ++_channels)
-                    p_target[_channels] = p_source[_channels];
-            }
-            else
-            {
-                for (int _channels = 0; _channels < channels; ++_channels)
-                    p_target[_channels] = FILL_VALUE;
-            }
-        }
-
-    //    memcpy(rgb_image, odata, memsize);
-    memCopy(odata, rgb_image, memsize);
-
-    if (!ImageTMP)
-    {
-        free_psram_heap(std::string(TAG) + "->odata", odata);
-    }
-    if (ImageTMP)
-        ImageTMP->RGBImageRelease();
-
-    RGBImageRelease();
-}
-
-
-
-void CRotateImage::RotateAntiAliasing(float _angle, int _centerx, int _centery)
-{
-    int org_width, org_height;
-    float m[2][3];
-
-    float x_center = _centerx;
-    float y_center = _centery;
-    _angle = _angle / 180 * M_PI;
-
-    if (doflip)
-    {
-        org_width = width;
-        org_height = height;
-        height = org_width;
-        width = org_height;
-        x_center =  x_center - (org_width/2) + (org_height/2);
-        y_center =  y_center + (org_width/2) - (org_height/2);
-        if (ImageOrg)
-        {
-            ImageOrg->height = height;
-            ImageOrg->width = width;
-        }
-    }
-    else
-    {
-        org_width = width;
-        org_height = height;
-    }
-
-    m[0][0] = cos(_angle);
-    m[0][1] = sin(_angle);
-    m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
-
-    m[1][0] = -m[0][1];
-    m[1][1] = m[0][0];
-    m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
-
-    if (doflip)
-    {
-        m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
-        m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
-    }
-
-    int memsize = width * height * channels;
-    uint8_t* odata;
-    if (ImageTMP)
-    {
-        odata = ImageTMP->RGBImageLock();
-    }
-    else
-    {
-        odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
-    }
-    
-
-    int x_source_1, y_source_1, x_source_2, y_source_2;
-    float x_source, y_source;
-    float quad_ul, quad_ur, quad_ol, quad_or;
-    stbi_uc* p_target;
-    stbi_uc *p_source_ul, *p_source_ur, *p_source_ol, *p_source_or;
-
-    RGBImageLock();
-
-    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
-    for (int y = 0; y < height; ++y)
-        for (int x = 0; x < width; ++x)
-        {
-            p_target = odata + (channels * (y * width + x));
-
-            x_source = (m[0][0] * x + m[0][1] * y);
-            y_source = (m[1][0] * x + m[1][1] * y);
-
-            x_source += (m[0][2]);
-            y_source += (m[1][2]);
-
-            x_source_1 = (int)x_source;
-            x_source_2 = x_source_1 + 1;
-            y_source_1 = (int)y_source;
-            y_source_2 = y_source_1 + 1;
-
-            quad_ul = (x_source_2 - x_source) * (y_source_2 - y_source);
-            quad_ur = (1- (x_source_2 - x_source)) * (y_source_2 - y_source);
-            quad_or = (x_source_2 - x_source) * (1-(y_source_2 - y_source));
-            quad_ol = (1- (x_source_2 - x_source)) * (1-(y_source_2 - y_source));
-
-
-            if ((x_source_1 >= 0) && (x_source_2 < org_width) && (y_source_1 >= 0) && (y_source_2 < org_height))
-            {
-                p_source_ul = rgb_image + (channels * (y_source_1 * org_width + x_source_1));
-                p_source_ur = rgb_image + (channels * (y_source_1 * org_width + x_source_2));
-                p_source_or = rgb_image + (channels * (y_source_2 * org_width + x_source_1));
-                p_source_ol = rgb_image + (channels * (y_source_2 * org_width + x_source_2));
-                for (int _channels = 0; _channels < channels; ++_channels)
-                {
-                    p_target[_channels] = (int)((float)p_source_ul[_channels] * quad_ul
-                                                + (float)p_source_ur[_channels] * quad_ur
-                                                + (float)p_source_or[_channels] * quad_or
-                                                + (float)p_source_ol[_channels] * quad_ol);
-                }
-            }
-            else
-            {
-                for (int _channels = 0; _channels < channels; ++_channels)
-                    p_target[_channels] = FILL_VALUE;
-            }
-        }
-
-    //    memcpy(rgb_image, odata, memsize);
-    memCopy(odata, rgb_image, memsize);
-
-    if (!ImageTMP)
-    {
-        free_psram_heap(std::string(TAG) + "->odata", odata);
-    }
-    if (ImageTMP)
-        ImageTMP->RGBImageRelease();
-
-    RGBImageRelease();
-}
-
-
-void CRotateImage::Rotate(float _angle)
-{
-//    ESP_LOGD(TAG, "width %d, height %d", width, height);
-    Rotate(_angle, width / 2, height / 2);
-}
-
-void CRotateImage::RotateAntiAliasing(float _angle)
-{
-//    ESP_LOGD(TAG, "width %d, height %d", width, height);
-    RotateAntiAliasing(_angle, width / 2, height / 2);
-}
-
-void CRotateImage::Translate(int _dx, int _dy)
-{
-    if ((_dx == 0) && (_dy == 0)) {  // identity transform, the copy would leave the image unchanged
-        return;
-    }
-
-    int memsize = width * height * channels;
-    uint8_t* odata;
-    if (ImageTMP)
-    {
-        odata = ImageTMP->RGBImageLock();
-    }
-    else
-    {
-        odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
-    }
-
-
-
-    int x_source, y_source;
-    stbi_uc* p_target;
-    stbi_uc* p_source;
-
-    RGBImageLock();
-
-    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
-    for (int y = 0; y < height; ++y)
-        for (int x = 0; x < width; ++x)
-        {
-            p_target = odata + (channels * (y * width + x));
-
-            x_source = x - _dx;
-            y_source = y - _dy;
-
-            if ((x_source >= 0) && (x_source < width) && (y_source >= 0) && (y_source < height))
-            {
-                p_source = rgb_image + (channels * (y_source * width + x_source));
-                for (int _channels = 0; _channels < channels; ++_channels)
-                    p_target[_channels] = p_source[_channels];
-            }
-            else
-            {
-                for (int _channels = 0; _channels < channels; ++_channels)
-                    p_target[_channels] = FILL_VALUE;
-            }
-        }
-
-    //    memcpy(rgb_image, odata, memsize);
-    memCopy(odata, rgb_image, memsize);
-    if (!ImageTMP)
-    {
-        free_psram_heap(std::string(TAG) + "->odata", odata);
-    }
-
-    if (ImageTMP)
-    {
-        ImageTMP->RGBImageRelease();
-    }
-    RGBImageRelease();
-
-}
-
+#include <string>
+#include <limits.h>
+#include "CRotateImage.h"
+#include "psram.h"
+
+static const char *TAG = "C ROTATE IMG";
+
+static bool getRotateBufferSize(int width, int height, int channels, size_t* size)
+{
+    if (size == NULL || width <= 0 || height <= 0 || channels <= 0) return false;
+    const size_t w = static_cast<size_t>(width);
+    const size_t h = static_cast<size_t>(height);
+    const size_t c = static_cast<size_t>(channels);
+    if (w > SIZE_MAX / h || w * h > SIZE_MAX / c) return false;
+    const size_t total = w * h * c;
+    if (total > static_cast<size_t>(INT_MAX)) return false;
+    *size = total;
+    return true;
+}
+
+// Value written to target pixels whose source lies outside the image (the gaps left by a rotation or
+// translation). It has to be black: the reference image is rotated in the browser (edit_reference.html),
+// which exports the uncovered canvas area as black. The alignment markers are cut from that reference,
+// so a marker that reaches into the gap would otherwise be matched against the wrong colour (#4169).
+static const stbi_uc FILL_VALUE = 0;
+
+CRotateImage::CRotateImage(std::string _name, CImageBasis *_org, CImageBasis *_temp, bool _flip) : CImageBasis(_name)
+{
+    rgb_image = _org->rgb_image;
+    channels = _org->channels;
+    width = _org->width;
+    height = _org->height;
+    bpp = _org->bpp;
+    externalImage = true;   
+    ImageTMP = _temp;   
+    ImageOrg = _org; 
+    islocked = false;
+    doflip = _flip;
+}
+
+void CRotateImage::Rotate(float _angle, int _centerx, int _centery)
+{
+    if ((_angle == 0) && !doflip) {  // identity transform, the copy would leave the image unchanged
+        return;
+    }
+
+    int org_width, org_height;
+    float m[2][3];
+
+    float x_center = _centerx;
+    float y_center = _centery;
+    _angle = _angle / 180 * M_PI;
+
+    if (doflip)
+    {
+        org_width = width;
+        org_height = height;
+        height = org_width;
+        width = org_height;
+        x_center =  x_center - (org_width/2) + (org_height/2);
+        y_center =  y_center + (org_width/2) - (org_height/2);
+        if (ImageOrg)
+        {
+            ImageOrg->height = height;
+            ImageOrg->width = width;
+        }
+    }
+    else
+    {
+        org_width = width;
+        org_height = height;
+    }
+
+    m[0][0] = cos(_angle);
+    m[0][1] = sin(_angle);
+    m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
+
+    m[1][0] = -m[0][1];
+    m[1][1] = m[0][0];
+    m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
+
+    if (doflip)
+    {
+        m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
+        m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
+    }
+
+    size_t bufferSize = 0;
+    if (!getRotateBufferSize(width, height, channels, &bufferSize)) {
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: invalid dimensions or size overflow");
+        return;
+    }
+    const int memsize = static_cast<int>(bufferSize);
+    uint8_t* odata;
+    if (ImageTMP) {
+        odata = ImageTMP->RGBImageLock();
+    } else {
+        odata = static_cast<unsigned char*>(malloc_psram_heap(
+            std::string(TAG) + "->odata", bufferSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    }
+    if (odata == NULL) {
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: temporary PSRAM allocation failed");
+        return;
+    }
+    
+
+    int x_source, y_source;
+    stbi_uc* p_target;
+    stbi_uc* p_source;
+
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        if (ImageTMP) ImageTMP->RGBImageRelease();
+        else free_psram_heap(std::string(TAG) + "->odata", odata);
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: source image is unavailable");
+        return;
+    }
+
+    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
+    for (int y = 0; y < height; ++y)
+        for (int x = 0; x < width; ++x)
+        {
+            p_target = odata + (channels * (y * width + x));
+
+            x_source = int(m[0][0] * x + m[0][1] * y);
+            y_source = int(m[1][0] * x + m[1][1] * y);
+
+            x_source += int(m[0][2]);
+            y_source += int(m[1][2]);
+
+            if ((x_source >= 0) && (x_source < org_width) && (y_source >= 0) && (y_source < org_height))
+            {
+                p_source = source + (channels * (y_source * org_width + x_source));
+                for (int _channels = 0; _channels < channels; ++_channels)
+                    p_target[_channels] = p_source[_channels];
+            }
+            else
+            {
+                for (int _channels = 0; _channels < channels; ++_channels)
+                    p_target[_channels] = FILL_VALUE;
+            }
+        }
+
+    //    memcpy(rgb_image, odata, memsize);
+    memCopy(odata, source, memsize);
+
+    if (!ImageTMP)
+    {
+        free_psram_heap(std::string(TAG) + "->odata", odata);
+    }
+    if (ImageTMP)
+        ImageTMP->RGBImageRelease();
+
+    RGBImageRelease();
+}
+
+
+
+void CRotateImage::RotateAntiAliasing(float _angle, int _centerx, int _centery)
+{
+    int org_width, org_height;
+    float m[2][3];
+
+    float x_center = _centerx;
+    float y_center = _centery;
+    _angle = _angle / 180 * M_PI;
+
+    if (doflip)
+    {
+        org_width = width;
+        org_height = height;
+        height = org_width;
+        width = org_height;
+        x_center =  x_center - (org_width/2) + (org_height/2);
+        y_center =  y_center + (org_width/2) - (org_height/2);
+        if (ImageOrg)
+        {
+            ImageOrg->height = height;
+            ImageOrg->width = width;
+        }
+    }
+    else
+    {
+        org_width = width;
+        org_height = height;
+    }
+
+    m[0][0] = cos(_angle);
+    m[0][1] = sin(_angle);
+    m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
+
+    m[1][0] = -m[0][1];
+    m[1][1] = m[0][0];
+    m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
+
+    if (doflip)
+    {
+        m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
+        m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
+    }
+
+    size_t bufferSize = 0;
+    if (!getRotateBufferSize(width, height, channels, &bufferSize)) {
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: invalid dimensions or size overflow");
+        return;
+    }
+    const int memsize = static_cast<int>(bufferSize);
+    uint8_t* odata;
+    if (ImageTMP) {
+        odata = ImageTMP->RGBImageLock();
+    } else {
+        odata = static_cast<unsigned char*>(malloc_psram_heap(
+            std::string(TAG) + "->odata", bufferSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    }
+    if (odata == NULL) {
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: temporary PSRAM allocation failed");
+        return;
+    }
+    
+
+    int x_source_1, y_source_1, x_source_2, y_source_2;
+    float x_source, y_source;
+    float quad_ul, quad_ur, quad_ol, quad_or;
+    stbi_uc* p_target;
+    stbi_uc *p_source_ul, *p_source_ur, *p_source_ol, *p_source_or;
+
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        if (ImageTMP) ImageTMP->RGBImageRelease();
+        else free_psram_heap(std::string(TAG) + "->odata", odata);
+        if (doflip) {
+            width = org_width;
+            height = org_height;
+            if (ImageOrg) { ImageOrg->width = width; ImageOrg->height = height; }
+        }
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: source image is unavailable");
+        return;
+    }
+
+    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
+    for (int y = 0; y < height; ++y)
+        for (int x = 0; x < width; ++x)
+        {
+            p_target = odata + (channels * (y * width + x));
+
+            x_source = (m[0][0] * x + m[0][1] * y);
+            y_source = (m[1][0] * x + m[1][1] * y);
+
+            x_source += (m[0][2]);
+            y_source += (m[1][2]);
+
+            x_source_1 = (int)x_source;
+            x_source_2 = x_source_1 + 1;
+            y_source_1 = (int)y_source;
+            y_source_2 = y_source_1 + 1;
+
+            quad_ul = (x_source_2 - x_source) * (y_source_2 - y_source);
+            quad_ur = (1- (x_source_2 - x_source)) * (y_source_2 - y_source);
+            quad_or = (x_source_2 - x_source) * (1-(y_source_2 - y_source));
+            quad_ol = (1- (x_source_2 - x_source)) * (1-(y_source_2 - y_source));
+
+
+            if ((x_source_1 >= 0) && (x_source_2 < org_width) && (y_source_1 >= 0) && (y_source_2 < org_height))
+            {
+                p_source_ul = source + (channels * (y_source_1 * org_width + x_source_1));
+                p_source_ur = source + (channels * (y_source_1 * org_width + x_source_2));
+                p_source_or = source + (channels * (y_source_2 * org_width + x_source_1));
+                p_source_ol = source + (channels * (y_source_2 * org_width + x_source_2));
+                for (int _channels = 0; _channels < channels; ++_channels)
+                {
+                    p_target[_channels] = (int)((float)p_source_ul[_channels] * quad_ul
+                                                + (float)p_source_ur[_channels] * quad_ur
+                                                + (float)p_source_or[_channels] * quad_or
+                                                + (float)p_source_ol[_channels] * quad_ol);
+                }
+            }
+            else
+            {
+                for (int _channels = 0; _channels < channels; ++_channels)
+                    p_target[_channels] = FILL_VALUE;
+            }
+        }
+
+    //    memcpy(rgb_image, odata, memsize);
+    memCopy(odata, source, memsize);
+
+    if (!ImageTMP)
+    {
+        free_psram_heap(std::string(TAG) + "->odata", odata);
+    }
+    if (ImageTMP)
+        ImageTMP->RGBImageRelease();
+
+    RGBImageRelease();
+}
+
+
+void CRotateImage::Rotate(float _angle)
+{
+//    ESP_LOGD(TAG, "width %d, height %d", width, height);
+    Rotate(_angle, width / 2, height / 2);
+}
+
+void CRotateImage::RotateAntiAliasing(float _angle)
+{
+//    ESP_LOGD(TAG, "width %d, height %d", width, height);
+    RotateAntiAliasing(_angle, width / 2, height / 2);
+}
+
+void CRotateImage::Translate(int _dx, int _dy)
+{
+    if ((_dx == 0) && (_dy == 0)) {  // identity transform, the copy would leave the image unchanged
+        return;
+    }
+
+    size_t bufferSize = 0;
+    if (!getRotateBufferSize(width, height, channels, &bufferSize)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: invalid dimensions or size overflow");
+        return;
+    }
+    const int memsize = static_cast<int>(bufferSize);
+    uint8_t* odata;
+    if (ImageTMP) {
+        odata = ImageTMP->RGBImageLock();
+    } else {
+        odata = static_cast<unsigned char*>(malloc_psram_heap(
+            std::string(TAG) + "->odata", bufferSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    }
+    if (odata == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: temporary PSRAM allocation failed");
+        return;
+    }
+
+
+
+    int x_source, y_source;
+    stbi_uc* p_target;
+    stbi_uc* p_source;
+
+    uint8_t* source = RGBImageLock();
+    if (source == NULL) {
+        if (ImageTMP) ImageTMP->RGBImageRelease();
+        else free_psram_heap(std::string(TAG) + "->odata", odata);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Image transform: source image is unavailable");
+        return;
+    }
+
+    // y outer / x inner: write the target (and mostly read the source) sequentially in PSRAM
+    for (int y = 0; y < height; ++y)
+        for (int x = 0; x < width; ++x)
+        {
+            p_target = odata + (channels * (y * width + x));
+
+            x_source = x - _dx;
+            y_source = y - _dy;
+
+            if ((x_source >= 0) && (x_source < width) && (y_source >= 0) && (y_source < height))
+            {
+                p_source = source + (channels * (y_source * width + x_source));
+                for (int _channels = 0; _channels < channels; ++_channels)
+                    p_target[_channels] = p_source[_channels];
+            }
+            else
+            {
+                for (int _channels = 0; _channels < channels; ++_channels)
+                    p_target[_channels] = FILL_VALUE;
+            }
+        }
+
+    //    memcpy(rgb_image, odata, memsize);
+    memCopy(odata, source, memsize);
+    if (!ImageTMP)
+    {
+        free_psram_heap(std::string(TAG) + "->odata", odata);
+    }
+
+    if (ImageTMP)
+    {
+        ImageTMP->RGBImageRelease();
+    }
+    RGBImageRelease();
+
+}
+

+ 76 - 34
code/components/jomjol_tfliteclass/CTfLiteClass.cpp

@@ -6,6 +6,8 @@
 #include "../../include/defines.h"
 
 #include <sys/stat.h>
+#include <new>
+#include <limits.h>
 
 // #define DEBUG_DETAIL_ON
 
@@ -30,7 +32,9 @@ void CTfLiteClass::MakeStaticResolver()
 
 float CTfLiteClass::GetOutputValue(int nr)
 {
+    if (this->interpreter == nullptr || nr < 0) return -1000.0f;
     TfLiteTensor* output2 = this->interpreter->output(0);
+    if (output2 == nullptr || output2->dims == nullptr || output2->dims->size < 2) return -1000.0f;
 
     int numeroutput = output2->dims->data[1];
     if ((nr+1) > numeroutput)
@@ -42,7 +46,7 @@ float CTfLiteClass::GetOutputValue(int nr)
 
 int CTfLiteClass::GetClassFromImageBasis(CImageBasis *rs)
 {
-    if (!LoadInputImageBasis(rs))
+    if (interpreter == nullptr || !LoadInputImageBasis(rs))
       return -1000;
 
     Invoke();
@@ -92,10 +96,15 @@ int CTfLiteClass::GetOutClassification(int _von, int _bis)
 }
 
 
-void CTfLiteClass::GetInputDimension(bool silent = false)
+void CTfLiteClass::GetInputDimension(bool silent)
 {
+  if (this->interpreter == nullptr) return;
   TfLiteTensor* input2 = this->interpreter->input(0);
+  if (input2 == nullptr || input2->dims == nullptr) return;
 
+  im_height = 0;
+  im_width = 0;
+  im_channel = 0;
   int numdim = input2->dims->size;
   if (!silent)  ESP_LOGD(TAG, "NumDimension: %d", numdim);
 
@@ -126,7 +135,9 @@ int CTfLiteClass::ReadInputDimenstion(int _dim)
 
 int CTfLiteClass::GetAnzOutPut(bool silent)
 {
+  if (this->interpreter == nullptr) return 0;
   TfLiteTensor* output2 = this->interpreter->output(0);
+  if (output2 == nullptr || output2->dims == nullptr) return 0;
 
   int numdim = output2->dims->size;
   if (!silent) ESP_LOGD(TAG, "NumDimension: %d", numdim);
@@ -154,48 +165,76 @@ int CTfLiteClass::GetAnzOutPut(bool silent)
 
 void CTfLiteClass::Invoke()
 {
-    if (interpreter != nullptr)
-      interpreter->Invoke();
+    if (interpreter == nullptr) return;
+    if (interpreter->Invoke() != kTfLiteOk) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "TensorFlow Lite Invoke() failed");
+    }
 }
 
 
 bool CTfLiteClass::LoadInputImageBasis(CImageBasis *rs)
 {
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CTfLiteClass::LoadInputImageBasis - Start");
-    #endif
-
-    unsigned int w = rs->width;
-    unsigned int h = rs->height;
-    unsigned char red, green, blue;
-//    ESP_LOGD(TAG, "Image: %s size: %d x %d\n", _fn.c_str(), w, h);
-
-    input_i = 0;
-    float* input_data_ptr = (interpreter->input(0))->data.f;
-
-    for (int y = 0; y < h; ++y)
-        for (int x = 0; x < w; ++x)
-            {
-                red = rs->GetPixelColor(x, y, 0);
-                green = rs->GetPixelColor(x, y, 1);
-                blue = rs->GetPixelColor(x, y, 2);
-                *(input_data_ptr) = (float) red;
-                input_data_ptr++;
-                *(input_data_ptr) = (float) green;
-                input_data_ptr++;
-                *(input_data_ptr) = (float) blue;
-                input_data_ptr++;
-            }
-
-    #ifdef DEBUG_DETAIL_ON 
-        LogFile.WriteHeapInfo("CTfLiteClass::LoadInputImageBasis - done");
-    #endif
+    if (rs == nullptr || !rs->ImageOkay() || interpreter == nullptr) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadInputImageBasis: image or interpreter is unavailable");
+        return false;
+    }
+
+    TfLiteTensor* inputTensor = interpreter->input(0);
+    if (inputTensor == nullptr || inputTensor->dims == nullptr ||
+        inputTensor->data.f == nullptr || inputTensor->type != kTfLiteFloat32 ||
+        inputTensor->dims->size < 4) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadInputImageBasis: input tensor is unavailable or not float32 image data");
+        return false;
+    }
 
+    const int imageWidth = rs->width;
+    const int imageHeight = rs->height;
+    if (imageWidth <= 0 || imageHeight <= 0 || rs->channels < 3) return false;
+
+    const int expectedHeight = inputTensor->dims->data[1];
+    const int expectedWidth = inputTensor->dims->data[2];
+    const int expectedChannels = inputTensor->dims->data[3];
+    if (expectedWidth != imageWidth || expectedHeight != imageHeight || expectedChannels != 3) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadInputImageBasis: image dimensions do not match model input tensor");
+        return false;
+    }
+
+    if (static_cast<size_t>(imageWidth) > SIZE_MAX / static_cast<size_t>(imageHeight)) return false;
+    const size_t pixelCount = static_cast<size_t>(imageWidth) * static_cast<size_t>(imageHeight);
+    if (pixelCount > SIZE_MAX / (3U * sizeof(float))) return false;
+    const size_t requiredBytes = pixelCount * 3U * sizeof(float);
+    if (inputTensor->bytes < requiredBytes) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "LoadInputImageBasis: model input tensor buffer is smaller than the image");
+        return false;
+    }
+
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CTfLiteClass::LoadInputImageBasis - Start");
+#endif
+
+    uint8_t* image = rs->RGBImageLock();
+    if (image == nullptr) return false;
+    float* inputData = inputTensor->data.f;
+    size_t outputIndex = 0;
+    for (int y = 0; y < imageHeight; ++y) {
+        for (int x = 0; x < imageWidth; ++x) {
+            const size_t sourceOffset =
+                (static_cast<size_t>(y) * static_cast<size_t>(imageWidth) +
+                 static_cast<size_t>(x)) * static_cast<size_t>(rs->channels);
+            inputData[outputIndex++] = static_cast<float>(image[sourceOffset]);
+            inputData[outputIndex++] = static_cast<float>(image[sourceOffset + 1]);
+            inputData[outputIndex++] = static_cast<float>(image[sourceOffset + 2]);
+        }
+    }
+    rs->RGBImageRelease();
+
+#ifdef DEBUG_DETAIL_ON
+    LogFile.WriteHeapInfo("CTfLiteClass::LoadInputImageBasis - done");
+#endif
     return true;
 }
 
 
-
 bool CTfLiteClass::MakeAllocate()
 {
     if (!ownsSharedMemoryLease || tensor_arena == NULL || model == nullptr) {
@@ -343,6 +382,9 @@ CTfLiteClass::CTfLiteClass()
     this->input = nullptr;
     this->output = nullptr;
     this->kTensorArenaSize = TENSOR_ARENA_SIZE;
+    this->im_height = 0;
+    this->im_width = 0;
+    this->im_channel = 0;
     this->tensor_arena = static_cast<uint8_t*>(psram_get_shared_tensor_arena_memory());
     this->ownsSharedMemoryLease = (this->tensor_arena != NULL);
     if (!this->ownsSharedMemoryLease) {