# Can I use self-defined cost function for optimization in SimpleITK?

**URL:** <https://discourse.itk.org/t/can-i-use-self-defined-cost-function-for-optimization-in-simpleitk/3575>\
**Category:** Algorithms\
**Tags:** simpleitk, registration\
**Created:** [October 26, 2020, 3:18pm UTC](https://discourse.itk.org/t/can-i-use-self-defined-cost-function-for-optimization-in-simpleitk/3575 "2020-10-26T15:18:38Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dada](https://discourse.itk.org/letter_avatar_proxy/v4/letter/d/9d8465/32.png) [@dada](https://discourse.itk.org/u/dada)\
**Post date:** [October 26, 2020, 3:18pm UTC](https://discourse.itk.org/t/can-i-use-self-defined-cost-function-for-optimization-in-simpleitk/3575/1 "2020-10-26T15:18:38Z")

</div>

Hello,

I am doing B-Spline registration, I use Sum of Squared Differences (SSD) as the cost and found images were deformed too much. I would like to add some regularization in the cost function to constrain image deformation. Can I use self-defined cost function for optimization in SimpleITK? Do I need to make the changes in the C++ ITK library then compile them? (e.g. write a class for customized cost in C++ …). Many thanks.

---

<div class="post-metadata">

**Author:** ![zivy](https://discourse.itk.org/user_avatar/discourse.itk.org/zivy/32/1726_2.png) [@zivy](https://discourse.itk.org/u/zivy)\
**Post date:** [October 26, 2020, 4:59pm UTC](https://discourse.itk.org/t/can-i-use-self-defined-cost-function-for-optimization-in-simpleitk/3575/2 "2020-10-26T16:59:57Z")

</div>

Hello @dada,

Unfortunately, you cannot add cost functions directly into SimpleITK. The process is as you described, add into ITK C++ and then wrap into SimpleITK. The best way to do this is to use the closest existing functionality. If you are not familiar with ITK development this may be a significant effort.

Possibly consider using other tools that provide the functionality you want, take a look at the [ANTs](https://github.com/ANTsX) or [Elastix](https://github.com/SuperElastix) family of tools .
