diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..411b009 --- /dev/null +++ b/.clang-format @@ -0,0 +1,151 @@ +## This config file is only relevant for clang-format version 8.0.0 +## +## Examples of each format style can be found on the in the clang-format documentation +## See: https://clang.llvm.org/docs/ClangFormatStyleOptions.html for details of each option +## +## The clang-format binaries can be downloaded as part of the clang binary distributions +## from https://releases.llvm.org/download.html +## +## Use the script Utilities/Maintenance/clang-format.bash to faciliate +## maintaining a consistent code style. +## +## EXAMPLE apply code style enforcement before commit: +# Utilities/Maintenance/clang-format.bash --clang ${PATH_TO_CLANG_FORMAT_8.0.0} --modified +## EXAMPLE apply code style enforcement after commit: +# Utilities/Maintenance/clang-format.bash --clang ${PATH_TO_CLANG_FORMAT_8.0.0} --last +--- +# This configuration requires clang-format version 8.0.0 exactly. +BasedOnStyle: Mozilla +Language: Cpp +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: true +AlignEscapedNewlines: Right +AlignOperands: true +AlignTrailingComments: true +# clang 9.0 AllowAllArgumentsOnNextLine: true +# clang 9.0 AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Inline +# clang 9.0 AllowShortLambdasOnASingleLine: All +# clang 9.0 features AllowShortIfStatementsOnASingleLine: Never +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: All +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: false +BinPackParameters: false +BreakBeforeBraces: Custom +BraceWrapping: + # clang 9.0 feature AfterCaseLabel: false + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: true + BeforeElse: true +## This is the big change from historical ITK formatting! +# Historically ITK used a style similar to https://en.wikipedia.org/wiki/Indentation_style#Whitesmiths_style +# with indented braces, and not indented code. This style is very difficult to automatically +# maintain with code beautification tools. Not indenting braces is more common among +# formatting tools. + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakBeforeBinaryOperators: None +#clang 6.0 BreakBeforeInheritanceComma: true +BreakInheritanceList: BeforeComma +BreakBeforeTernaryOperators: true +#clang 6.0 BreakConstructorInitializersBeforeComma: true +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +## The following line allows larger lines in non-documentation code +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 2 +ContinuationIndentWidth: 2 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + - Regex: '.*' + Priority: 1 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: true +IndentPPDirectives: AfterHash +IndentWidth: 2 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 2 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: false +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +## The following line allows larger lines in non-documentation code +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Middle +ReflowComments: true +# We may want to sort the includes as a separate pass +SortIncludes: false +# We may want to revisit this later +SortUsingDeclarations: false +SpaceAfterCStyleCast: false +# SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 2 +UseTab: Never +... diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..c598f42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,14 @@ +# Custom attribute to mark sources as using our C++/C code style. +[attr]our-c-style whitespace=tab-in-indent,no-lf-at-eof hooks.style=KWStyle,clangformat + +*.c our-c-style +*.h our-c-style +*.cxx our-c-style +*.hxx our-c-style +*.txx our-c-style +*.txt whitespace=tab-in-indent,no-lf-at-eof +*.cmake whitespace=tab-in-indent,no-lf-at-eof + +# ExternalData content links must have LF newlines +*.md5 crlf=input +*.sha512 crlf=input diff --git a/.github/workflows/build-test-package.yml b/.github/workflows/build-test-package.yml new file mode 100644 index 0000000..19b97f5 --- /dev/null +++ b/.github/workflows/build-test-package.yml @@ -0,0 +1,15 @@ + +name: Build, test, package + +on: [push,pull_request] + +jobs: + cxx-build-workflow: + uses: InsightSoftwareConsortium/ITKRemoteModuleBuildTestPackageAction/.github/workflows/build-test-cxx.yml@v5.4.0 + + python-build-workflow: + uses: InsightSoftwareConsortium/ITKRemoteModuleBuildTestPackageAction/.github/workflows/build-test-package-python.yml@v5.4.0 + with: + test-notebooks: false + secrets: + pypi_password: ${{ secrets.pypi_password }} diff --git a/.github/workflows/clang-format-linter.yml b/.github/workflows/clang-format-linter.yml new file mode 100644 index 0000000..69166d9 --- /dev/null +++ b/.github/workflows/clang-format-linter.yml @@ -0,0 +1,13 @@ +name: clang-format linter + +on: [push,pull_request] + +jobs: + lint: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + with: + fetch-depth: 1 + - uses: InsightSoftwareConsortium/ITKClangFormatLinterAction@master diff --git a/CMakeLists.txt b/CMakeLists.txt index e8ac7c2..367910c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,3 +1,12 @@ +cmake_minimum_required(VERSION 3.10.2) project(IOFDF) set(IOFDF_LIBRARIES IOFDF) -itk_module_impl() + +if(NOT ITK_SOURCE_DIR) + find_package(ITK REQUIRED) + list(APPEND CMAKE_MODULE_PATH ${ITK_CMAKE_DIR}) + include(ITKModuleExternal) +else() + itk_module_impl() +endif() + diff --git a/CTestConfig.cmake b/CTestConfig.cmake new file mode 100644 index 0000000..efccad4 --- /dev/null +++ b/CTestConfig.cmake @@ -0,0 +1,7 @@ +set(CTEST_PROJECT_NAME "ITK") +set(CTEST_NIGHTLY_START_TIME "1:00:00 UTC") + +set(CTEST_DROP_METHOD "https") +set(CTEST_DROP_SITE "open.cdash.org") +set(CTEST_DROP_LOCATION "/submit.php?project=Insight") +set(CTEST_DROP_SITE_CDASH TRUE) diff --git a/ITKKWStyleOverwrite.txt b/ITKKWStyleOverwrite.txt deleted file mode 100644 index 3334495..0000000 --- a/ITKKWStyleOverwrite.txt +++ /dev/null @@ -1,3 +0,0 @@ -test/.*\.cxx Namespace Disable -/.*\.cxx Header Disable -/.*\.h Header Disable diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..62589ed --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md deleted file mode 100644 index dd85738..0000000 --- a/README.md +++ /dev/null @@ -1,5 +0,0 @@ -This is an ITK remote module that can be requested during an ITK build by setting Module_FDFImageIO to ON when configuring ITK. - -Initial work was done by Glenn Pierce (glennpierce@gmail.com) -Code brought up to current ITK standards by Nicholas Tustison (mtustison@gmail.com) -Converted to an ITK Remote module by Kent Williams (norman-k-williams@uiowa.edu) diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..4890b0e --- /dev/null +++ b/README.rst @@ -0,0 +1,47 @@ +ITKIOFDF +======== + +.. image:: https://github.com/InsightSoftwareConsortium/ITKIOFDF/workflows/Build,%20test,%20package/badge.svg + +.. image:: https://img.shields.io/pypi/v/itk-iofdf.svg + :target: https://pypi.python.org/pypi/itk-iofdf + :alt: PyPI + +.. image:: https://img.shields.io/badge/License-Apache%202.0-blue.svg + :target: https://github.com/InsightSoftwareConsortium/ITKIOFDF/blob/master/LICENSE) + :alt: License + +Overview +-------- + +This is a module for the `Insight Toolkit (ITK) `_ to read or +write the FDF image format. + +It contains an `ImageIO` class to read or write the FDF image format. + +This module is available in the ITK source tree as a Remote module. To enable +it, set:: + + Module_IOFDF:BOOL=ON + +in ITK's CMake build configuration. + +Install the Python package with:: + + pip install itk-iofdf + + +License +------- + +This software is distributed under the Apache 2.0 license. Please see +the *LICENSE* file for details. + + +Acknowledgements +---------------- + +Initial work was done by `Glenn Pierce `_\; the +code was brought up to current ITK standards by +`Nicholas Tustison `_\; and it was converted to an +ITK Remote module by `Kent Williams `_. diff --git a/include/itkFDFCommonImageIO.h b/include/itkFDFCommonImageIO.h index 34226ab..23abae6 100644 --- a/include/itkFDFCommonImageIO.h +++ b/include/itkFDFCommonImageIO.h @@ -1,20 +1,20 @@ -/* Copyright (C) 2004 Glenn Pierce. +/*========================================================================= * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * Copyright NumFOCUS * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Library General Public License for more details. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * You should have received a copy of the GNU Library General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ - + * https://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ #ifndef itkFDFCommonImageIO_h #define itkFDFCommonImageIO_h @@ -31,61 +31,70 @@ namespace itk { -std::string RemoveCharacters( std::string, char ); +std::string +RemoveCharacters(std::string, char); -void Tokenize(const std::string& str, std::vector& tokens, const std::string& delimiters = " "); +void +Tokenize(const std::string & str, std::vector & tokens, const std::string & delimiters = " "); -std::string ParseLine(std::string line); +std::string +ParseLine(std::string line); -template -void ConvertFromString (std::string s, T &value) +template +void +ConvertFromString(std::string s, T & value) { - std::stringstream str; - str << s; - str >> value; + std::stringstream str; + str << s; + str >> value; } -template -void StringToVector (std::string value, std::vector& values) +template +void +StringToVector(std::string value, std::vector & values) { - std::vector tokens; + std::vector tokens; - // value consists of something like {256,256} - std::string::size_type startBracketPosition = value.find_first_of("{", 0); - std::string::size_type endBracketPosition = value.find_first_of("}", startBracketPosition); + // value consists of something like {256,256} + std::string::size_type startBracketPosition = value.find_first_of("{", 0); + std::string::size_type endBracketPosition = value.find_first_of("}", startBracketPosition); - if ( startBracketPosition != std::string::npos && endBracketPosition != std::string::npos) { - std::string elements = value.substr(startBracketPosition + 1, endBracketPosition - startBracketPosition - 1); + if (startBracketPosition != std::string::npos && endBracketPosition != std::string::npos) + { + std::string elements = value.substr(startBracketPosition + 1, endBracketPosition - startBracketPosition - 1); - Tokenize(elements, tokens, ","); - } + Tokenize(elements, tokens, ","); + } - T element; + T element; - for(unsigned int i=0; i -void PrintVector (std::ostream& os, std::string name, const std::vector& vect) +template +void +PrintVector(std::ostream & os, std::string name, const std::vector & vect) { int size = vect.size(); os << name << " {"; - for(int i=0; i < size; i++) { - os << vect[i]; + for (int i = 0; i < size; i++) + { + os << vect[i]; - if (i < size - 1) - os << ", "; + if (i < size - 1) + os << ", "; } os << "}" << std::endl; } -} +} // namespace itk #endif diff --git a/include/itkFDFImageIO.h b/include/itkFDFImageIO.h index 3238bbf..30a6fb1 100644 --- a/include/itkFDFImageIO.h +++ b/include/itkFDFImageIO.h @@ -1,19 +1,20 @@ -/* Copyright (C) 2004 Glenn Pierce. +/*========================================================================= * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * Copyright NumFOCUS * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Library General Public License for more details. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * You should have received a copy of the GNU Library General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ + * https://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ #ifndef itkFDFImageIO_h #define itkFDFImageIO_h @@ -33,10 +34,12 @@ namespace itk class IOFDF_EXPORT FDFImageIO : public ImageIOBase { public: - /** Standard class typedefs. */ - typedef FDFImageIO Self; - typedef ImageIOBase Superclass; - typedef SmartPointer Pointer; + ITK_DISALLOW_COPY_AND_MOVE(FDFImageIO); + + /** Standard class type alias. */ + using Self = FDFImageIO; + using Superclass = ImageIOBase; + using Pointer = SmartPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -44,89 +47,100 @@ class IOFDF_EXPORT FDFImageIO : public ImageIOBase /** Run-time type information (and related methods). */ itkTypeMacro(FDFImageIO, ImageIOBase); - virtual bool SupportsDimension( unsigned long dim ) ITK_OVERRIDE + bool + SupportsDimension(unsigned long dim) override + { + if (dim == 2 || dim == 3) { - if( dim == 2 || dim == 3 ) - { return true; - } + } else - { + { return false; - } } + } /*-------- This part of the interface deals with reading data. ------ */ /** Determine the file type. Returns true if this ImageIO can read the * file specified. */ - virtual bool CanReadFile(const char*) ITK_OVERRIDE; + bool + CanReadFile(const char *) override; /** Set the spacing and diemention information for the set filename. */ - virtual void ReadImageInformation() ITK_OVERRIDE; + void + ReadImageInformation() override; /** Get the type of the pixel. */ -// virtual const std::type_info& GetPixelType() const; + // virtual const std::type_info& GetPixelType() const; /** Reads the data from disk into the memory buffer provided. */ - virtual void Read(void* buffer) ITK_OVERRIDE; + void + Read(void * buffer) override; /** Reads 3D data from multiple files assuming one slice per file. */ - virtual void ReadVolume(void* buffer); + virtual void + ReadVolume(void * buffer); /** Compute the size (in bytes) of the components of a pixel. For * example, and RGB pixel of unsigned char would have a * component size of 1 byte. */ -// virtual unsigned int GetComponentSize() const; + // virtual unsigned int GetComponentSize() const; /*-------- This part of the interfaces deals with writing data. ----- */ /** Determine the file type. Returns true if this ImageIO can read the * file specified. */ - virtual bool CanWriteFile(const char*) ITK_OVERRIDE; + bool + CanWriteFile(const char *) override; /** Writes the spacing and dimentions of the image. * Assumes SetFileName has been called with a valid file name. */ - virtual void WriteImageInformation() ITK_OVERRIDE; + void + WriteImageInformation() override; /** Writes the data to disk from the memory buffer provided. Make sure * that the IORegion has been set properly. */ - virtual void Write(const void* buffer) ITK_OVERRIDE; + void + Write(const void * buffer) override; protected: FDFImageIO(); - ~FDFImageIO(); - void PrintSelf(std::ostream& os, Indent indent) const ITK_OVERRIDE; + ~FDFImageIO() override; + void + PrintSelf(std::ostream & os, Indent indent) const override; - void WriteSlice(std::string& fileName, const void* buffer); + void + WriteSlice(std::string & fileName, const void * buffer); - int ReadHeader(const char *FileNameToRead); + int + ReadHeader(const char * FileNameToRead); private: - FDFImageIO(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - - void SwapBytesIfNecessary(void* buffer, unsigned long numberOfPixels); + void + SwapBytesIfNecessary(void * buffer, unsigned long numberOfPixels); // Position after ReadImageInformation. size_t m_InputPosition; - std::string m_SpatialRank; - std::string m_Checksum; - std::string m_Bits; - std::vector m_Size; - std::vector m_Location; - std::vector m_Span; - std::vector m_Roi; + std::string m_SpatialRank; + std::string m_Checksum; + std::string m_Bits; + std::vector m_Size; + std::vector m_Location; + std::vector m_Span; + std::vector m_Roi; }; } // end namespace itk -#define RAISE_EXCEPTION() \ - { ExceptionObject exception(__FILE__, __LINE__); \ - exception.SetDescription("File cannot be read"); \ - throw exception; } +#define RAISE_EXCEPTION() \ + { \ + ExceptionObject exception(__FILE__, __LINE__); \ + exception.SetDescription("File cannot be read"); \ + throw exception; \ + } #endif diff --git a/include/itkFDFImageIOFactory.h b/include/itkFDFImageIOFactory.h index b0c7250..3788c18 100644 --- a/include/itkFDFImageIOFactory.h +++ b/include/itkFDFImageIOFactory.h @@ -1,19 +1,20 @@ -/* Copyright (C) 2004 Glenn Pierce. +/*========================================================================= * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * Copyright NumFOCUS * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Library General Public License for more details. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * You should have received a copy of the GNU Library General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ + * https://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ #ifndef itkFDFImageIOFactory_h #define itkFDFImageIOFactory_h #include "IOFDFExport.h" @@ -29,15 +30,19 @@ namespace itk class IOFDF_EXPORT FDFImageIOFactory : public ObjectFactoryBase { public: - /** Standard class typedefs. */ - typedef FDFImageIOFactory Self; - typedef ObjectFactoryBase Superclass; - typedef SmartPointer Pointer; - typedef SmartPointer ConstPointer; + ITK_DISALLOW_COPY_AND_MOVE(FDFImageIOFactory); + + /** Standard class type alias. */ + using Self = FDFImageIOFactory; + using Superclass = ObjectFactoryBase; + using Pointer = SmartPointer; + using ConstPointer = SmartPointer; /** Class methods used to interface with the registered factories. */ - virtual const char* GetITKSourceVersion(void) const ITK_OVERRIDE; - virtual const char* GetDescription(void) const ITK_OVERRIDE; + const char * + GetITKSourceVersion() const override; + const char * + GetDescription() const override; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); @@ -46,20 +51,16 @@ class IOFDF_EXPORT FDFImageIOFactory : public ObjectFactoryBase itkTypeMacro(FDFImageIOFactory, ObjectFactoryBase); /** Register one factory of this type */ - static void RegisterOneFactory(void) + static void + RegisterOneFactory() { FDFImageIOFactory::Pointer FdfFactory = FDFImageIOFactory::New(); - ObjectFactoryBase::RegisterFactory(FdfFactory); + ObjectFactoryBase::RegisterFactoryInternal(FdfFactory); } protected: FDFImageIOFactory(); - ~FDFImageIOFactory(); - -private: - FDFImageIOFactory(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - + ~FDFImageIOFactory() override; }; diff --git a/itk-module.cmake b/itk-module.cmake index a0d7b1f..f5dafbb 100644 --- a/itk-module.cmake +++ b/itk-module.cmake @@ -1,6 +1,14 @@ -set(DOCUMENTATION "This modules contains an ImageIO class to read or write the -FDF image format.") +# the top-level README is used for describing this module, just +# re-used it for documentation here +get_filename_component(MY_CURRENT_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) +file(READ "${MY_CURRENT_DIR}/README.rst" DOCUMENTATION) +# itk_module() defines the module dependencies in IOFDF +# The testing module in IOFDF depends on ITKTestKernel +# By convention those modules outside of ITK are not prefixed with +# ITK + +# define the dependencies of the include module and the tests itk_module(IOFDF ENABLE_SHARED DEPENDS @@ -9,6 +17,8 @@ itk_module(IOFDF TEST_DEPENDS ITKTestKernel ITKTransform + FACTORY_NAMES + ImageIO::FDF DESCRIPTION "${DOCUMENTATION}" EXCLUDE_FROM_DEFAULT diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..d601876 --- /dev/null +++ b/setup.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from os import sys + +try: + from skbuild import setup +except ImportError: + print('scikit-build is required to build from source.', file=sys.stderr) + print('Please run:', file=sys.stderr) + print('', file=sys.stderr) + print(' python -m pip install scikit-build') + sys.exit(1) + +setup( + name='itk-iofdf', + version='1.0.2', + author='Glenn Pierce', + author_email='glennpierce@gmail.com', + packages=['itk'], + package_dir={'itk': 'itk'}, + download_url=r'https://github.com/InsightSoftwareConsortium/ITKIOFDF', + description=r'ITK `ImageIO` class to read or write the FDF image format', + long_description='itk-iofdf provides an `ImageIO` class to read or ' + 'write the FDF image format.', + classifiers=[ + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: C++", + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: Healthcare Industry", + "Intended Audience :: Science/Research", + "Topic :: Scientific/Engineering", + "Topic :: Scientific/Engineering :: Medical Science Apps.", + "Topic :: Scientific/Engineering :: Information Analysis", + "Topic :: Software Development :: Libraries", + "Operating System :: Android", + "Operating System :: Microsoft :: Windows", + "Operating System :: POSIX", + "Operating System :: Unix", + "Operating System :: MacOS" + ], + license='Apache', + keywords='ITK InsightToolkit FDF', + url=r'https://github.com/InsightSoftwareConsortium/ITKIOFDF', + install_requires=[ + r'itk>=5.2.0.post3' + ] + ) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 0903c68..e05f33c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -3,7 +3,7 @@ set(IOFDF_SRC itkFDFCommonImageIO.cxx itkFDFImageIOFactory.cxx) -add_library(IOFDF ${IOFDF_SRC}) +add_library(IOFDF ${ITK_LIBRARY_BUILD_TYPE} ${IOFDF_SRC}) target_link_libraries(IOFDF ${ITKIOImageBase_LIBRARIES} ${ITKTransform_LIBRARIES}) itk_module_target(IOFDF) diff --git a/src/ImageReadWrite.cxx b/src/ImageReadWrite.cxx index 6612eb5..4d7e287 100644 --- a/src/ImageReadWrite.cxx +++ b/src/ImageReadWrite.cxx @@ -1,12 +1,12 @@ /*========================================================================= * - * Copyright Insight Software Consortium + * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0.txt + * https://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -28,59 +28,61 @@ #include "itkImage.h" -int main( int argc, char ** argv ) +int +main(int argc, char ** argv) { - typedef float PixelType; - const unsigned int Dimension = 2; + using PixelType = float; + constexpr unsigned int Dimension = 2; - typedef itk::Image< PixelType, Dimension > ImageType; - typedef itk::ImageFileReader< ImageType > ReaderType; - typedef itk::ImageToVTKImageFilter< ImageType > ImageToVTKType; - typedef itk::NormalizeImageFilter< ImageType, ImageType> NormalizeFilter; - typedef itk::ChangeInformationImageFilter< ImageType > ChangeInformationFilter; + using ImageType = itk::Image; + using ReaderType = itk::ImageFileReader; + using ImageToVTKType = itk::ImageToVTKImageFilter; + using NormalizeFilter = itk::NormalizeImageFilter; + using ChangeInformationFilter = itk::ChangeInformationImageFilter; // Register FDF Factory itk::FDFImageIOFactory::RegisterOneFactory(); - ReaderType::Pointer reader = ReaderType::New(); - NormalizeFilter::Pointer normalizer = NormalizeFilter::New(); + ReaderType::Pointer reader = ReaderType::New(); + NormalizeFilter::Pointer normalizer = NormalizeFilter::New(); ChangeInformationFilter::Pointer movingChange = ChangeInformationFilter::New(); - reader->SetFileName( "/home/glenn/development/reader/test.fdf" ); + reader->SetFileName("/home/glenn/development/reader/test.fdf"); - try { - reader->Update(); + try + { + reader->Update(); } - catch( itk::ExceptionObject & exp ) + catch (itk::ExceptionObject & exp) { - std::cerr << "Exception caught" << std::endl; - std::cerr << exp << std::endl; + std::cerr << "Exception caught" << std::endl; + std::cerr << exp << std::endl; } std::cout << reader << std::endl; - normalizer->SetInput( reader->GetOutput() ); + normalizer->SetInput(reader->GetOutput()); movingChange->SetInput(normalizer->GetOutput()); movingChange->CenterImageOn(); - vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New(); + vtkRenderWindowInteractor * iren = vtkRenderWindowInteractor::New(); ImageToVTKType::Pointer bridge = ImageToVTKType::New(); - bridge->SetInput( movingChange->GetOutput() ); + bridge->SetInput(movingChange->GetOutput()); - vtkImageViewer *viewer = vtkImageViewer::New(); - viewer->SetInput( bridge->GetOutput() ); + vtkImageViewer * viewer = vtkImageViewer::New(); + viewer->SetInput(bridge->GetOutput()); viewer->SetColorWindow(1); viewer->SetColorLevel(0.1); - //viewer->SetupInteractor(iren); + // viewer->SetupInteractor(iren); - while(1) - viewer->Render(); + while (1) + viewer->Render(); viewer->Delete(); - //iren->Delete(); + // iren->Delete(); return 0; } diff --git a/src/itkFDFCommonImageIO.cxx b/src/itkFDFCommonImageIO.cxx index 5fafc2b..f5c3e5b 100644 --- a/src/itkFDFCommonImageIO.cxx +++ b/src/itkFDFCommonImageIO.cxx @@ -1,19 +1,20 @@ -/* Copyright (C) 2004 Glenn Pierce. +/*========================================================================= * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * Copyright NumFOCUS * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Library General Public License for more details. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * You should have received a copy of the GNU Library General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ + * https://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ #include "itkFDFCommonImageIO.h" @@ -21,55 +22,59 @@ namespace itk { // Remove a particular type of character from a string -std::string RemoveCharacters( std::string line, char character ) +std::string +RemoveCharacters(std::string line, char character) { - line.erase( std::remove( line.begin(), line.end(), character ), line.end() ); + line.erase(std::remove(line.begin(), line.end(), character), line.end()); return line; } -void Tokenize(const std::string& str, std::vector& tokens, const std::string& delimiters) +void +Tokenize(const std::string & str, std::vector & tokens, const std::string & delimiters) { - // Skip delimiters at beginning. - std::string::size_type lastPos = str.find_first_not_of(delimiters, 0); - // Find first "non-delimiter". - std::string::size_type pos = str.find_first_of(delimiters, lastPos); + // Skip delimiters at beginning. + std::string::size_type lastPos = str.find_first_not_of(delimiters, 0); + // Find first "non-delimiter". + std::string::size_type pos = str.find_first_of(delimiters, lastPos); - while (std::string::npos != pos || std::string::npos != lastPos) - { - // Found a token, add it to the vector. - tokens.push_back(str.substr(lastPos, pos - lastPos)); - // Skip delimiters. Note the "not_of" - lastPos = str.find_first_not_of(delimiters, pos); - // Find next "non-delimiter" - pos = str.find_first_of(delimiters, lastPos); - } + while (std::string::npos != pos || std::string::npos != lastPos) + { + // Found a token, add it to the vector. + tokens.push_back(str.substr(lastPos, pos - lastPos)); + // Skip delimiters. Note the "not_of" + lastPos = str.find_first_not_of(delimiters, pos); + // Find next "non-delimiter" + pos = str.find_first_of(delimiters, lastPos); + } } -std::string ParseLine(std::string line) +std::string +ParseLine(std::string line) { - // strip * - line = RemoveCharacters( line, '*' ); - line = RemoveCharacters( line, '\"' ); - line = RemoveCharacters( line, '[' ); - line = RemoveCharacters( line, ']' ); + // strip * + line = RemoveCharacters(line, '*'); + line = RemoveCharacters(line, '\"'); + line = RemoveCharacters(line, '['); + line = RemoveCharacters(line, ']'); - // Need to deal with space between {} - std::string::size_type startBracketPosition = line.find_first_of("{", 0); - std::string::size_type endBracketPosition = line.find_first_of("}", startBracketPosition); + // Need to deal with space between {} + std::string::size_type startBracketPosition = line.find_first_of("{", 0); + std::string::size_type endBracketPosition = line.find_first_of("}", startBracketPosition); - if ( startBracketPosition != std::string::npos && endBracketPosition != std::string::npos) { - std::string element = line.substr(startBracketPosition, endBracketPosition - startBracketPosition); + if (startBracketPosition != std::string::npos && endBracketPosition != std::string::npos) + { + std::string element = line.substr(startBracketPosition, endBracketPosition - startBracketPosition); - // Find whitespace within {} and erase - std::string::size_type whiteSpacePosition = line.find_first_of(" ", startBracketPosition); + // Find whitespace within {} and erase + std::string::size_type whiteSpacePosition = line.find_first_of(" ", startBracketPosition); - while (whiteSpacePosition != std::string::npos) - { - line.erase(whiteSpacePosition, 1); - whiteSpacePosition = line.find_first_of(" ", whiteSpacePosition); - } + while (whiteSpacePosition != std::string::npos) + { + line.erase(whiteSpacePosition, 1); + whiteSpacePosition = line.find_first_of(" ", whiteSpacePosition); } + } - return line; -} + return line; } +} // namespace itk diff --git a/src/itkFDFImageIO.cxx b/src/itkFDFImageIO.cxx index e77e5b1..a862fdc 100644 --- a/src/itkFDFImageIO.cxx +++ b/src/itkFDFImageIO.cxx @@ -1,19 +1,20 @@ -/* Copyright (C) 2004 Glenn Pierce. +/*========================================================================= * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * Copyright NumFOCUS * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Library General Public License for more details. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * You should have received a copy of the GNU Library General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ + * https://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ #include "itkFDFImageIO.h" #include "itkFDFCommonImageIO.h" @@ -21,54 +22,53 @@ #include "itkRGBPixel.h" #include "itkRGBAPixel.h" #include "vnl/vnl_matrix.h" -#include +#include #include namespace itk { -bool FDFImageIO::CanReadFile(const char* file) +bool +FDFImageIO::CanReadFile(const char * file) { this->SetFileName(file); // First check the extension std::string filename = file; - if( filename == "" ) - { - itkDebugMacro(<<"No filename specified."); + if (filename.empty()) + { + itkDebugMacro(<< "No filename specified."); return false; - } + } - bool extensionFound = false; + bool extensionFound = false; std::string::size_type FDFPos = filename.rfind(".fdf"); - if ((FDFPos != std::string::npos) - && (FDFPos == filename.length() - 4)) - { + if ((FDFPos != std::string::npos) && (FDFPos == filename.length() - 4)) + { extensionFound = true; - } + } FDFPos = filename.rfind(".FDF"); - if ((FDFPos != std::string::npos) - && (FDFPos == filename.length() - 4)) - { + if ((FDFPos != std::string::npos) && (FDFPos == filename.length() - 4)) + { extensionFound = true; - } + } - if( !extensionFound ) - { - itkDebugMacro(<<"The filename extension is not recognized"); + if (!extensionFound) + { + itkDebugMacro(<< "The filename extension is not recognized"); return false; - } + } std::ifstream inFile; - inFile.open(m_FileName.c_str(), std::ios::in | std::ios::binary ); - if( !inFile ) - { + inFile.open(m_FileName.c_str(), std::ios::in | std::ios::binary); + if (!inFile) + { ExceptionObject exception(__FILE__, __LINE__); - std::string msg = "File \"" + m_FileName + "\" cannot be read."; + std::string msg = "File \"" + m_FileName + "\" cannot be read."; exception.SetDescription(msg.c_str()); throw exception; - } + } // Check for a neccessary header variable @@ -76,14 +76,15 @@ bool FDFImageIO::CanReadFile(const char* file) return true; } -void FDFImageIO::ReadImageInformation() +void +FDFImageIO::ReadImageInformation() { - if(!this->CanReadFile(m_FileName.c_str())) + if (!this->CanReadFile(m_FileName.c_str())) RAISE_EXCEPTION(); - std::string line; + std::string line; std::vector tokens; - std::string type, name, value; + std::string type, name, value; ImageIORegion region; @@ -91,224 +92,223 @@ void FDFImageIO::ReadImageInformation() // Check if there was an error opening the file if (!inFile) - { + { std::cout << "Unable to open the file\n"; RAISE_EXCEPTION(); - } + } this->SetFileTypeToBinary(); - while( getline( inFile, line, '\n' ) ) + while (getline(inFile, line, '\n')) + { + if (line == "\0") { - if ( line == "\0" ) - { break; - } + } // Formats the lines in the FDF header such as removing whitespace between {} - line = ParseLine( line ); - Tokenize( line, tokens, " ;" ); + line = ParseLine(line); + Tokenize(line, tokens, " ;"); - if( tokens.size() == 4 ) - { + if (tokens.size() == 4) + { type = tokens[0]; name = tokens[1]; value = tokens[3]; - if( name == "spatial_rank" ) - { + if (name == "spatial_rank") + { this->m_SpatialRank = value; - } + } - if( name == "matrix" ) - { + if (name == "matrix") + { std::vector dimensions; - StringToVector( value, dimensions ); + StringToVector(value, dimensions); // Set the number of dimensions - if( this->GetNumberOfDimensions() < dimensions.size() ) - { - this->SetNumberOfDimensions( dimensions.size() ); - } + if (this->GetNumberOfDimensions() < dimensions.size()) + { + this->SetNumberOfDimensions(dimensions.size()); + } - ImageIORegion::SizeType size( dimensions.size() ); - ImageIORegion::IndexType index( dimensions.size() ); + ImageIORegion::SizeType size(dimensions.size()); + ImageIORegion::IndexType index(dimensions.size()); - for( unsigned int i = 0; i < dimensions.size(); i++ ) - { - this->SetDimensions( i, dimensions[i] ); + for (unsigned int i = 0; i < dimensions.size(); i++) + { + this->SetDimensions(i, dimensions[i]); size[i] = dimensions[i]; index[i] = 0; - } - - region.SetSize( size ); - region.SetIndex( index ); - this->SetIORegion( region ); } - if( name == "orientation" ) - { - const unsigned numDim(this->GetNumberOfDimensions()); + region.SetSize(size); + region.SetIndex(index); + this->SetIORegion(region); + } + + if (name == "orientation") + { + const unsigned numDim(this->GetNumberOfDimensions()); std::vector orientation; - StringToVector( value, orientation ); + StringToVector(value, orientation); - vnl_matrix testDirections(numDim,numDim); + vnl_matrix testDirections(numDim, numDim); - for( unsigned int i = 0; i < numDim; i++ ) - { + for (unsigned int i = 0; i < numDim; i++) + { std::vector componentVector; - for( unsigned int j = 0; j < numDim; j++ ) - { + for (unsigned int j = 0; j < numDim; j++) + { double val = orientation[i * numDim + j]; - testDirections(j,i) = val; - componentVector.push_back( val ); - } - this->SetDirection( i, componentVector ); + testDirections(j, i) = val; + componentVector.push_back(val); } + this->SetDirection(i, componentVector); + } // check for degenerate dimensions. this will happen // if the dimension of the image is 2 but the // direction matrix in the file is 3x3. // if direction matrix is degenerate, punt and set // directions to identity - if(vnl_determinant(testDirections) == 0) + if (vnl_determinant(testDirections) == 0) + { + for (unsigned int i = 0; i < numDim; i++) { - for( unsigned int i = 0; i < numDim; i++ ) - { std::vector componentVector; - for( unsigned int j = 0; j < numDim; j++ ) - { + for (unsigned int j = 0; j < numDim; j++) + { double val = i == j ? 1.0 : 0.0; - componentVector.push_back( val ); - } - this->SetDirection( i, componentVector ); + componentVector.push_back(val); } + this->SetDirection(i, componentVector); } } - if( name == "span" ) - { - StringToVector( value, this->m_Span ); - } + } + if (name == "span") + { + StringToVector(value, this->m_Span); + } - if( name == "origin" ) - { + if (name == "origin") + { std::vector origin; - StringToVector( value, origin ); + StringToVector(value, origin); - if( this->GetNumberOfDimensions() < origin.size() ) - { - this->SetNumberOfDimensions( origin.size() ); - } - - for( unsigned int i = 0; i < origin.size(); i++ ) - { - this->SetOrigin( i, origin[i] / 10.0 ); - } - } - - if( name == "roi" ) + if (this->GetNumberOfDimensions() < origin.size()) { - StringToVector( value, this->m_Roi ); + this->SetNumberOfDimensions(origin.size()); } - if( name == "location" ) + for (unsigned int i = 0; i < origin.size(); i++) { - StringToVector( value, this->m_Location ); + this->SetOrigin(i, origin[i] / 10.0); } + } - if( name == "bigendian" ) + if (name == "roi") + { + StringToVector(value, this->m_Roi); + } + + if (name == "location") + { + StringToVector(value, this->m_Location); + } + + if (name == "bigendian") + { + if (value == "0") { - if( value == "0" ) - { this->SetByteOrderToLittleEndian(); - } + } else - { + { this->SetByteOrderToBigEndian(); - } } + } // Get the binary data type - if( name == "storage" ) - { - this->SetPixelType( SCALAR ); + if (name == "storage") + { + this->SetPixelType(IOPixelEnum::SCALAR); - if( value == "double" ) - { - this->SetComponentType( DOUBLE ); - } - else if( value == "float" ) - { - this->SetComponentType( FLOAT ); - } - else if( value == "long" ) - { - this->SetComponentType( LONG ); - } - else if( value == "unsigned long" ) - { - this->SetComponentType( ULONG ); - } - else if( value == "int" ) - { - this->SetComponentType( INT ); - } - else if( value == "unsigned int" ) - { - this->SetComponentType( UINT ); - } - else if( value == "short" ) - { - this->SetComponentType( SHORT ); - } - else if( value == "unsigned short" ) - { - this->SetComponentType( USHORT ); - } - else if( value == "char" ) - { - this->SetComponentType( CHAR ); - } - else if( value == "unsigned char" ) - { - this->SetComponentType( UCHAR ); - } + if (value == "double") + { + this->SetComponentType(IOComponentEnum::DOUBLE); + } + else if (value == "float") + { + this->SetComponentType(IOComponentEnum::FLOAT); + } + else if (value == "long") + { + this->SetComponentType(IOComponentEnum::LONG); + } + else if (value == "unsigned long") + { + this->SetComponentType(IOComponentEnum::ULONG); + } + else if (value == "int") + { + this->SetComponentType(IOComponentEnum::INT); + } + else if (value == "unsigned int") + { + this->SetComponentType(IOComponentEnum::UINT); + } + else if (value == "short") + { + this->SetComponentType(IOComponentEnum::SHORT); + } + else if (value == "unsigned short") + { + this->SetComponentType(IOComponentEnum::USHORT); + } + else if (value == "char") + { + this->SetComponentType(IOComponentEnum::CHAR); + } + else if (value == "unsigned char") + { + this->SetComponentType(IOComponentEnum::UCHAR); + } else - { - itkExceptionMacro( "Unknown component type: " << value ); - } + { + itkExceptionMacro("Unknown component type: " << value); } + } // Get the bits - if( name == "bits" ) - { - ConvertFromString( value, this->m_Bits ); - } + if (name == "bits") + { + ConvertFromString(value, this->m_Bits); + } // Get the checksum - if( name == "checksum" ) - { - ConvertFromString( value, this->m_Checksum ); - } + if (name == "checksum") + { + ConvertFromString(value, this->m_Checksum); } + } tokens.clear(); - } + } - inFile.seekg( 0, std::ios::end ); + inFile.seekg(0, std::ios::end); long int fileSize = inFile.tellg(); this->m_InputPosition = fileSize - this->GetImageSizeInBytes(); - for( unsigned int i = 0; i < this->GetNumberOfDimensions(); i++ ) - { - this->SetSpacing( i, ( this->m_Roi[i] * 10 ) / this->GetDimensions( i ) ); - } + for (unsigned int i = 0; i < this->GetNumberOfDimensions(); i++) + { + this->SetSpacing(i, (this->m_Roi[i] * 10) / this->GetDimensions(i)); + } } -void FDFImageIO::ReadVolume(void*) -{ - -} +void +FDFImageIO::ReadVolume(void *) +{} // const std::type_info& FDFImageIO::GetPixelType() const // { @@ -340,8 +340,8 @@ void FDFImageIO::ReadVolume(void*) // return typeid(RGBAPixel); // default: // { -// itkExceptionMacro ("Invalid type: " << m_PixelType << ", only unsigned char, unsigned short, RGB are allowed."); -// return this->ConvertToTypeInfo(m_PixelType); +// itkExceptionMacro ("Invalid type: " << m_PixelType << ", only unsigned char, unsigned short, RGB +// are allowed."); return this->ConvertToTypeInfo(m_PixelType); // } // case UNKNOWN: // itkExceptionMacro ("Unknown pixel type: " << m_PixelType); @@ -389,7 +389,8 @@ void FDFImageIO::ReadVolume(void*) // return 1; // } -void FDFImageIO::Read(void* buffer) +void +FDFImageIO::Read(void * buffer) { std::ifstream inFile(m_FileName.c_str(), std::ios::in | std::ios::binary); @@ -399,201 +400,186 @@ void FDFImageIO::Read(void* buffer) RAISE_EXCEPTION(); } - inFile.seekg( this->m_InputPosition ); + inFile.seekg(this->m_InputPosition); if (!inFile) - { + { RAISE_EXCEPTION(); - } + } - char * p = static_cast(buffer); + auto * p = static_cast(buffer); - inFile.read( p, this->GetImageSizeInBytes() ); + inFile.read(p, this->GetImageSizeInBytes()); bool success = !inFile.bad(); inFile.close(); - if( !success ) - { + if (!success) + { itkExceptionMacro("Error reading image data."); - } + } - this->SwapBytesIfNecessary( buffer, this->GetImageSizeInPixels() ); + this->SwapBytesIfNecessary(buffer, this->GetImageSizeInPixels()); } -FDFImageIO::FDFImageIO() -{ -} +FDFImageIO::FDFImageIO() = default; -FDFImageIO::~FDFImageIO() {} +FDFImageIO::~FDFImageIO() = default; -void FDFImageIO::PrintSelf(std::ostream& os, Indent indent) const +void +FDFImageIO::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); -// os << indent << "PixelType " << m_PixelType << "\n"; -// os << indent << "Start of image in bytes from start of file " << this->m_InputPosition << "\n"; -// os << indent << "Number of pixels in image: " << this->GetImageSizeInPixels() << "\n"; -// os << indent << "Image size in bytes: " << this->GetImageSizeInBytes() << "\n"; -// os << indent << "Checksum: " << this->checksum << "\n"; -// os << indent << "Spatial Rank: " << this->spatial_rank << "\n"; -// os << indent << "Bits: " << this->bits << "\n"; -// os << indent; PrintVector(os, "Matrix", this->matrix); -// os << indent; PrintVector(os, "Location", this->location); -// os << indent; PrintVector(os, "ROI", this->roi); -// os << indent; PrintVector(os, "Span", this->span); + // os << indent << "PixelType " << m_PixelType << "\n"; + // os << indent << "Start of image in bytes from start of file " << this->m_InputPosition << "\n"; + // os << indent << "Number of pixels in image: " << this->GetImageSizeInPixels() << "\n"; + // os << indent << "Image size in bytes: " << this->GetImageSizeInBytes() << "\n"; + // os << indent << "Checksum: " << this->checksum << "\n"; + // os << indent << "Spatial Rank: " << this->spatial_rank << "\n"; + // os << indent << "Bits: " << this->bits << "\n"; + // os << indent; PrintVector(os, "Matrix", this->matrix); + // os << indent; PrintVector(os, "Location", this->location); + // os << indent; PrintVector(os, "ROI", this->roi); + // os << indent; PrintVector(os, "Span", this->span); } -bool FDFImageIO::CanWriteFile( const char * /* name */) +bool +FDFImageIO::CanWriteFile(const char * /* name */) { - //not possible to write a fdf file + // not possible to write a fdf file return false; } -void FDFImageIO::SwapBytesIfNecessary( void* buffer, unsigned long numberOfPixels ) +void +FDFImageIO::SwapBytesIfNecessary(void * buffer, unsigned long numberOfPixels) { - switch( this->GetComponentType() ) + switch (this->GetComponentType()) + { + case IOComponentEnum::CHAR: { - case CHAR: + if (this->m_ByteOrder == IOByteOrderEnum::LittleEndian) { - if ( this->m_ByteOrder == LittleEndian ) - { - ByteSwapper::SwapRangeFromSystemToLittleEndian( - (char*)buffer, numberOfPixels ); - } - else if ( this->m_ByteOrder == BigEndian ) - { - ByteSwapper::SwapRangeFromSystemToBigEndian( - (char *)buffer, numberOfPixels ); - } - break; + ByteSwapper::SwapRangeFromSystemToLittleEndian((char *)buffer, numberOfPixels); } - case FLOAT: + else if (this->m_ByteOrder == IOByteOrderEnum::BigEndian) { - if ( this->m_ByteOrder == LittleEndian ) - { - ByteSwapper::SwapRangeFromSystemToLittleEndian( - (float *)buffer, numberOfPixels ); - } - else if ( this->m_ByteOrder == BigEndian ) - { - ByteSwapper::SwapRangeFromSystemToBigEndian( - (float *)buffer, numberOfPixels ); - } + ByteSwapper::SwapRangeFromSystemToBigEndian((char *)buffer, numberOfPixels); + } break; + } + case IOComponentEnum::FLOAT: + { + if (this->m_ByteOrder == IOByteOrderEnum::LittleEndian) + { + ByteSwapper::SwapRangeFromSystemToLittleEndian((float *)buffer, numberOfPixels); } - case UCHAR: + else if (this->m_ByteOrder == IOByteOrderEnum::BigEndian) { - if ( this->m_ByteOrder == LittleEndian ) - { - ByteSwapper::SwapRangeFromSystemToLittleEndian( - (unsigned char*)buffer, numberOfPixels ); - } - else if ( this->m_ByteOrder == BigEndian ) - { - ByteSwapper::SwapRangeFromSystemToBigEndian( - (unsigned char *)buffer, numberOfPixels ); - } + ByteSwapper::SwapRangeFromSystemToBigEndian((float *)buffer, numberOfPixels); + } break; + } + case IOComponentEnum::UCHAR: + { + if (this->m_ByteOrder == IOByteOrderEnum::LittleEndian) + { + ByteSwapper::SwapRangeFromSystemToLittleEndian((unsigned char *)buffer, numberOfPixels); } - case SHORT: + else if (this->m_ByteOrder == IOByteOrderEnum::BigEndian) { - if ( this->m_ByteOrder == LittleEndian ) - { - ByteSwapper::SwapRangeFromSystemToLittleEndian( - (short*)buffer, numberOfPixels ); - } - else if ( this->m_ByteOrder == BigEndian ) - { - ByteSwapper::SwapRangeFromSystemToBigEndian( - (short *)buffer, numberOfPixels ); - } + ByteSwapper::SwapRangeFromSystemToBigEndian((unsigned char *)buffer, numberOfPixels); + } break; + } + case IOComponentEnum::SHORT: + { + if (this->m_ByteOrder == IOByteOrderEnum::LittleEndian) + { + ByteSwapper::SwapRangeFromSystemToLittleEndian((short *)buffer, numberOfPixels); } - case USHORT: + else if (this->m_ByteOrder == IOByteOrderEnum::BigEndian) { - if ( this->m_ByteOrder == LittleEndian ) - { - ByteSwapper::SwapRangeFromSystemToLittleEndian( - (unsigned short*)buffer, numberOfPixels ); - } - else if ( this->m_ByteOrder == BigEndian ) - { - ByteSwapper::SwapRangeFromSystemToBigEndian( - (unsigned short *)buffer, numberOfPixels ); - } + ByteSwapper::SwapRangeFromSystemToBigEndian((short *)buffer, numberOfPixels); + } break; + } + case IOComponentEnum::USHORT: + { + if (this->m_ByteOrder == IOByteOrderEnum::LittleEndian) + { + ByteSwapper::SwapRangeFromSystemToLittleEndian((unsigned short *)buffer, numberOfPixels); } - case INT: + else if (this->m_ByteOrder == IOByteOrderEnum::BigEndian) { - if ( this->m_ByteOrder == LittleEndian ) - { - ByteSwapper::SwapRangeFromSystemToLittleEndian( - (int*)buffer, numberOfPixels ); - } - else if ( this->m_ByteOrder == BigEndian ) - { - ByteSwapper::SwapRangeFromSystemToBigEndian( - (int *)buffer, numberOfPixels ); - } + ByteSwapper::SwapRangeFromSystemToBigEndian((unsigned short *)buffer, numberOfPixels); + } break; + } + case IOComponentEnum::INT: + { + if (this->m_ByteOrder == IOByteOrderEnum::LittleEndian) + { + ByteSwapper::SwapRangeFromSystemToLittleEndian((int *)buffer, numberOfPixels); } - case UINT: + else if (this->m_ByteOrder == IOByteOrderEnum::BigEndian) { - if ( this->m_ByteOrder == LittleEndian ) - { - ByteSwapper::SwapRangeFromSystemToLittleEndian( - (unsigned int*)buffer, numberOfPixels ); - } - else if ( this->m_ByteOrder == BigEndian ) - { - ByteSwapper::SwapRangeFromSystemToBigEndian( - (unsigned int *)buffer, numberOfPixels ); - } + ByteSwapper::SwapRangeFromSystemToBigEndian((int *)buffer, numberOfPixels); + } break; + } + case IOComponentEnum::UINT: + { + if (this->m_ByteOrder == IOByteOrderEnum::LittleEndian) + { + ByteSwapper::SwapRangeFromSystemToLittleEndian((unsigned int *)buffer, numberOfPixels); } - case LONG: + else if (this->m_ByteOrder == IOByteOrderEnum::BigEndian) { - if ( this->m_ByteOrder == LittleEndian ) - { - ByteSwapper::SwapRangeFromSystemToLittleEndian( - (long*)buffer, numberOfPixels ); - } - else if ( this->m_ByteOrder == BigEndian ) - { - ByteSwapper::SwapRangeFromSystemToBigEndian( - (long *)buffer, numberOfPixels ); - } + ByteSwapper::SwapRangeFromSystemToBigEndian((unsigned int *)buffer, numberOfPixels); + } break; + } + case IOComponentEnum::LONG: + { + if (this->m_ByteOrder == IOByteOrderEnum::LittleEndian) + { + ByteSwapper::SwapRangeFromSystemToLittleEndian((long *)buffer, numberOfPixels); } - case ULONG: + else if (this->m_ByteOrder == IOByteOrderEnum::BigEndian) { - if ( this->m_ByteOrder == LittleEndian ) - { - ByteSwapper::SwapRangeFromSystemToLittleEndian( - (unsigned long*)buffer, numberOfPixels ); - } - else if ( this->m_ByteOrder == BigEndian ) - { - ByteSwapper::SwapRangeFromSystemToBigEndian( - (unsigned long *)buffer, numberOfPixels ); - } + ByteSwapper::SwapRangeFromSystemToBigEndian((long *)buffer, numberOfPixels); + } break; + } + case IOComponentEnum::ULONG: + { + if (this->m_ByteOrder == IOByteOrderEnum::LittleEndian) + { + ByteSwapper::SwapRangeFromSystemToLittleEndian((unsigned long *)buffer, numberOfPixels); + } + else if (this->m_ByteOrder == IOByteOrderEnum::BigEndian) + { + ByteSwapper::SwapRangeFromSystemToBigEndian((unsigned long *)buffer, numberOfPixels); } + break; + } default: - ExceptionObject exception( __FILE__, __LINE__ ); - exception.SetDescription( "Pixel Type Unknown" ); + ExceptionObject exception(__FILE__, __LINE__); + exception.SetDescription("Pixel Type Unknown"); throw exception; - } + } } -void FDFImageIO::WriteImageInformation(void) +void +FDFImageIO::WriteImageInformation() { - //not possible to write a fdf file + // not possible to write a fdf file } -void FDFImageIO::Write(const void* /* buffer */) +void +FDFImageIO::Write(const void * /* buffer */) { - //not possible to write a fdf file + // not possible to write a fdf file } } // end namespace itk diff --git a/src/itkFDFImageIOFactory.cxx b/src/itkFDFImageIOFactory.cxx index 69b46d4..a09f48a 100644 --- a/src/itkFDFImageIOFactory.cxx +++ b/src/itkFDFImageIOFactory.cxx @@ -1,19 +1,20 @@ -/* Copyright (C) 2004 Glenn Pierce. +/*========================================================================= * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * Copyright NumFOCUS * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Library General Public License for more details. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * You should have received a copy of the GNU Library General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ + * https://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ #include "itkFDFImageIOFactory.h" #include "itkCreateObjectFunction.h" @@ -25,24 +26,19 @@ namespace itk { FDFImageIOFactory::FDFImageIOFactory() { - this->RegisterOverride("itkImageIOBase", - "itkFDFImageIO", - "FDF Image IO", - 1, - CreateObjectFunction::New()); + this->RegisterOverride( + "itkImageIOBase", "itkFDFImageIO", "FDF Image IO", true, CreateObjectFunction::New()); } -FDFImageIOFactory::~FDFImageIOFactory() -{ -} +FDFImageIOFactory::~FDFImageIOFactory() = default; -const char* -FDFImageIOFactory::GetITKSourceVersion(void) const +const char * +FDFImageIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } -const char* +const char * FDFImageIOFactory::GetDescription() const { return "FDF ImageIO Factory, allows the loading of Varian FDF images into Insight"; @@ -54,13 +50,14 @@ FDFImageIOFactory::GetDescription() const static bool FDFImageIOFactoryHasBeenRegistered; -void IOFDF_EXPORT FDFImageIOFactoryRegister__Private(void) +void IOFDF_EXPORT + FDFImageIOFactoryRegister__Private() { - if( ! FDFImageIOFactoryHasBeenRegistered ) - { + if (!FDFImageIOFactoryHasBeenRegistered) + { FDFImageIOFactoryHasBeenRegistered = true; FDFImageIOFactory::RegisterOneFactory(); - } + } } diff --git a/test/itkFDFImageIOTest.cxx b/test/itkFDFImageIOTest.cxx index 8f9447a..50cb957 100644 --- a/test/itkFDFImageIOTest.cxx +++ b/test/itkFDFImageIOTest.cxx @@ -1,12 +1,12 @@ /*========================================================================= * - * Copyright Insight Software Consortium + * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0.txt + * https://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,41 +22,40 @@ #include "itkImage.h" -int itkFDFImageIOTest( int argc, char * argv[] ) +int +itkFDFImageIOTest(int argc, char * argv[]) { - if(argc < 3) - { + if (argc < 3) + { std::cerr << "Usage: itkFDFImageIO ImageType; - typedef itk::ImageFileReader< ImageType > ReaderType; + using ImageType = itk::Image; + using ReaderType = itk::ImageFileReader; // Register FDF Factory itk::FDFImageIOFactory::RegisterOneFactory(); ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName( argv[2] ); + reader->SetFileName(argv[2]); try - { + { reader->Update(); - } - catch( itk::ExceptionObject & exp ) - { + } + catch (itk::ExceptionObject & exp) + { std::cerr << "Exception caught" << std::endl; std::cerr << exp << std::endl; return EXIT_FAILURE; - } + } ImageType::Pointer im = reader->GetOutput(); - std::cerr << im->GetDirection() << std::endl - << im->GetOrigin() << std::endl - << im->GetSpacing() << std::endl; + std::cerr << im->GetDirection() << std::endl << im->GetOrigin() << std::endl << im->GetSpacing() << std::endl; return EXIT_SUCCESS; }