Skip to content

Commit 04d1168

Browse files
Copilotthewtex
andcommitted
Apply black formatting to modified files
Co-authored-by: thewtex <[email protected]>
1 parent 34f33b2 commit 04d1168

File tree

3 files changed

+76
-44
lines changed

3 files changed

+76
-44
lines changed

Wrapping/Generators/Python/Tests/CMakeLists.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,11 @@ if(ITK_WRAP_unsigned_char AND WRAP_2)
201201
COMMAND
202202
${CMAKE_CURRENT_SOURCE_DIR}/test_xarray.py
203203
DATA{${WrapITK_SOURCE_DIR}/images/cthead1.png})
204+
itk_python_add_test(
205+
NAME
206+
PythonImreadSingleFileListTest
207+
COMMAND
208+
${CMAKE_CURRENT_SOURCE_DIR}/test_imread_single_file_list.py)
204209
endif()
205210
endif()
206211

Wrapping/Generators/Python/Tests/test_imread_single_file_list.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,20 +34,20 @@ def test_imread_single_element_list():
3434
"""Test that imread works with a list containing a single file path."""
3535
# Create a temporary image file
3636
temp_dir = tempfile.mkdtemp()
37-
filename = os.path.join(temp_dir, 'test_image.png')
38-
37+
filename = os.path.join(temp_dir, "test_image.png")
38+
3939
try:
4040
# Create and save a test image
4141
arr = np.random.randint(0, 256, (10, 10), dtype=np.uint8)
4242
image = itk.image_from_array(arr)
4343
itk.imwrite(image, filename)
44-
44+
4545
# Test 1: imread with a string (baseline - should always work)
4646
img_from_string = itk.imread(filename)
4747
assert img_from_string is not None
4848
assert itk.size(img_from_string)[0] == 10
4949
assert itk.size(img_from_string)[1] == 10
50-
50+
5151
# Test 2: imread with a single-element list (the bug case)
5252
img_from_list = itk.imread([filename])
5353
assert img_from_list is not None
@@ -56,9 +56,9 @@ def test_imread_single_element_list():
5656
assert itk.size(img_from_list)[0] == 10
5757
assert itk.size(img_from_list)[1] == 10
5858
assert itk.size(img_from_list)[2] == 1
59-
59+
6060
print("✓ Test passed: imread works with single-element list")
61-
61+
6262
finally:
6363
# Cleanup
6464
if os.path.exists(filename):
@@ -71,16 +71,16 @@ def test_imread_multi_element_list():
7171
"""Test that imread still works with a list containing multiple file paths."""
7272
# Create temporary image files
7373
temp_dir = tempfile.mkdtemp()
74-
filename1 = os.path.join(temp_dir, 'test_image1.png')
75-
filename2 = os.path.join(temp_dir, 'test_image2.png')
76-
74+
filename1 = os.path.join(temp_dir, "test_image1.png")
75+
filename2 = os.path.join(temp_dir, "test_image2.png")
76+
7777
try:
7878
# Create and save test images
7979
arr = np.random.randint(0, 256, (10, 10), dtype=np.uint8)
8080
image = itk.image_from_array(arr)
8181
itk.imwrite(image, filename1)
8282
itk.imwrite(image, filename2)
83-
83+
8484
# Test: imread with a multi-element list (should work as before)
8585
img_from_list = itk.imread([filename1, filename2])
8686
assert img_from_list is not None
@@ -89,9 +89,9 @@ def test_imread_multi_element_list():
8989
assert itk.size(img_from_list)[0] == 10
9090
assert itk.size(img_from_list)[1] == 10
9191
assert itk.size(img_from_list)[2] == 2
92-
92+
9393
print("✓ Test passed: imread works with multi-element list")
94-
94+
9595
finally:
9696
# Cleanup
9797
if os.path.exists(filename1):

Wrapping/Generators/Python/itk/support/extras.py

