Skip to content

Commit

Permalink
feat(compare-images): add vector-magnitude computation
Browse files Browse the repository at this point in the history
  • Loading branch information
thewtex committed Aug 21, 2023
1 parent f7fcf55 commit 8541e8b
Show file tree
Hide file tree
Showing 13 changed files with 192 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""itkwasm-compare-images-emscripten: Read files and images related to compare-images file format. Emscripten implementation."""

from .compare_double_images_async import compare_double_images_async
from .vector_magnitude_async import vector_magnitude_async

from ._version import __version__
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from pathlib import Path
import os
from typing import Dict, Tuple, Optional, List, Any
from typing import Dict, Tuple, Optional, List

from .js_package import js_package

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Generated file. To retain edits, remove this comment.

# Generated file. Do not edit.

from pathlib import Path
import os
from typing import Dict, Tuple, Optional, List, Any

from .js_package import js_package

from itkwasm.pyodide import (
to_js,
to_py,
js_resources
)
from itkwasm import (
InterfaceTypes,
Image,
)

async def vector_magnitude_async(
vector_image: Image,
) -> Image:
"""Generate a scalar magnitude image based on the input vector's norm.
:param vector_image: Input vector image
:type vector_image: Image
:return: Output magnitude image
:rtype: Image
"""
js_module = await js_package.js_module
web_worker = js_resources.web_worker

kwargs = {}

outputs = await js_module.vectorMagnitude(web_worker, to_js(vector_image), **kwargs)

output_web_worker = None
output_list = []
outputs_object_map = outputs.as_object_map()
for output_name in outputs.object_keys():
if output_name == 'webWorker':
output_web_worker = outputs_object_map[output_name]
else:
output_list.append(to_py(outputs_object_map[output_name]))

js_resources.web_worker = output_web_worker

if len(output_list) == 1:
return output_list[0]
return tuple(output_list)
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""itkwasm-compare-images-wasi: Read files and images related to compare-images file format. WASI implementation."""

from .compare_double_images import compare_double_images
from .compare_images import compare_images
from .compare_double_images import compare_double_images
from .vector_magnitude import vector_magnitude

