Skip to content

ENH: structural_similarity: n-dimensional and multichannel support - #1511

Merged
stefanv merged 14 commits into
scikit-image:masterfrom
grlee77:ssim_ndim
May 20, 2015
Merged

stefanv merged 14 commits into
scikit-image:masterfrom
grlee77:ssim_ndim

Conversation

@grlee77

@grlee77 grlee77 commented May 14, 2015

Copy link
Copy Markdown
Contributor

This pull requests implements the following enhancements / bug fix to the structural_similarity metric:

  • extend the structural_similarity metric to n-dimensional arrays and multichannel images
  • modify the implementation so that the results exactly match the reference implementation of the algorithm's original authors if the appropriate flags are set.
  • address possibly erroneous computation of the gradient

The existing implementation in scikit-image differs slightly from the one in the publication of Wang. et. al. referenced in the docstring. The difference is primarily due to using a constant weighting rather than an 11-tap FIR Gaussian filter for the sliding window. The default constant used for covariance normalization was also slightly different. I added a note to the docstring informing the user of the settings needed to match this reference implementation, but by default left the behaviour so that the result will match prior versions of scikit-image. I think it is important to be able to exactly match the reference implementation for comparison to results in many existing publications in the literature.

The only thing in this pull request that is not fully backwards compatible is the computation of the gradient. I do not personally use the gradient, but the existing implementation gave a result visually different from the result I get from code by the author of the following publication:

Avanaki, A. N. (2009). Exact global histogram specification optimized for structural similarity. Optical Review, 16, 613-621.
https://ece.uwaterloo.ca/~nnikvand/Coderep/SHINE%20TOOLBOX/SHINEtoolbox/ssim_sens.m

I am not sure of the exact source of the difference in gradient computations as the equations look nominally the same, but I suspect it is a subtle difference in the call to view_as_windows in the old implementation vs. the explicit filtering used in my n-dimensional implementation and the 2D Matlab implementation referenced above. Was anyone successfully using the gradient returned by the prior implementation in an application? I couldn't find anywhere else in the code base that it was used.

other minor points addressed are:

  • the computation speed of the scipy.ndimage based filtering used in this implementation is higher than the prior approach using view_as_windows.
  • tests were added to validate the results vs. the outputs of C and Matlab reference implementations for the 2D case
  • other algorithm constants that were previously hard coded (K1, K2) can be modified if desired via keyword arguments
  • allow the full structural similarity image to be returned if requested (via full=True), rather than just the mean value
  • allow computation of an "image content weighted" variant of structural similarity as proposed in
    Wang, Z. and Shang, X. Spatial pooling strategies for perceptual image quality assessment. Proc. IEEE Inter. Conf. Image. Proc. 2006. p. 2945-2948.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If possible, it would be best to load the usual cameraman for testing purposes and generate a pseudorandom noisy version with skimage.util.random_noise with the appropriate settings and a set seed.

To keep the package size down, we may need a rebase which omits the original commit of the noisy cameraman.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that would be a better solution. I don't know what the seed was when I originally generated that image, so I would need to recompute the Matlab and IPOL reference values hardcoded in the tests.

@JDWarner

Copy link
Copy Markdown
Contributor

Thanks for the PR, @grlee77! SSIM in nD has great potential e.g. in medical image denoising, and you've made a lot of other improvements.

The Travis error is specific to Python 3.3 and has the following traceback:

======================================================================
ERROR: skimage.measure.tests.test_structural_similarity.test_ssim_multichannel
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/travis/venv/lib/python3.3/site-packages/nose/case.py", line 198, in runTest
    self.test(*self.arg)
  File "/home/travis/build/scikit-image/scikit-image/skimage/measure/tests/test_structural_similarity.py", line 95, in test_ssim_multichannel
    S2 = ssim(Xc, Yc, win_size=3)
  File "/home/travis/build/scikit-image/scikit-image/skimage/measure/_structural_similarity.py", line 182, in structural_similarity
    ch_result = structural_similarity(X[..., ch], Y[..., ch], **args)
TypeError: structural_similarity() got multiple values for argument 'X'

======================================================================
ERROR: skimage.measure.tests.test_structural_similarity.test_ssim_multichannel_chelsea
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/travis/venv/lib/python3.3/site-packages/nose/case.py", line 198, in runTest
    self.test(*self.arg)
  File "/home/travis/build/scikit-image/scikit-image/skimage/measure/tests/test_structural_similarity.py", line 135, in test_ssim_multichannel_chelsea
    mssim = ssim(Xc, Yc)
  File "/home/travis/build/scikit-image/scikit-image/skimage/measure/_structural_similarity.py", line 182, in structural_similarity
    ch_result = structural_similarity(X[..., ch], Y[..., ch], **args)
TypeError: structural_similarity() got multiple values for argument 'X'

@grlee77

grlee77 commented May 14, 2015

Copy link
Copy Markdown
Contributor Author

