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

Optimization of function for converting mask images to uint8 type #426

Open
wants to merge 7 commits into
base: Main
Choose a base branch
from

Conversation

lcolok
Copy link
Contributor

@lcolok lcolok commented Jan 11, 2024

Dear friend,

Thank you so much for your continuous contributions.

During recent usage, I found some potential improvements when converting mask images to uint8 type. I've adapted the original (mask*255.0).astype(np.uint8) operation into a new function: optimized_mask_to_uint8(mask). This function has the following processing logic:

  1. Checks whether the input is a numpy array, and if not, an error will be escalated.
  2. Adapts the input mask to ensure all values are within the range [0,1]. If any values are out of this range, a prompt will be displayed.
  3. If the mask is of floating-point type, it's converted to np.float32 to prevent overflow when being multiplied by 255.
  4. Converts the adapted mask to uint8 type.
  5. If the mask is 3D and the first dimension is 1, dimensional reduction is performed.

This is my small improvement to the function. I hope we can discuss it together to see if it is suitable for adoption. I really appreciate your past efforts and look forward to further collaboration!

Best regards


# If mask is floating-point type, convert it to np.float32 to avoid overflow
if mask_clamped.dtype.kind == 'f':
mask_clamped = mask_clamped.astype(np.float32)
Copy link
Owner

Choose a reason for hiding this comment

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

Since it has already been clamped between 0 and 1, is there a need to consider overflow?

height, width, _ = image.shape
# Create an empty mask with the shape (N, H, W, 1), where N is the batch size, set to 1
mask = torch.zeros(
(1, height, width, 1), dtype=torch.float32, device=mask_working_device
Copy link
Owner

Choose a reason for hiding this comment

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

What is the reason for making the mask 4-dim here? The masks used in ComfyUI are 3-dim masks (b, h, w)

Copy link
Owner

Choose a reason for hiding this comment

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

The review was pending due to my mistake.

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.

2 participants