Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
451 changes: 451 additions & 0 deletions meshroom/aliceVision/IntrinsicsEditing.py

Large diffs are not rendered by default.

Empty file.
108 changes: 108 additions & 0 deletions pyTests/intrinsicsEditing/test_intrinsicsEditing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""
Collection of unit tests for the intrinsicsEditing module.
"""

import os

import numpy as np
import pytest

from pyalicevision import camera, intrinsicsEditing, sfmData, sfmDataIO

INTRINSIC_ID = 1
WIDTH = 4000
HEIGHT = 3000
SCALE = 3000.0

DEFAULTS = {
"focalLength": 0.0,
"pixelRatio": 0.0,
"centerOffsetX": -100000.0,
"centerOffsetY": -100000.0,
"sensorWidth": 0.0,
"sensorHeight": 0.0,
"circleCenterX": -100000.0,
"circleCenterY": -100000.0,
"circleRadius": 0.0,
}


def _writeInput(path, sensorWidth, width=WIDTH, height=HEIGHT):
"""Save an SfMData with one pinhole intrinsic, used by one view (formats like USD only keep used intrinsics)."""
data = sfmData.SfMData()
intrinsic = camera.Pinhole(width, height, SCALE, SCALE, 0.0, 0.0)
intrinsic.setSensorWidth(sensorWidth)
intrinsic.setSensorHeight(24.0)
data.getIntrinsics()[INTRINSIC_ID] = intrinsic
data.getViews()[10] = sfmData.View("/tmp/img.jpg", 10, INTRINSIC_ID, 20, width, height)

Check warning on line 37 in pyTests/intrinsicsEditing/test_intrinsicsEditing.py

View check run for this annotation

codefactor.io / CodeFactor

B108

Probable insecure usage of temp file/directory.
assert sfmDataIO.save(data, path, sfmDataIO.ALL)


def _edit(inputPath, outputPath, edits):
"""Run editSfmData with the fields filled from the input, then `edits` applied to them."""
data = sfmData.SfMData()
assert sfmDataIO.load(data, inputPath, sfmDataIO.ALL)
_, values = intrinsicsEditing.readIntrinsic(data, intrinsicsEditing.AUTO)
snapshot = {name: values.get(name, DEFAULTS[name]) for name in DEFAULTS}
fields = dict(snapshot, **edits)
intrinsicsEditing.editSfmData(inputPath, outputPath, intrinsicsEditing.AUTO, "pinhole", fields, snapshot,
{}, True, DEFAULTS)


def _readScale(path):
data = sfmData.SfMData()
assert sfmDataIO.load(data, path, sfmDataIO.ALL)
intrinsic = camera.IntrinsicScaleOffset.cast(data.getIntrinsics()[INTRINSIC_ID])
return np.ravel(intrinsic.getScale()).tolist()


@pytest.mark.parametrize("sensorWidth", [0.0, -10.0])
def test_focal_length_edit_rejects_invalid_input_sensor_width(tmp_path, sensorWidth):
""" A focal length edit with an input sensor width <= 0 is rejected instead of writing an invalid scale. """
inputPath, outputPath = str(tmp_path / "in.usda"), str(tmp_path / "out.usda")
_writeInput(inputPath, sensorWidth)

with pytest.raises(ValueError, match="sensor width"):
_edit(inputPath, outputPath, {"focalLength": 50.0})
assert not os.path.exists(outputPath)


def test_focal_length_edit_with_sensor_width_edit(tmp_path):
""" Editing the sensor width along with the focal length fixes an input sensor width <= 0. """
inputPath, outputPath = str(tmp_path / "in.usda"), str(tmp_path / "out.usda")
_writeInput(inputPath, 0.0)

_edit(inputPath, outputPath, {"focalLength": 50.0, "sensorWidth": 36.0})
expected = 50.0 * WIDTH / 36.0
assert _readScale(outputPath) == pytest.approx([expected, expected])


def test_focal_length_edit_rejects_invalid_scale(tmp_path):
""" A focal length edit giving a non-finite scale (image size of 0) is rejected. """
inputPath, outputPath = str(tmp_path / "in.usda"), str(tmp_path / "out.usda")
_writeInput(inputPath, 36.0, width=0, height=0)

with pytest.raises(ValueError, match="Invalid scale"):
_edit(inputPath, outputPath, {"focalLength": 50.0})
assert not os.path.exists(outputPath)


@pytest.mark.parametrize("sensorWidth", [36.0, 0.0])
def test_pixel_ratio_edit(tmp_path, sensorWidth):
""" A pixel ratio edit is applied with or without a known sensor width (fy kept, fx = fy / pixel ratio). """
inputPath, outputPath = str(tmp_path / "in.usda"), str(tmp_path / "out.usda")
_writeInput(inputPath, sensorWidth)

_edit(inputPath, outputPath, {"pixelRatio": 2.0})
assert _readScale(outputPath) == pytest.approx([SCALE / 2.0, SCALE])


def test_pixel_ratio_edit_rejects_unknown_scale(tmp_path):
""" A pixel ratio edit is rejected if the input scale is unknown, instead of being dropped. """
# The JSON format stores the focal length in mm: with a sensor width of 0, the scale is loaded as NaN
inputPath, outputPath = str(tmp_path / "in.sfm"), str(tmp_path / "out.sfm")
_writeInput(inputPath, 0.0)

with pytest.raises(ValueError, match="pixel ratio"):
_edit(inputPath, outputPath, {"pixelRatio": 2.0})
assert not os.path.exists(outputPath)
21 changes: 21 additions & 0 deletions pyTests/sfmData/test_sfmdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

import os

import pytest

from pyalicevision import sfmData as av
from ..constants import IMAGE_PATH, VIEW_ID, INTRINSIC_ID, POSE_ID, IMAGE_WIDTH, \
IMAGE_HEIGHT, RIG_ID, SUBPOSE_ID, METADATA
Expand Down Expand Up @@ -259,6 +261,25 @@ def test_sfmdata_get_view():
assert view.getImageInfo().getImagePath() == IMAGE_PATH


def test_sfmdata_missing_key():
""" Test that getting or deleting a missing key of the Views, Poses and Intrinsics raises KeyError(key),
as for a dict. """
data = av.SfMData()
data.getViews()[VIEW_ID] = av.View()
data.getPoses()[POSE_ID] = av.CameraPose()
data.getIntrinsics()[INTRINSIC_ID] = av.Pinhole()
missing_id = 999

for mapping in (data.getViews(), data.getPoses(), data.getIntrinsics()):
with pytest.raises(KeyError) as error:
mapping[missing_id]
assert error.value.args == (missing_id,)

with pytest.raises(KeyError):
del mapping[missing_id]
assert len(mapping) == 1, "Deleting a missing key should not change the mapping"


def test_sfmdata_combine():
""" Test creating two SfMData objects before combining them into a single one. """
data1 = av.SfMData()
Expand Down
5 changes: 4 additions & 1 deletion src/aliceVision/camera/Camera.i
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ using namespace aliceVision::camera;
%}

%include <aliceVision/camera/cameraCommon.hpp>

%include <aliceVision/camera/IntrinsicBase.i>
%include <aliceVision/camera/Distortion.i>
%include <aliceVision/camera/Undistortion.i>
%include <aliceVision/camera/camera.hpp>
%include <aliceVision/camera/cameraUndistortImage.hpp>

Expand All @@ -35,7 +39,6 @@ using namespace aliceVision::camera;
%include <aliceVision/camera/Undistortion3DE.i>
%include <aliceVision/camera/UndistortionRadial.i>

%include <aliceVision/camera/IntrinsicInitMode.i>
%include <aliceVision/camera/Equidistant.i>
%include <aliceVision/camera/Equirectangular.i>
%include <aliceVision/camera/Pinhole.i>
9 changes: 9 additions & 0 deletions src/aliceVision/camera/Distortion.i
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

%include <std_shared_ptr.i>
%shared_ptr(aliceVision::camera::Distortion)
%shared_ptr(aliceVision::camera::DistortionBrown)
%shared_ptr(aliceVision::camera::DistortionFisheye)
%shared_ptr(aliceVision::camera::DistortionFisheye1)
%shared_ptr(aliceVision::camera::DistortionRadialK1)
%shared_ptr(aliceVision::camera::DistortionRadialK3)
%shared_ptr(aliceVision::camera::DistortionRadialK3PT)

%include <aliceVision/camera/Distortion.hpp>

%{
Expand Down
1 change: 0 additions & 1 deletion src/aliceVision/camera/Equidistant.i
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/.

%include <std_shared_ptr.i>
%shared_ptr(aliceVision::camera::Equidistant)

%include <aliceVision/camera/IntrinsicScaleOffsetDisto.i>
%include <aliceVision/camera/Equidistant.hpp>
Expand Down
1 change: 0 additions & 1 deletion src/aliceVision/camera/Equirectangular.i
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/.

%include <std_shared_ptr.i>
%shared_ptr(aliceVision::camera::Equirectangular)

%include <aliceVision/camera/IntrinsicScaleOffsetDisto.i>
%include <aliceVision/camera/Equirectangular.hpp>
Expand Down
10 changes: 10 additions & 0 deletions src/aliceVision/camera/IntrinsicBase.i
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,17 @@
// You can obtain one at https://mozilla.org/MPL/2.0/.

%include <std_shared_ptr.i>
// EInitMode is used by IntrinsicBase: wrap it in every module that includes this file (e.g. sfmData),
// otherwise getInitializationMode() returns an opaque pointer.
%include <aliceVision/camera/IntrinsicInitMode.i>

// The whole intrinsic hierarchy is declared here, before any intrinsic class or factory function is parsed.
%shared_ptr(aliceVision::camera::IntrinsicBase)
%shared_ptr(aliceVision::camera::IntrinsicScaleOffset)
%shared_ptr(aliceVision::camera::IntrinsicScaleOffsetDisto)
%shared_ptr(aliceVision::camera::Pinhole)
%shared_ptr(aliceVision::camera::Equidistant)
%shared_ptr(aliceVision::camera::Equirectangular)

%{
#include <aliceVision/camera/IntrinsicBase.hpp>
Expand Down
5 changes: 5 additions & 0 deletions src/aliceVision/camera/IntrinsicInitMode.i
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

// Stream operators are not usable from Python, and their __lshift__ clashes with other headers' (e.g. ExposureSetting)
// in modules that include this file through IntrinsicBase.i (e.g. sfmData).
%ignore aliceVision::camera::operator<<(std::ostream&, const EInitMode);
%ignore aliceVision::camera::operator>>(std::istream&, EInitMode&);

%include <aliceVision/camera/IntrinsicInitMode.hpp>

%{
Expand Down
1 change: 0 additions & 1 deletion src/aliceVision/camera/IntrinsicScaleOffset.i
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/.

%include <std_shared_ptr.i>
%shared_ptr(aliceVision::camera::IntrinsicScaleOffset)

%include <aliceVision/camera/IntrinsicBase.i>
%include <aliceVision/camera/IntrinsicScaleOffset.hpp>
Expand Down
3 changes: 2 additions & 1 deletion src/aliceVision/camera/IntrinsicScaleOffsetDisto.i
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
// You can obtain one at https://mozilla.org/MPL/2.0/.

%include <std_shared_ptr.i>
%shared_ptr(aliceVision::camera::IntrinsicScaleOffsetDisto)

%include <aliceVision/camera/IntrinsicScaleOffset.i>
%include <aliceVision/camera/Distortion.i>
%include <aliceVision/camera/Undistortion.i>
%include <aliceVision/camera/IntrinsicScaleOffsetDisto.hpp>

%{
Expand Down
1 change: 0 additions & 1 deletion src/aliceVision/camera/Pinhole.i
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
// You can obtain one at https://mozilla.org/MPL/2.0/.

%include <std_shared_ptr.i>
%shared_ptr(aliceVision::camera::Pinhole)


%{
Expand Down
7 changes: 7 additions & 0 deletions src/aliceVision/camera/Undistortion.i
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

%include <std_shared_ptr.i>
%shared_ptr(aliceVision::camera::Undistortion)
%shared_ptr(aliceVision::camera::UndistortionRadialK3)
%shared_ptr(aliceVision::camera::Undistortion3DEAnamorphic4)
%shared_ptr(aliceVision::camera::Undistortion3DEClassicLD)
%shared_ptr(aliceVision::camera::Undistortion3DERadial4)

%include <aliceVision/camera/Undistortion.hpp>

%{
Expand Down
94 changes: 94 additions & 0 deletions src/aliceVision/exception.i
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// This file is part of the AliceVision project.
// Copyright (c) 2026 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

// Convert the C++ exceptions thrown by the wrapped functions into Python exceptions.
// Without it, an uncaught C++ exception (e.g. when reading an invalid file) terminates the Python process.
// The standard exceptions keep their meaning (invalid_argument: ValueError, out_of_range: IndexError, ...),
// the other ones are raised as RuntimeError.
// Mapping lookups of a missing key throw aliceVision_MissingKeyError, raised as KeyError(key) like a Python dict.

%include <exception.i>

%{
#include <new>
#include <stdexcept>
#include <string>

// Thrown by the wrapped mapping lookups (__getitem__, __delitem__) for a missing key.
// Derives from std::out_of_range so that C++ code can still catch it as such.
class aliceVision_MissingKeyError : public std::out_of_range
{
public:
explicit aliceVision_MissingKeyError(unsigned long long key)
: std::out_of_range("Key not found: " + std::to_string(key)),
key(key)
{}

unsigned long long key;
};

// Set the Python error matching the C++ exception being handled.
// Must be called from a catch block: it rethrows the current exception to find its type.
// Kept out of %exception, which is inlined into every wrapper function.
static inline void aliceVision_setPythonErrorFromCurrentException()
{
try
{
throw;
}
catch (const aliceVision_MissingKeyError& e)
{
// Before std::out_of_range, its base class. The key is the error argument, as for a Python dict.
PyObject* key = PyLong_FromUnsignedLongLong(e.key);
if (key)
{
PyErr_SetObject(PyExc_KeyError, key);
Py_DECREF(key);
}
// Otherwise the conversion set a Python error (MemoryError)
}
catch (const std::invalid_argument& e)
{
SWIG_Error(SWIG_ValueError, e.what());
}
catch (const std::domain_error& e)
{
SWIG_Error(SWIG_ValueError, e.what());
}
catch (const std::out_of_range& e)
{
SWIG_Error(SWIG_IndexError, e.what());
}
catch (const std::overflow_error& e)
{
SWIG_Error(SWIG_OverflowError, e.what());
}
catch (const std::bad_alloc& e)
{
SWIG_Error(SWIG_MemoryError, e.what());
}
catch (const std::exception& e)
{
SWIG_Error(SWIG_RuntimeError, e.what());
}
catch (...)
{
SWIG_Error(SWIG_RuntimeError, "Unknown C++ exception");
}
}
%}

%exception {
try
{
$action
}
catch (...)
{
aliceVision_setPythonErrorFromCurrentException();
SWIG_fail;
}
}
2 changes: 2 additions & 0 deletions src/aliceVision/global.i
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

%include <aliceVision/exception.i>

%include <stdint.i>
%include <std_container.i>
%include <std_string.i>
Expand Down
Loading
Loading