Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MRG] Stage 1 of new pixels module #1985

Merged
merged 9 commits into from
Jan 15, 2024

Conversation

scaramallion
Copy link
Member

@scaramallion scaramallion commented Dec 27, 2023

Describe the changes

Notes:

  • I may not keep the pixels.enums module.
  • Also not sure if I'll keep the DecoderRunner.test_for() method
  • I'll probably end up chopping down the **kwargs section of the docstrings on as_array()/iter_array()/as_buffer()/iter_buffer() and referencing the corresponding decoder guides document page instead.
  • I thought it'd be more convenient to split out the pixel data related tests to their own sub-folder (pytest tests/pixels ftw), but I can lump them back in with all the rest

Future work

Stage 2

  • Add the remaining plugins (gdcm, pillow, pylibjpeg, jpeg_ls)
  • This probably requires an update to pylibjpeg + plugins

Stage 3

  • Add support for BinaryIO as a src for as_array(), iter_array(), as_buffer() and iter_buffer()
  • Add a pair of functions to access the pixel data as an ndarray without having to go through dcmread()
    • func(src: str | PathLike[str] | BinaryIO, ...) -> numpy.ndarray: and a corresponding frame iterator
    • pxlread()? pixel_array()? read_array()? Haven't thought of any really good names for it. I'd like some symmetry with dcmread() though.
  • Add tutorial + docs

And at some point

  • Move encoders module under pixels
  • Move pixel utils to pixels module
  • Deprecate pixel_data_handlers, switch Dataset pixel array methods over

Tasks

  • Unit tests added that reproduce the issue or prove feature is working
  • Fix or feature added
  • Code typed and mypy shows no errors
  • Documentation updated (if relevant)
  • Unit tests passing and overall coverage the same or better

Copy link

codecov bot commented Dec 27, 2023

Codecov Report

All modified and coverable lines are covered by tests ✅

Comparison is base (69c7abc) 97.97% compared to head (ed6103e) 98.10%.
Report is 6 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1985      +/-   ##
==========================================
+ Coverage   97.97%   98.10%   +0.12%     
==========================================
  Files          63       67       +4     
  Lines       10968    11710     +742     
==========================================
+ Hits        10746    11488     +742     
  Misses        222      222              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@scaramallion scaramallion changed the title Stage 1 of new pixels module [MRG] Stage 1 of new pixels module Dec 30, 2023
@scaramallion scaramallion marked this pull request as ready for review December 30, 2023 21:48
Comment on lines 684 to 693
if self.photometric_interpretation == PI.YBR_FULL_422:
# PS 3.3, Annex C.7.6.3
ybr_length = expected / 2 * 3 + expected / 2 * 3 % 2
if actual >= ybr_length:
raise ValueError(
"The number of bytes of pixel data is a third larger "
f"than expected ({actual} vs {expected} bytes) which "
"indicates the set photometric interpretation "
"'YBR_FULL_422' is incorrect"
)
Copy link
Member Author

Choose a reason for hiding this comment

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

Related to #1133, would you like a more detailed message @darcymason ?

Comment on lines +846 to +855
def as_array(
self,
src: Buffer | Dataset,
*,
index: int | None = None,
validate: bool = True,
raw: bool = False,
decoding_plugin: str = "",
**kwargs: DecodeOptions,
) -> "np.ndarray":
Copy link
Member Author

Choose a reason for hiding this comment

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

The index parameter here and the indices parameter for iter_array() are related to #1263 and #1243

Comment on lines +968 to +971
* `view_only`: :class:`bool` - if ``True`` then make a best effort
attempt to return an :class:`~numpy.ndarray` that's a `view
<https://numpy.org/doc/stable/user/basics.copies.html#view>`_
on the original buffer (default ``False``).
Copy link
Member Author

Choose a reason for hiding this comment

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

view_only parameter and behaviour is related to #746

Comment on lines +419 to +424
if force_ybr:
arr = convert_color_space(arr, PI.RGB, PI.YBR_FULL)
self.set_option("photometric_interpretation", PI.YBR_FULL)
elif to_rgb:
arr = convert_color_space(arr, PI.YBR_FULL, PI.RGB)
self.set_option("photometric_interpretation", PI.RGB)
Copy link
Member Author

Choose a reason for hiding this comment

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

Related to #1781 (and others), converts YBR to RGB by default

Comment on lines +1066 to +1079
# Check to see if we have any more frames available
# Should only apply to JPEG transfer syntaxes
excess = []
for frame in frame_generator:
if len(frame) == bytes_per_frame:
excess.append(np.frombuffer(frame, dtype))
runner.set_option("number_of_frames", runner.number_of_frames + 1)

if excess:
warn_and_log(
"More frames have been found in the encapsulated pixel data "
"than expected from the supplied number of frames"
)
arr = np.concatenate([arr, *excess])
Copy link
Member Author