anyone have a suggestion of what might be causing that error specific to Python 3.3? I currently only have 2.7 and 3.4 installed locally.

I was not sure how best to implement passing the arguments in the multichannel case where it calls the function independently for each channel. Perhaps there is a better/cleaner solution that wouldn't involve the call to locals() and would also fix the Travis build error?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Double check: can't this be done using ndimage's gaussian filter implementation?

@stefanv

stefanv commented May 14, 2015

Copy link
Copy Markdown
Member

I'm restarting the test--at least in my browser I can't scroll down to the bottom of the log for some reason.

@JDWarner

Copy link
Copy Markdown
Contributor

@stefanv - Travis terminates the interactive log display at 10k lines. The only way to see beyond that is to hit the "download log" button in the upper right to get the full log as a raw plaintext file.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stefanv here's your answer re: ndimage.gaussian_filter. =)

@grlee77 What does this mean? And is it important? I'd say it's worth deviating a bit from a reference implementation if it eliminates the need to reimplement a Gaussian filter from scratch...

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without taking a deep dive into DSP theory, the number of taps is the number of nonzero coefficients in a discrete-time difference equation. Gaussian filters are symmetric and non-causal, so they always have an odd number of taps inspecting the samples on either side and including zero. A 13-tap filter looks one index farther away from zero at every point compared to an 11-tap filter, and it will yield different results. If done correctly they both approximate an ideal Gaussian, but the 13-tap filter should be a better approximation.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JDWarner my interpretation of what you're saying is that using ndimage should give "better" results, in some DSP optimality sense? Also, does this at all interact with the size parameter? I don't understand how the number of taps can be higher than the number of samples.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this sense, as all Gaussian filter coefficients are nonzero, consider size == taps. So setting size=13 would be equivalent to ndi.gaussian_filter, but the new implementation allows this to be set arbitrarily.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In practice it may not be a big deal to just use the 13-tap filter and making a brief note about the difference. I think the result should agree to within 2-3 decimal places either way, which is typically the level of precision that ssim values are tabulated in the literature.

Here are some concrete numbers for a noisy vs. clean cameraman image:
Matlab code of Wang et. al.:
0.327314295673357
Gaussian with window size 11, gaussian_weights=True, use_sample_covariance=False
0.32731429567337322 (identical to >10 decimal places)
window size 13, gaussian_weights=True, use_sample_covariance = False
0.32785353312812454 (first few decimals the same, probably good enough)
old sckit image v0.11 implementation with the constant window of size 7
0.34192589699605191 (already differs at the second decimal)

@stefanv stefanv May 15, 2015 via email

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jni

jni commented May 15, 2015

Copy link
Copy Markdown
Member

@grlee77 as scikit-image Guardian of the Dimensions, this PR makes me very happy! I think there's a bit of cleanup/API discussion to be done here but overall, great contribution, thanks!!!

@stefanv

stefanv commented May 15, 2015

Copy link
Copy Markdown
Member

Agreed, a really nice contribution!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be a good idea to tell users to set size to an odd number. I'm not sure an even number of taps makes sense at all for a Gaussian.

@grlee77

grlee77 commented May 15, 2015

Copy link
Copy Markdown
Contributor Author

I did a rebase to remove camera_noisy.png and modified the tests to generate the values from a specific random seed.

The other suggestions have been incorporated, but there are two outstanding questions brought up above:

1.) Keep or remove the 11-tap gaussian filter implementation and instead use the 13-tap one already implemented in scipy.ndimage? see the response above for an example where the effect on precision relative to the reference implementation is discussed. I am fine either way on this.

2.) Should the number of return arguments be variable or should it always be a 3-tuple (mssim, gradient, ssim) with the values not requested set to None? The drawback here is that a tuple would break existing code where gradient=False because previously just a single number was returned in that case.

@grlee77

grlee77 commented May 15, 2015

Copy link
Copy Markdown
Contributor Author

didn't read the updates before posting the above. I will go with the existing 13-tap FIR filter from ndimage as suggested.

@grlee77

grlee77 commented May 15, 2015

Copy link
Copy Markdown
Contributor Author

scipy.ndimage.gaussian_filter is now used instead. The win_size input is no longer used for the Gaussian filtering case, because the ndimage.gaussian_filter filter chooses the window size internally to be appropriate to whatever sigma is chosen for the Gaussian (e.g. 13 when sigma=1.5).

The tests still pass after lowering the tolerance to decimal=3

Should I raise a ValueError or issue a warning if the user specifies win_size when gaussian_window=True?

@grlee77

grlee77 commented May 15, 2015

Copy link
Copy Markdown
Contributor Author

Note: I should probably remove or update the image_content_weighted option to reflect the final version that was published in the journal article below as opposed to the conference preceding cited as reference [3] of the docstring.

Z. Wang and Q. Li. Information Content Weighting for Perceptual Image Quality Assessment. IEEE Trans. Image Process. 2011; 20(5):1185-1198

