ANSCV tests: add ans_imshow include + headless ConsoleTest
Add ConsoleTest.cpp, a headless (no-GUI) smoke test for ANSOPENCV image ops plus an optional RTSP capture path, built as its own executable (ANSCV-ConsoleTest) so it does not collide with ANSCV-UnitTest's GUI main. Make the ans_imshow.hpp include (shipped with ANSMIND, outside the repo) configurable via the ANSMIND_INCLUDE_DIR cache variable, defaulting to C:/ProgramData/ANSCENTER/ANSMIND. Warn rather than fail configure when the header is absent so unrelated targets still build. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,380 @@
|
||||
// ANSCV Console Test
|
||||
// ------------------------------------------------------------------
|
||||
// A headless (no GUI) smoke test for ANSCENTER::ANSOPENCV image ops plus an
|
||||
// optional RTSP capture test (ANSCENTER::ANSRTSPClient). It prints a PASS/FAIL
|
||||
// line per check so results are visible in a plain console (and in CI).
|
||||
// Exit code == number of failed checks (0 == all OK).
|
||||
//
|
||||
// Usage:
|
||||
// ANSCV-ConsoleTest.exe # image ops only (no camera needed)
|
||||
// ANSCV-ConsoleTest.exe <rtsp-url> # image ops + headless RTSP capture
|
||||
// ANSCV-ConsoleTest.exe <rtsp-url> <maxFrames>
|
||||
// ANSCV-ConsoleTest.exe <rtsp-url> <maxFrames> <saveDir>
|
||||
// When <saveDir> is given:
|
||||
// <saveDir>/frames/NNNN.jpg full-res captured frames (MP4 input)
|
||||
// <saveDir>/preview_NNNN.jpg downscaled previews for quick viewing
|
||||
// <saveDir>/rtsp_clip.mp4 short clip (NVENC, via ANSCV ImagesToMP4HW)
|
||||
//
|
||||
// This is intentionally separate from ANSCV-UnitTest.cpp, whose main()
|
||||
// opens OpenCV windows (cv::imshow) for the same RTSP stream.
|
||||
#include "ANSOpenCV.h"
|
||||
#include "ANSRTSP.h"
|
||||
#include "ans_imshow.hpp"
|
||||
#include <opencv2/opencv.hpp>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstdlib>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <filesystem>
|
||||
#ifdef _WIN32
|
||||
# define NOMINMAX
|
||||
# define WIN32_LEAN_AND_MEAN
|
||||
# include <windows.h>
|
||||
#endif
|
||||
|
||||
using ANSCENTER::ANSOPENCV;
|
||||
using ANSCENTER::ANSRTSPClient;
|
||||
using ANSCENTER::DetectionObject;
|
||||
|
||||
namespace {
|
||||
|
||||
int g_pass = 0;
|
||||
int g_fail = 0;
|
||||
|
||||
// Report a single check. `detail` is appended for context (sizes, counts, ...).
|
||||
void check(const std::string& name, bool ok, const std::string& detail = "") {
|
||||
if (ok) {
|
||||
++g_pass;
|
||||
std::cout << " [PASS] " << name;
|
||||
} else {
|
||||
++g_fail;
|
||||
std::cout << " [FAIL] " << name;
|
||||
}
|
||||
if (!detail.empty()) std::cout << " (" << detail << ")";
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
std::string dims(const cv::Mat& m) {
|
||||
return std::to_string(m.cols) + "x" + std::to_string(m.rows) +
|
||||
" ch=" + std::to_string(m.channels());
|
||||
}
|
||||
|
||||
// A 640x480 BGR test image: smooth gradient plus a few filled shapes so the
|
||||
// transforms operate on something with real structure (not a flat color).
|
||||
cv::Mat MakeTestImage(int w = 640, int h = 480) {
|
||||
cv::Mat img(h, w, CV_8UC3);
|
||||
for (int y = 0; y < h; ++y) {
|
||||
for (int x = 0; x < w; ++x) {
|
||||
img.at<cv::Vec3b>(y, x) = cv::Vec3b(
|
||||
static_cast<uchar>(x * 255 / w),
|
||||
static_cast<uchar>(y * 255 / h),
|
||||
static_cast<uchar>((x + y) * 255 / (w + h)));
|
||||
}
|
||||
}
|
||||
cv::rectangle(img, cv::Rect(50, 50, 200, 150), cv::Scalar(0, 0, 255), -1);
|
||||
cv::circle(img, cv::Point(450, 300), 80, cv::Scalar(0, 255, 0), -1);
|
||||
return img;
|
||||
}
|
||||
|
||||
// Headless RTSP capture test. Connects to `url`, pulls up to `maxFrames`
|
||||
// frames (or until `timeoutMs` elapses), and reports resolution, frame count,
|
||||
// JPEG sizes, per-grab latency and approximate FPS. No GUI — every frame is
|
||||
// reported as text. Bounded so it always terminates even if the camera is
|
||||
// unreachable. Adds PASS/FAIL checks to the global tally.
|
||||
void RtspConsoleTest(const std::string& url, int maxFrames,
|
||||
const std::string& saveDir = "", int timeoutMs = 15000) {
|
||||
std::cout << "-- RTSP capture --" << std::endl;
|
||||
std::cout << "URL: " << url << std::endl;
|
||||
// Give slow/high-res streams enough wall-clock to reach maxFrames.
|
||||
timeoutMs = (std::max)(timeoutMs, maxFrames * 1000);
|
||||
std::cout << "Grabbing up to " << maxFrames << " frames (timeout "
|
||||
<< timeoutMs << " ms)..." << std::endl;
|
||||
|
||||
// When saving, full-res frames go into <saveDir>/frames (clean, zero-padded
|
||||
// names) so the MP4 encoder globs only those; previews go into <saveDir>.
|
||||
std::string framesDir;
|
||||
if (!saveDir.empty()) {
|
||||
framesDir = saveDir + "/frames";
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(framesDir, ec);
|
||||
std::cout << "Saving frames to: " << saveDir << std::endl;
|
||||
}
|
||||
|
||||
ANSOPENCV::InitCameraNetwork();
|
||||
|
||||
ANSRTSPClient* client = nullptr;
|
||||
// CreateANSRTSPHandle(handle, licenseKey, username, password, url).
|
||||
// Credentials embedded in the URL → pass empty user/pass, matching the
|
||||
// existing RSTPTestClient() usage.
|
||||
int created = CreateANSRTSPHandle(&client, "", "", "", url.c_str());
|
||||
check("CreateANSRTSPHandle", client != nullptr,
|
||||
"rc=" + std::to_string(created));
|
||||
if (client == nullptr) {
|
||||
ANSOPENCV::DeinitCameraNetwork();
|
||||
return;
|
||||
}
|
||||
|
||||
StartRTSP(&client);
|
||||
|
||||
int width = 0, height = 0;
|
||||
int64_t pts = 0;
|
||||
int frames = 0;
|
||||
long long totalJpegBytes = 0;
|
||||
long long totalGrabMs = 0;
|
||||
int firstW = 0, firstH = 0;
|
||||
int64_t firstPts = 0, lastPts = 0;
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
auto elapsedMs = [&] {
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - t0).count();
|
||||
};
|
||||
|
||||
int polls = 0;
|
||||
while (frames < maxFrames && elapsedMs() < timeoutMs) {
|
||||
++polls;
|
||||
std::string jpeg;
|
||||
const auto g0 = std::chrono::steady_clock::now();
|
||||
GetRTSPStrImage(&client, width, height, pts, jpeg);
|
||||
const auto grabMs = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - g0).count();
|
||||
|
||||
if (jpeg.empty()) {
|
||||
// No frame ready yet (connecting / between frames). Back off briefly.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (frames == 0) { firstW = width; firstH = height; firstPts = pts; }
|
||||
lastPts = pts;
|
||||
++frames;
|
||||
totalJpegBytes += static_cast<long long>(jpeg.size());
|
||||
totalGrabMs += grabMs;
|
||||
|
||||
// Optionally persist the frame so it can be viewed outside the console.
|
||||
// The grabbed bytes are already a JPEG, so the full-res file is a direct
|
||||
// dump (no re-encode). The preview is decoded + downscaled for quick view.
|
||||
if (!saveDir.empty()) {
|
||||
// Zero-pad to 4 digits (lexicographic sort == capture order) without
|
||||
// snprintf: some included headers #define snprintf -> _snprintf.
|
||||
std::string idx = std::to_string(frames);
|
||||
if (idx.size() < 4) idx.insert(0, 4 - idx.size(), '0');
|
||||
// Full-res frame -> frames/ (MP4 input). Already JPEG: direct dump.
|
||||
std::ofstream f(framesDir + "/" + idx + ".jpg", std::ios::binary);
|
||||
f.write(jpeg.data(), static_cast<std::streamsize>(jpeg.size()));
|
||||
f.close();
|
||||
// Downscaled preview -> saveDir (chat-friendly viewing).
|
||||
std::vector<uchar> buf(jpeg.begin(), jpeg.end());
|
||||
cv::Mat full = cv::imdecode(buf, cv::IMREAD_COLOR);
|
||||
if (!full.empty()) {
|
||||
const int previewW = 960;
|
||||
cv::Mat preview;
|
||||
cv::resize(full, preview,
|
||||
cv::Size(previewW, full.rows * previewW / full.cols));
|
||||
cv::imwrite(saveDir + "/preview_" + idx + ".jpg", preview);
|
||||
}
|
||||
}
|
||||
|
||||
// Report every frame for the first few, then every 10th to stay readable.
|
||||
if (frames <= 5 || frames % 10 == 0) {
|
||||
std::cout << " frame " << frames << ": " << width << "x" << height
|
||||
<< " pts=" << pts << " jpeg=" << jpeg.size() << "B"
|
||||
<< " grab=" << grabMs << "ms" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
const long long elapsed = elapsedMs();
|
||||
StopRTSP(&client);
|
||||
ReleaseANSRTSPHandle(&client);
|
||||
ANSOPENCV::DeinitCameraNetwork();
|
||||
|
||||
std::cout << " polls=" << polls << " frames=" << frames
|
||||
<< " elapsed=" << elapsed << "ms" << std::endl;
|
||||
if (frames > 0) {
|
||||
const double fps = elapsed > 0 ? frames * 1000.0 / elapsed : 0.0;
|
||||
std::cout << " resolution=" << firstW << "x" << firstH
|
||||
<< " avgJpeg=" << (totalJpegBytes / frames) << "B"
|
||||
<< " avgGrab=" << (totalGrabMs / frames) << "ms"
|
||||
<< " ~fps=" << fps
|
||||
<< " ptsDelta=" << (lastPts - firstPts) << std::endl;
|
||||
}
|
||||
|
||||
check("RTSP received >=1 frame", frames > 0,
|
||||
std::to_string(frames) + " frames in " + std::to_string(elapsed) + "ms");
|
||||
if (frames > 0) {
|
||||
check("RTSP frame has valid resolution", firstW > 0 && firstH > 0,
|
||||
std::to_string(firstW) + "x" + std::to_string(firstH));
|
||||
}
|
||||
|
||||
// Encode the captured frames into a short MP4 clip using ANSCV's own
|
||||
// hardware (NVENC) encoder, so the stream can actually be watched as video.
|
||||
// maxWidth=1280 downscales the 4K stills to a manageable file; playback fps
|
||||
// is fixed at 5 so a small burst yields a watchable clip.
|
||||
if (!saveDir.empty() && frames >= 2) {
|
||||
const std::string mp4Path = saveDir + "/rtsp_clip.mp4";
|
||||
const int playbackFps = 5;
|
||||
std::cout << " encoding MP4 (" << frames << " frames -> " << mp4Path
|
||||
<< ", maxW=1280, " << playbackFps << " fps)..." << std::endl;
|
||||
const int rc = ANSCV_ImagesToMP4HW_S(framesDir.c_str(), mp4Path.c_str(),
|
||||
1280, playbackFps);
|
||||
bool ok = rc != 0 && std::filesystem::exists(mp4Path);
|
||||
std::string detail = "rc=" + std::to_string(rc);
|
||||
if (ok) {
|
||||
const auto sz = std::filesystem::file_size(mp4Path);
|
||||
detail += ", " + std::to_string(sz) + " bytes";
|
||||
}
|
||||
check("RTSP frames encoded to MP4", ok, detail);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
std::cout << "==== ANSCV Console Test ====" << std::endl;
|
||||
|
||||
// Optional RTSP target. argv[1] = URL, argv[2] = max frames (default 60),
|
||||
// argv[3] = directory to save captured frames into (optional).
|
||||
const std::string rtspUrl = (argc > 1) ? argv[1] : "";
|
||||
const int rtspMaxFrames = (argc > 2) ? std::atoi(argv[2]) : 60;
|
||||
const std::string rtspSaveDir = (argc > 3) ? argv[3] : "";
|
||||
|
||||
ANSOPENCV cv_;
|
||||
const bool licensed = cv_.Init(""); // empty license key, matching existing tests
|
||||
std::cout << "Init(\"\") license valid: " << (licensed ? "yes" : "no") << std::endl;
|
||||
|
||||
const cv::Mat src = MakeTestImage();
|
||||
std::cout << "Source image: " << dims(src) << std::endl;
|
||||
std::cout << "-- Geometry / resize --" << std::endl;
|
||||
|
||||
{
|
||||
cv::Mat out;
|
||||
cv_.ImageResize(src, 320, 240, out);
|
||||
check("ImageResize 320x240", out.cols == 320 && out.rows == 240, dims(out));
|
||||
}
|
||||
{
|
||||
cv::Mat out;
|
||||
cv_.ImageResizeWithRatio(src, 320, out);
|
||||
check("ImageResizeWithRatio width=320", out.cols == 320 && !out.empty(), dims(out));
|
||||
}
|
||||
{
|
||||
cv::Mat out = cv_.ImageResizeV2(src, 200);
|
||||
check("ImageResizeV2 width=200", !out.empty() && out.cols == 200, dims(out));
|
||||
}
|
||||
{
|
||||
cv::Mat out = cv_.ImageCrop(src, cv::Rect(10, 20, 100, 80));
|
||||
check("ImageCrop 100x80", out.cols == 100 && out.rows == 80, dims(out));
|
||||
}
|
||||
{
|
||||
cv::Mat out = cv_.RotateImage(src, 90.0);
|
||||
check("RotateImage 90deg", !out.empty(), dims(out));
|
||||
}
|
||||
{
|
||||
cv::Mat out = cv_.FlipImage(src, 1); // horizontal
|
||||
check("FlipImage horizontal", out.size() == src.size() && !out.empty(), dims(out));
|
||||
}
|
||||
{
|
||||
// ShiftImage expands the canvas by |shiftX| x |shiftY| to keep all
|
||||
// pixels after the translation (640+30, 480+40).
|
||||
cv::Mat out = cv_.ShiftImage(src, 30, 40);
|
||||
check("ShiftImage (30,40) expands canvas",
|
||||
out.cols == src.cols + 30 && out.rows == src.rows + 40, dims(out));
|
||||
}
|
||||
|
||||
std::cout << "-- Color / enhancement --" << std::endl;
|
||||
{
|
||||
cv::Mat out = cv_.ToGray(src);
|
||||
check("ToGray -> 1 channel", out.channels() == 1 && !out.empty(), dims(out));
|
||||
}
|
||||
{
|
||||
cv::Mat out = cv_.ImageContrastEnhancement(src);
|
||||
check("ImageContrastEnhancement", !out.empty(), dims(out));
|
||||
}
|
||||
{
|
||||
cv::Mat out = cv_.ImageWhiteBalance(src);
|
||||
check("ImageWhiteBalance", !out.empty(), dims(out));
|
||||
}
|
||||
{
|
||||
cv::Mat out = cv_.ImageDarkEnhancement(src, 1.5);
|
||||
check("ImageDarkEnhancement x1.5", !out.empty(), dims(out));
|
||||
}
|
||||
|
||||
std::cout << "-- Noise augmentation --" << std::endl;
|
||||
{
|
||||
cv::Mat out = cv_.AddGaussianNoise(src, 0.0, 20.0);
|
||||
check("AddGaussianNoise", out.size() == src.size() && !out.empty(), dims(out));
|
||||
}
|
||||
{
|
||||
cv::Mat out = cv_.AddSaltAndPepperNoise(src, 0.02);
|
||||
check("AddSaltAndPepperNoise", out.size() == src.size() && !out.empty(), dims(out));
|
||||
}
|
||||
{
|
||||
cv::Mat out = cv_.AddSpeckleNoise(src, 0.1);
|
||||
check("AddSpeckleNoise", out.size() == src.size() && !out.empty(), dims(out));
|
||||
}
|
||||
|
||||
std::cout << "-- Encode --" << std::endl;
|
||||
{
|
||||
std::string bin = cv_.MatToBinaryData(src);
|
||||
check("MatToBinaryData non-empty", !bin.empty(),
|
||||
std::to_string(bin.size()) + " bytes");
|
||||
}
|
||||
{
|
||||
std::string b64 = cv_.MatToBase64(src);
|
||||
check("MatToBase64 non-empty", !b64.empty(),
|
||||
std::to_string(b64.size()) + " chars");
|
||||
}
|
||||
|
||||
std::cout << "-- Parse / serialize --" << std::endl;
|
||||
{
|
||||
// GetBoundingBoxes parses a JSON object with a "results" array, each
|
||||
// entry carrying x/y/width/height.
|
||||
const std::string boxesJson =
|
||||
R"({"results":[)"
|
||||
R"({"x":10,"y":20,"width":30,"height":40},)"
|
||||
R"({"x":100,"y":110,"width":50,"height":60}]})";
|
||||
std::vector<cv::Rect> boxes = cv_.GetBoundingBoxes(boxesJson);
|
||||
bool ok = boxes.size() == 2 &&
|
||||
boxes[0] == cv::Rect(10, 20, 30, 40) &&
|
||||
boxes[1] == cv::Rect(100, 110, 50, 60);
|
||||
check("GetBoundingBoxes parses 2 boxes", ok,
|
||||
std::to_string(boxes.size()) + " boxes");
|
||||
}
|
||||
{
|
||||
std::vector<DetectionObject> dets(2);
|
||||
dets[0].classId = 1; dets[0].className = "person";
|
||||
dets[0].confidence = 0.9f; dets[0].box = cv::Rect(10, 10, 40, 80);
|
||||
dets[1].classId = 2; dets[1].className = "car";
|
||||
dets[1].confidence = 0.8f; dets[1].box = cv::Rect(60, 60, 100, 50);
|
||||
std::string json = cv_.VectorDetectionToJsonString(dets);
|
||||
check("VectorDetectionToJsonString non-empty", !json.empty(),
|
||||
std::to_string(json.size()) + " chars");
|
||||
}
|
||||
|
||||
if (!rtspUrl.empty()) {
|
||||
RtspConsoleTest(rtspUrl, rtspMaxFrames, rtspSaveDir);
|
||||
} else {
|
||||
std::cout << "-- RTSP capture --" << std::endl;
|
||||
std::cout << " (skipped: no RTSP URL given; pass one as the first "
|
||||
"argument to run it)" << std::endl;
|
||||
}
|
||||
|
||||
std::cout << "============================" << std::endl;
|
||||
std::cout << "Result: " << g_pass << " passed, " << g_fail << " failed."
|
||||
<< std::endl;
|
||||
|
||||
// NOTE: at process exit one of the loaded DLLs throws a C++ exception
|
||||
// during DllMain(PROCESS_DETACH) (observed exit code 0xE06D7363),
|
||||
// regardless of test outcome. All test work is complete by this point, so
|
||||
// force a deterministic exit code for CI. TerminateProcess is used because
|
||||
// both return and quick_exit go through ExitProcess, which still triggers
|
||||
// the faulty DLL-detach path; TerminateProcess skips it.
|
||||
std::cout.flush();
|
||||
std::cerr.flush();
|
||||
#ifdef _WIN32
|
||||
::TerminateProcess(::GetCurrentProcess(), static_cast<UINT>(g_fail));
|
||||
#endif
|
||||
return g_fail;
|
||||
}
|
||||
Reference in New Issue
Block a user