Lines changed: 59 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -361,8 +361,13 @@ def GetArrayViewFromImage(
361361
array_view_from_image = GetArrayViewFromImage
362362

363363

364-
def _GetImageFromArray(arr: ArrayLike, function_name: str, is_vector: bool,
365-
ttype, need_contiguous:bool = True):
364+
def _GetImageFromArray(
365+
arr: ArrayLike,
366+
function_name: str,
367+
is_vector: bool,
368+
ttype,
369+
need_contiguous: bool = True,
370+
):
366371
"""Get an ITK image from a Python array."""
367372
import itk
368373

@@ -419,7 +424,6 @@ def _GetImageFromArray(arr: ArrayLike, function_name: str, is_vector: bool,
419424
return templatedFunction(arr, is_vector)
420425

421426

422-
423427
def GetImageFromArray(
424428
arr: ArrayLike, is_vector: bool = False, ttype=None
425429
) -> "itkt.ImageBase":
@@ -471,8 +475,9 @@ def GetImageViewFromArray(
471475
array, since a copy is performed and care must be taken to keep a reference
472476
to the copied array. This warning can be suppressed with need_contiguous=False
473477
"""
474-
return _GetImageFromArray(arr, "GetImageViewFromArray", is_vector, ttype,
475-
need_contiguous=need_contiguous)
478+
return _GetImageFromArray(
479+
arr, "GetImageViewFromArray", is_vector, ttype, need_contiguous=need_contiguous
480+
)
476481

477482

478483
image_view_from_array = GetImageViewFromArray
@@ -752,7 +757,7 @@ def image_from_vtk_image(vtk_image: "vtk.vtkImageData") -> "itkt.ImageBase":
752757
dims = dims[:-1] # 2D, not 3D
753758
dims.reverse()
754759
if is_vector:
755-
dims.append(number_of_components)
760+
dims.append(number_of_components)
756761
array.shape = tuple(dims)
757762
l_image = itk.image_view_from_array(array, is_vector)
758763

@@ -790,7 +795,10 @@ def dict_from_image(image: "itkt.Image") -> Dict:
790795
pixel_arr = itk.array_from_image(image)
791796
imageType = wasm_type_from_image_type(image)
792797
buffered_region = image.GetBufferedRegion()
793-
bufferedRegion = { "index": tuple(buffered_region.GetIndex()), "size": tuple(buffered_region.GetSize())}
798+
bufferedRegion = {
799+
"index": tuple(buffered_region.GetIndex()),
800+
"size": tuple(buffered_region.GetSize()),
801+
}
794802
return dict(
795803
imageType=imageType,
796804
name=image.GetObjectName(),
@@ -959,9 +967,7 @@ def dict_from_pointset(pointset: "itkt.PointSet") -> Dict:
959967
if number_of_points == 0:
960968
points_array = np.array([], np.float32)
961969
else:
962-
points_array = itk.array_from_vector_container(
963-
pointset.GetPoints()
964-
).flatten()
970+
points_array = itk.array_from_vector_container(pointset.GetPoints()).flatten()
965971

966972
point_data = pointset.GetPointData()
967973
if point_data.Size() == 0:
@@ -993,6 +999,7 @@ def dict_from_pointset(pointset: "itkt.PointSet") -> Dict:
993999
pointData=point_data_numpy,
9941000
)
9951001

1002+
9961003
def polyline_from_dict(polyline_dict: Dict) -> "itkt.PolylineParametricPath":
9971004
"""Deserialize an dictionary representing an itk.PolylineParametricPath object."""
9981005
import itk
@@ -1006,6 +1013,7 @@ def polyline_from_dict(polyline_dict: Dict) -> "itkt.PolylineParametricPath":
10061013

10071014
return polyline
10081015

1016+
10091017
def dict_from_polyline(polyline: "itkt.PolylineParametricPath") -> Dict:
10101018
"""Serialize a Python itk.PolylineParametricPath object to a pickable Python dictionary."""
10111019
import itk
@@ -1017,22 +1025,28 @@ def dict_from_polyline(polyline: "itkt.PolylineParametricPath") -> Dict:
10171025
vertexList=vertex_list_array,
10181026
)
10191027

1020-
def dict_from_transform(transform: Union["itkt.TransformBase", List["itkt.TransformBase"]]) -> Union[List[Dict], Dict]:
1028+
1029+
def dict_from_transform(
1030+
transform: Union["itkt.TransformBase", List["itkt.TransformBase"]],
1031+
) -> Union[List[Dict], Dict]:
10211032
"""Serialize a Python itk.Transform object to a pickable Python dictionary.
10221033
10231034
If the transform is a list of transforms, then a list of dictionaries is returned.
10241035
If the transform is a single, non-Composite transform, then a single dictionary is returned.
10251036
Composite transforms and nested composite transforms are flattened into a list of dictionaries.
10261037
"""
10271038
import itk
1039+
10281040
datatype_dict = {"double": itk.D, "float": itk.F}
10291041

10301042
def update_transform_dict(current_transform):
10311043
current_transform_type = current_transform.GetTransformTypeAsString()
10321044
current_transform_type_split = current_transform_type.split("_")
10331045

10341046
transform_type = dict()
1035-
transform_parameterization = current_transform_type_split[0].replace("Transform", "")
1047+
transform_parameterization = current_transform_type_split[0].replace(
1048+
"Transform", ""
1049+
)
10361050
transform_type["transformParameterization"] = transform_parameterization
10371051

10381052
transform_type["parametersValueType"] = python_to_js(
@@ -1042,7 +1056,7 @@ def update_transform_dict(current_transform):
10421056
transform_type["outputDimension"] = int(current_transform_type_split[3])
10431057

10441058
transform_dict = dict()
1045-
transform_dict['transformType'] = transform_type
1059+
transform_dict["transformType"] = transform_type
10461060
transform_dict["name"] = current_transform.GetObjectName()
10471061

10481062
transform_dict["inputSpaceName"] = current_transform.GetInputSpaceName()
@@ -1064,6 +1078,7 @@ def update_transform_dict(current_transform):
10641078

10651079
dict_array = []
10661080
multi = False
1081+
10671082
def add_transform_dict(transform):
10681083
transform_type = transform.GetTransformTypeAsString()
10691084
if "CompositeTransform" in transform_type:
@@ -1076,6 +1091,7 @@ def add_transform_dict(transform):
10761091
else:
10771092
dict_array.append(update_transform_dict(transform))
10781093
return False
1094+
10791095
if isinstance(transform, list):
10801096
multi = True
10811097
for t in transform:
@@ -1088,13 +1104,19 @@ def add_transform_dict(transform):
10881104
else:
10891105
return dict_array[0]
10901106

1091-
def transform_from_dict(transform_dict: Union[Dict, List[Dict]]) -> "itkt.TransformBase":
1107+
1108+
def transform_from_dict(
1109+
transform_dict: Union[Dict, List[Dict]],
1110+
) -> "itkt.TransformBase":
10921111
"""Deserialize a dictionary representing an itk.Transform object.
10931112
1094-
If the dictionary represents a list of transforms, then a Composite Transform is returned."""
1113+
If the dictionary represents a list of transforms, then a Composite Transform is returned.
1114+
"""
10951115
import itk
10961116

1097-
def set_parameters(transform, transform_parameters, transform_fixed_parameters, data_type):
1117+
def set_parameters(
1118+
transform, transform_parameters, transform_fixed_parameters, data_type
1119+
):
10981120
# First set fixed parameters then parameters
10991121
o1 = itk.OptimizerParameters[data_type](list(transform_fixed_parameters))
11001122
transform.SetFixedParameters(o1)
@@ -1124,7 +1146,9 @@ def special_transform_check(transform_name):
11241146
transform_type = transform_dict[i]["transformType"]
11251147
data_type = parametersValueType_dict[transform_type["parametersValueType"]]
11261148

1127-
transform_parameterization = transform_type["transformParameterization"] + 'Transform'
1149+
transform_parameterization = (
1150+
transform_type["transformParameterization"] + "Transform"
1151+
)
11281152

11291153
# No template parameter needed for transforms having 2D or 3D name
11301154
# Also for some selected transforms
@@ -1145,7 +1169,9 @@ def special_transform_check(transform_name):
11451169
transform_template = getattr(itk, transform_parameterization)
11461170
if len(transform_template.items()[0][0]) > 2:
11471171
transform = transform_template[
1148-
data_type, transform_type["inputDimension"], transform_type["outputDimension"]
1172+
data_type,
1173+
transform_type["inputDimension"],
1174+
transform_type["outputDimension"],
11491175
].New()
11501176
else:
11511177
transform = transform_template[
@@ -1160,16 +1186,20 @@ def special_transform_check(transform_name):
11601186
transform,
11611187
transform_dict[i]["parameters"],
11621188
transform_dict[i]["fixedParameters"],
1163-
data_type
1189+
data_type,
11641190
)
11651191
transforms_list.append(transform)
11661192

11671193
# If array has length more than 1 then it's a composite transform
11681194
if len(transforms_list) > 1:
11691195
# Create a Composite Transform object
11701196
# and add all the transforms in it.
1171-
data_type = parametersValueType_dict[transform_dict[0]["transformType"]["parametersValueType"]]
1172-
transform = itk.CompositeTransform[data_type, transforms_list[0]["transformType"]['inputDimension']].New()
1197+
data_type = parametersValueType_dict[
1198+
transform_dict[0]["transformType"]["parametersValueType"]
1199+
]
1200+
transform = itk.CompositeTransform[
1201+
data_type, transforms_list[0]["transformType"]["inputDimension"]
1202+
].New()
11731203
for current_transform in transforms_list:
11741204
transform.AddTransform(current_transform)
11751205
else:
@@ -1550,8 +1580,6 @@ def search(s: str, case_sensitive: bool = False) -> List[str]: # , fuzzy=True):
15501580
return res
15511581

15521582

1553-
1554-
15551583
def set_inputs(
15561584
new_itk_object,
15571585
inargs: Optional[Sequence[Any]] = None,
@@ -1667,7 +1695,6 @@ def SetInputs(self, *args, **kargs):
16671695

16681696

16691697
class templated_class:
1670-
16711698
"""This class is used to mimic the behavior of the templated C++ classes.
16721699
16731700
It is used this way:
@@ -1760,7 +1787,6 @@ def add_image_templates(self, *args) -> None:
17601787
self.add_template(name, tuple(parameters))
17611788

17621789
class __templated_class_and_parameters__:
1763-
17641790
"""Inner class used to store the pair class-template parameters ready
17651791
to instantiate.
17661792
"""
@@ -1818,7 +1844,6 @@ def __len__(self):
18181844

18191845

18201846
class pipeline:
1821-
18221847
"""A convenient class to store the reference to the filters of a pipeline
18231848
18241849
With this class, a method can create a pipeline of several filters and
@@ -2317,7 +2342,8 @@ def tuple_to_string_type(t):
23172342
python_input_type = tuple_to_string_type(input_type)
23182343
type_list = "\n".join([python_type(x[0]) for x in template_type.keys()])
23192344
eg_type = ", ".join([python_type(x) for x in list(template_type.keys())[0]])
2320-
msg: str = """{template_type} is not wrapped for input type `{input_type}`.
2345+
msg: str = (
2346+
"""{template_type} is not wrapped for input type `{input_type}`.
23212347
23222348
To limit the size of the package, only a limited number of
23232349
types are available in ITK Python. To print the supported
@@ -2346,11 +2372,12 @@ def tuple_to_string_type(t):
23462372
23472373
{type_list}
23482374
""".format(
2349-
template_type=python_template_type,
2350-
input_type=python_input_type,
2351-
type_list=type_list,
2352-
eg_type=eg_type,
2353-
extra_eg=extra_eg,
2375+
template_type=python_template_type,
2376+
input_type=python_input_type,
2377+
type_list=type_list,
2378+
eg_type=eg_type,
2379+
extra_eg=extra_eg,
2380+
)
23542381
)
23552382
TypeError.__init__(self, msg)
23562383

0 commit comments

Comments
 (0)