Choose a reason for hiding this comment

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

Include any excess frames, related to #1666

Copy link
Member

@mrbean-bremen mrbean-bremen left a comment

Choose a reason for hiding this comment

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

@scaramallion - again a lot of new code, and I'm slower with reviewing than you have been with writing... I will finish it another day, but will post the few comments and questions I had so far.
I shall add that I like this refactoring, awesome work as usual!

doc/guides/decoding/decoder_plugins.rst Outdated Show resolved Hide resolved
decoding plugins.

When possible it's recommended that the decoding function return the decoded
pixel data as a :class:`bytearray` to minimise later memory usage.
Copy link
Member

Choose a reason for hiding this comment

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

minimize

Copy link
Member Author

Choose a reason for hiding this comment

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

Fixed

doc/guides/decoding/decoder_plugins.rst Outdated Show resolved Hide resolved
src/pydicom/pixels/decoders/base.py Show resolved Hide resolved
src/pydicom/pixels/decoders/base.py Outdated Show resolved Hide resolved
src/pydicom/pixels/decoders/base.py Show resolved Hide resolved
actual = len(self._src)

if self.transfer_syntax.is_encapsulated:
if actual == expected:
Copy link
Member

Choose a reason for hiding this comment

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

Shouldn't you add the padding before you make this check?

Copy link
Member Author

Choose a reason for hiding this comment

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

Ah, true. Will fix

Copy link
Member Author

Choose a reason for hiding this comment

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

Done

src/pydicom/pixels/decoders/base.py Outdated Show resolved Hide resolved
src/pydicom/pixels/decoders/base.py Show resolved Hide resolved
Copy link
Member

@mrbean-bremen mrbean-bremen left a comment

Choose a reason for hiding this comment

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

As usual, I only skimmed the tests, not checking any numbers - I trust that you to test the correct ones. Sorry for the long delay, I had kind of a stack overflow in my personal backlog...

@scaramallion
Copy link
Member Author

No problem, thanks for looking at it

@darcymason
Copy link
Member

Hey, I somehow missed this being MRG, haven't been checking in much lately because, well, Christmas etc., and I had a terrible cold. I'll check it out in the next couple of days.

@scaramallion
Copy link
Member Author

No worries

Copy link
Member

@darcymason darcymason left a comment

Choose a reason for hiding this comment

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

Did about half of a review -- lots here! Just a few comments so far...

| | Key | Value |
+==========================+=======================+================================================+
|:attr:`RLELosslessDecoder`| ``rle_segment_order`` | ``"<"`` for big endian segment order (default) |
| | | or ``">"`` for little endian segment order |
Copy link
Member

Choose a reason for hiding this comment

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

Are the characters correct? ">" is big endian in Python struct module.

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah, it should be the other way around. Fixed

doc/guides/decoding/decoder_plugins.rst Show resolved Hide resolved
src/pydicom/pixels/decoders/base.py Show resolved Hide resolved
src/pydicom/pixels/decoders/base.py Show resolved Hide resolved
src/pydicom/pixels/decoders/base.py Show resolved Hide resolved
Copy link
Member

@darcymason darcymason left a comment

Choose a reason for hiding this comment

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

So finally got through at least quickly going over most of the code, although with limited review of the tests, similar to @mrbean-bremen said.

This is quite the epic piece of work - it puts the pixel handling in a much better structure for future additions/changes.


8-bit pixel data encoded as **OW** using Explicit VR Big Endian will
be yielded as-is and may need byte-swapping. To facilitate this
an extra byte before the expected start (for and odd `index`) or after
Copy link
Member

Choose a reason for hiding this comment

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

for an_ index

Copy link
Member Author

Choose a reason for hiding this comment

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

Fixed, here and in as_buffer

.. warning::

This method is not thread-safe.

Copy link
Member

Choose a reason for hiding this comment

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

I'm thinking it could be thread-safe if the dict.pop() was used again? And I guess a missing label would have to be ignored.

Not that pydicom overall has actually tried to be thread-safe in any way, so I don't think it is worth worrying about.

Copy link
Member Author

Choose a reason for hiding this comment

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

Mostly I'm concerned about there being a single instance of the specific UID decoder, so any changes to it in one thread will propagate to the other threads. I've been trying to make everything threading/multiprocessing friendly (hopefully) since going off our citations in published papers a significant use case for our pixel data handling is machine learning/image processing pipelines.

I think this affects the encoder implementation too, I'm planning on refactoring it when I add in support for encoding J2K.

@scaramallion scaramallion merged commit 800635f into pydicom:main Jan 15, 2024
9 checks passed
@scaramallion scaramallion deleted the dev-pixel-decoding branch January 15, 2024 23:20
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.

None yet

3 participants