@stefanv

stefanv commented May 15, 2015 via email

Copy link
Copy Markdown
Member

@stefanv

stefanv commented May 15, 2015 via email

Copy link
Copy Markdown
Member

@grlee77

grlee77 commented May 16, 2015

Copy link
Copy Markdown
Contributor Author

In regards to the Wang. et. al. 2011 paper in my previous comment, that method is a bit more involved than the simpler equation from the abstract that was implemented here. To implement it, I would need to also convert various other parts of skimage (namely skimage.transforms.pyramid_laplace) to have n-dimensional support as well. That should be doable, but is probably out of the scope of the current pull request.

Instead I will just remove that option, because it doesn't seem very representative of their final published solution and I don't think it is widely used.

@stefanv

stefanv commented May 16, 2015 via email

Copy link
Copy Markdown
Member

@jni

jni commented May 16, 2015

Copy link
Copy Markdown
Member

@grlee77 ndimage.gaussian_filter has a truncate kwarg, does that not control the size of the filter?

As to the return values, you are right that it's an API-breaking change. In fact, even the deprecation path is tricky. I would say leave it optional for now and we can raise an issue to fix the API.

@JDWarner

Copy link
Copy Markdown
Contributor

@jni It sort of can, but doesn't work like you'd think. This example on StackOverflow explains it well with examples. Essentially the truncate kwarg works in conjunction with sigma to determine how many taps the filter should have, but setting either in isolation won't do what you want.

@jni

jni commented May 16, 2015

Copy link
Copy Markdown
Member

@JDWarner that's actually exactly how I thought it would work. =) So if we want a 13 or 11 tap filter we can just determine the correct truncate parameter value for ndimage.gaussian_filter based on the supplied sigma value?

@grlee77

grlee77 commented May 16, 2015

Copy link
Copy Markdown
Contributor Author

@jni. Thanks! I verified that if I set truncate=3.5 instead of the default 4.0, the filter is size 11x11 when sigma=1.5.
I verify the size by just filtering an impulse function:

a = np.zeros((16, 16))
a[8, 8] = 1.0
a_filt = ndimage.gaussian_filter(a, sigma=1.5, truncate=3.5)

This gives an 11x11 non-zero region as desired.

edit: verified that the test result now agrees with the reference implementation to several decimals of precision

@grlee77

grlee77 commented May 16, 2015

Copy link
Copy Markdown
Contributor Author

Apparently the truncate argument to gaussian_filter was added in scipy v14.0, so one of the Travis tests failed

@jni

jni commented May 16, 2015

Copy link
Copy Markdown
Member

Gaaaaah I was afraid of that. =( Use the default filter then? My reading of the previous discussion is that it works just as well, and it saves a chunk of extra code to maintain.

@grlee77

grlee77 commented May 18, 2015

Copy link
Copy Markdown
Contributor Author

@jni would it be better to leave it out or to put a version check with something like the following?

from .._shared import version_requirements
scipy_version = version_requirements.get_module_version('scipy')
    # sigma = 1.5, truncate=3.5 to match 11-tap filter in Wang et. al. 2004
    filter_func = gaussian_filter
    if scipy_version >= '0.14':
        filter_args = {'sigma': sigma, 'truncate': truncate}
    else:
        # truncate argument not implemented in older scipy versions
        filter_args = {'sigma': sigma}

a warning could be issued if the user explicitly passes in the truncate kwarg when it is not available and would be ignored

@jni

jni commented May 19, 2015

Copy link
Copy Markdown
Member

@grlee77 Again, from my reading of the implications of the tapness (=P) of the filter, 13-tap is actually more accurate, but doesn't exactly match some reference implementation. Is this correct?

  • if so, just go with 13-tap. The extra code complexity just isn't worth matching some arbitrary reference to arbitrary precision.
  • if not, I would rather a try/except to control for the scipy version (with a comment on the except).

Juan.

@grlee77

grlee77 commented May 19, 2015

Copy link
Copy Markdown
Contributor Author

@jni: you are correct. The main reason to prefer the 11-tap was for easier comparison to a number of already published papers using that implementation, but I think the 3-4 digits of agreement we get with the 13-tap implementation should be good enough in practice for that purpose.

@jni

jni commented May 20, 2015

Copy link
Copy Markdown
Member

Dunno wtf is wrong with Coveralls, but Travis and Appveyor are happy. @stefanv this is ready to merge imho. I want to deprecate the multi-return API but I think that should be left to a separate issue/PR.

stefanv added a commit that referenced this pull request May 20, 2015
ENH: structural_similarity: n-dimensional and multichannel support
@stefanv
stefanv merged commit 07f95e4 into scikit-image:master May 20, 2015
@stefanv

stefanv commented May 20, 2015

Copy link
Copy Markdown
Member

Awesome, thanks @grlee77 !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants