Skip to content

fix: always convert frames to RGB for the NSFW frame check - #1972

Open
shreyanshj10 wants to merge 2 commits into
hacksider:mainfrom
shreyanshj10:fix/issue-1963-nsfw-channel-order
Open

shreyanshj10 wants to merge 2 commits into
hacksider:mainfrom
shreyanshj10:fix/issue-1963-nsfw-channel-order

Conversation

@shreyanshj10

@shreyanshj10 shreyanshj10 commented Nov 3, 2026 •

Copy link
Copy Markdown

Problem

With Color Correction off — the default — the NSFW filter's frame check runs on frames whose red and blue channels are swapped.

predict_frame converted BGR to RGB only inside the color-correction branch (modules/predicter.py#L28-L33):

def predict_frame(target_frame: Frame) -> bool:
    # Convert the frame to RGB before processing if color correction is enabled
    if modules.globals.color_correction:
        target_frame = gpu_cvt_color(target_frame, cv2.COLOR_BGR2RGB)

    image = Image.fromarray(target_frame)
    image = opennsfw2.preprocess_image(image, opennsfw2.Preprocessing.YAHOO)

Image.fromarray on a 3-channel uint8 array produces mode RGB and reinterprets the bytes as-is, so with the toggle off the model is told every blue pixel is red and every red pixel is blue. No error, no crash — just quietly degraded probabilities on the one path a user turns the filter on for.

Root cause

The channel order opennsfw2 needs has nothing to do with the color-correction toggle, and the two were only ever connected by accident. The conversion went in unconditionally in 79c6615 ("use mjpeg and convert bgr to rgb"). Thirteen minutes later c91ab8b added the "Fix Blueish Cam" toggle and wrapped every BGR2RGB call site in the new flag — including this one, which is not a display path and does not belong to that feature.

Unconditional is the correct order for two independent reasons:

  • opennsfw2.preprocess_image expects an RGB PIL.Image. It does the flip to the model's BGR input itself (image = image[:, :, ::-1]) before subtracting the VGG channel means, so handing it BGR cancels that flip out.
  • It is what the rest of the codebase already does. Every other handoff from a pipeline frame to PIL or Qt converts unconditionally — _bgr_to_qpixmap (modules/ui.py#L275), and the two Image.fromarray(gpu_cvt_color(...)) sites at #L305 and #L1435. Frames in the pipeline are BGR; the predictor was the only place treating that as conditional.

With Color Correction on, the conversion already ran, so that path's behaviour is unchanged by this PR.

The only ndarray caller is the still-preview check at modules/ui.py#L1115; predict_image and predict_video use opennsfw2's own loaders and were never affected.

Changes

  • predict_frame always converts BGR to RGB, inline, matching the Image.fromarray(gpu_cvt_color(...)) form used elsewhere in the codebase.
  • Dropped the now-unused import modules.globals from modules/predicter.py.

Three lines of production code; no behaviour change anywhere else.

Tests

Added tests/test_predicter_channel_order.py. It pushes a pure-blue OpenCV frame — (B, G, R) = (255, 0, 0) — through predict_frame and asserts the array that reaches preprocess_image is [0, 0, 255]. opennsfw2 is stubbed, so no model is built or downloaded and the test is fast.

The Color-Correction-off case is the regression test: it fails with [255, 0, 0] before this change and passes after. The Color-Correction-on case passes either way and is there to pin that order down too, so the condition cannot come back inverted.

ruff check and the compileall check are clean.

Checklist status

Verified: the new regression test, ruff, and the compile check.

Not exercised: the full CONTRIBUTING checklist (enhancer on/off, map faces, camera listing, 15-minute soak). This change touches only the NSFW check's input conversion, not the swap or render pipeline, so FPS and boot time are unaffected — but I have not run the soak.

Branch

CONTRIBUTING asks for premain, but there is no premain branch on the remote, and recent merges (#1959, #1942, #1938) all landed on main, so this targets main. Happy to retarget if there is a branch I should be using instead.

Fixes #1963

Summary by Sourcery

Correct the NSFW frame-check input color order independently of the color-correction setting.

Bug Fixes:

  • Ensure NSFW frame checks always receive correctly ordered RGB data, including when color correction is disabled.

Tests:

  • Add regression coverage verifying RGB channel ordering with color correction both disabled and enabled.

opennsfw2.preprocess_image expects an RGB PIL image, but predict_frame
converted BGR to RGB only when the color-correction toggle was on. With
the toggle off, which is the default, the model received frames with red
and blue swapped. The conversion was unconditional when it was first
added and only became conditional when the Fix Blueish Cam toggle was
threaded through every BGR2RGB call site.

Add a regression test that asserts the channel order reaching
preprocess_image, with the model stubbed.
@sourcery-ai

sourcery-ai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Remove the color-correction dependency and always convert BGR frames to RGB before passing them to the NSFW preprocessor.

  • modules/predicter.py L18 (removed lines), L28-30

Tests

Add stubbed regression tests verifying that blue frames reach the NSFW preprocessor with RGB channel order regardless of the color-correction setting.

  • tests/test_predicter_channel_order.py L1-91

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

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.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="tests/test_predicter_channel_order.py" line_range="55-56" />
<code_context>
+            added.append(name)
+    # opennsfw2 must be ours even if the real package is installed, so that
+    # no model is ever built.
+    sys.modules["opennsfw2"] = stubs["opennsfw2"]
+    added.append("opennsfw2")
+
+    sys.modules.pop("modules.predicter", None)
</code_context>
<issue_to_address>
**Later imports see altered module state**

When the test process has already imported `opennsfw2` or `modules.predicter`, `_load_predicter` replaces or removes cached modules, and `_restore` pops them instead of restoring their prior values, so later imports see missing modules or duplicate module instances with reset module-level state and test results depend on execution order.

Save the prior `sys.modules` entries and restore them during cleanup.

Also at `tests/test_predicter_channel_order.py:58-81`.
</issue_to_address>

Linked issues

#1963 NSFW preview check receives red/blue-swapped frames when Color Correction is off (default) - predict_frame converts BGR to RGB only inside the color-correction branch · 1 of 1 met

# Requirement Status Notes
1 Always convert BGR frames to RGB before the NSFW frame check, regardless of Color Correction. ✅ Met predict_frame now converts unconditionally before creating the PIL image; the regression tests check the channel order with Color Correction both off and on.

Sourcery assessment

Approval pending. 1 finding to address first.

Blocking findings: tests/test_predicter_channel_order.py:56


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread tests/test_predicter_channel_order.py Resolved
The stubs were installed by hand and torn down by popping the names, so a
pre-existing opennsfw2 or modules.predicter was deleted rather than put
back and later imports in the same process saw a missing or duplicate
module. Use patch.dict, as tests/test_core_map_faces_fallback.py already
does, which restores sys.modules exactly.

@sourcery-ai sourcery-ai Bot left a comment

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.

Sourcery assessment

Approved.

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

Labels

None yet

Projects

None yet

1 participant