from ._version import __version__
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ def compare_double_images(
if len(baseline_images) < 1:
raise ValueError('"baseline-images" kwarg must have a length > 1')
if len(baseline_images) > 0:

args.append('--baseline-images')
for value in baseline_images:
input_count_string = str(len(pipeline_inputs))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import Dict, Tuple, Optional, List, Any
from .compare_double_images import compare_double_images
from .vector_magnitude import vector_magnitude

from itkwasm import (
Image,
Expand All @@ -21,6 +22,9 @@ def _to_scalar_double(image: Image) -> Image:
pixel_type = PixelTypes.VariableLengthVector
scalar_double = cast_image(image, pixel_type=pixel_type)

if scalar_double.imageType.pixelType == PixelTypes.VariableLengthVector:
scalar_double = vector_magnitude(scalar_double)

return scalar_double

def compare_images(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Generated file. To retain edits, remove this comment.

# Generated file. Do not edit.

from pathlib import Path, PurePosixPath
import os
from typing import Dict, Tuple, Optional, List, Any

from importlib_resources import files as file_resources

_pipeline = None

from itkwasm import (
InterfaceTypes,
PipelineOutput,
PipelineInput,
Pipeline,
Image,
)

def vector_magnitude(
vector_image: Image,
) -> Image:
"""Generate a scalar magnitude image based on the input vector's norm.
:param vector_image: Input vector image
:type vector_image: Image
:return: Output magnitude image
:rtype: Image
"""
global _pipeline
if _pipeline is None:
_pipeline = Pipeline(file_resources('itkwasm_compare_images_wasi').joinpath(Path('wasm_modules') / Path('vector-magnitude.wasi.wasm')))

pipeline_outputs: List[PipelineOutput] = [
PipelineOutput(InterfaceTypes.Image),
]

pipeline_inputs: List[PipelineInput] = [
PipelineInput(InterfaceTypes.Image, vector_image),
]

args: List[str] = ['--memory-io',]
# Inputs
args.append('0')
# Outputs
args.append('0')
# Options

outputs = _pipeline.run(args, pipeline_outputs, pipeline_inputs)

result = outputs[0].data
return result

Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ def test_compare_double_images():
baseline_dict = itk.dict_from_image(baseline_image)
baseline_image = Image(**baseline_dict)

print(test_image)
metrics, difference_image, difference_image_rendering = compare_images(test_image, baseline_images=[baseline_image])

assert metrics['almostEqual'] == False
Expand Down Expand Up @@ -45,7 +44,6 @@ def test_compare_uint8_images():
baseline_dict = itk.dict_from_image(baseline_image)
baseline_image = Image(**baseline_dict)

print(test_image)
metrics, difference_image, difference_image_rendering = compare_images(test_image, baseline_images=[baseline_image])

assert metrics['almostEqual'] == False
Expand All @@ -57,3 +55,30 @@ def test_compare_uint8_images():

assert difference_image.imageType.componentType == 'float64'
assert difference_image_rendering.imageType.componentType == 'uint8'

def test_compare_rgb_images():
from itkwasm_compare_images_wasi import compare_images

test_image_file = 'apple.jpg'
test_image_path = Path('..', '..', 'test', 'data', 'input', test_image_file)
test_image = itk.imread(test_image_path)
test_dict = itk.dict_from_image(test_image)
test_image = Image(**test_dict)

baseline_image_file = 'orange.jpg'
baseline_image_path = Path('..', '..', 'test', 'data', 'input', baseline_image_file)
baseline_image = itk.imread(baseline_image_path)
baseline_dict = itk.dict_from_image(baseline_image)
baseline_image = Image(**baseline_dict)

metrics, difference_image, difference_image_rendering = compare_images(test_image, baseline_images=[baseline_image])

assert metrics['almostEqual'] == False
assert metrics['numberOfPixelsWithDifferences'] == 26477
assert metrics['minimumDifference'] == 0.002273026683894841
assert metrics['maximumDifference'] == 312.2511648746159
assert metrics['totalDifference'] == 3121656.100202402
assert metrics['meanDifference'] == 117.90067228924735

assert difference_image.imageType.componentType == 'float64'
assert difference_image_rendering.imageType.componentType == 'uint8'
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated file. Do not edit.

import os
from typing import Dict, Tuple, Optional, List, Any

from itkwasm import (
environment_dispatch,
Image,
)

def vector_magnitude(
vector_image: Image,
) -> Image:
"""Generate a scalar magnitude image based on the input vector's norm.
:param vector_image: Input vector image
:type vector_image: Image
:return: Output magnitude image
:rtype: Image
"""
func = environment_dispatch("itkwasm_compare_images", "vector_magnitude")
output = func(vector_image)
return output
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated file. Do not edit.

import os
from typing import Dict, Tuple, Optional, List, Any

from itkwasm import (
environment_dispatch,
Image,
)

async def vector_magnitude_async(
vector_image: Image,
) -> Image:
"""Generate a scalar magnitude image based on the input vector's norm.
:param vector_image: Input vector image
:type vector_image: Image
:return: Output magnitude image
:rtype: Image
"""
func = environment_dispatch("itkwasm_compare_images", "vector_magnitude_async")
output = await func(vector_image)
return output
4 changes: 2 additions & 2 deletions src/bindgen/python/package-dunder-init.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import fs from 'fs-extra'
import path from 'path'

import snakeCase from "../snake-case.js"

import wasmBinaryInterfaceJson from "../wasm-binary-interface-json.js"
import writeIfOverrideNotPresent from '../write-if-override-not-present.js'

function packageDunderInit(outputDir, buildDir, wasmBinaries, packageName, packageDescription, packageDir, pypackage, async, sync) {
const functionNames = []
Expand All @@ -26,7 +26,7 @@ ${functionImports}
from ._version import __version__
`
const dunderInitPath = path.join(packageDir, pypackage, '__init__.py')
fs.writeFileSync(dunderInitPath, dunderInit)
writeIfOverrideNotPresent(dunderInitPath, dunderInit, "#")
}

export default packageDunderInit

0 comments on commit 8541e8b

Please sign in to comment.