Skip to content

优化qrcode: improve QR code parsing accuracy and speed#22

Draft
Copilot wants to merge 2 commits intomainfrom
copilot/optimize-qrcode-decoding
Draft

优化qrcode: improve QR code parsing accuracy and speed#22
Copilot wants to merge 2 commits intomainfrom
copilot/optimize-qrcode-decoding

Conversation

Copy link
Copy Markdown

Copilot AI commented Mar 31, 2026

QR code parsing had two core problems: a scoring function that gave wrong signal to the perspective matrix optimizer, and an exhaustive matrix search that made ~12,750 expensive evaluations per decode regardless of whether they helped.

Accuracy

Fix scoreArea scoring logic — the previous implementation rewarded black pixels in white areas and never scored black pixels in black areas, making the score a poor proxy for matrix correctness:

// Before: only white areas ever scored; black areas always returned 0
if qr.greyPixels[index] != 0 {
    if !isBlack { score++ }  // black pixel in white area — wrong
} else {
    if !isBlack { score++ }  // white pixel in white area — correct
}

// After: reward any pixel that matches its expected color
pixelIsBlack := qr.greyPixels[index] != 0
if pixelIsBlack == isBlack {
    score++
}

Speed

Replace autoAdjustmentMatrix exhaustive search with coordinate descent — the old algorithm tried all 255 index-combination × 50 scale steps against a frozen baseline matrix (improvements never compounded). Replaced with multi-scale coordinate descent (scales: 0.5 → 0.005) that updates the base on every improvement, converging in ~100 evaluations vs 12,750. The 256-row autoAdjustmentMatrixChangeIndex static table is removed.

Convert fillRegion recursive flood fill to iterative — eliminates the hard depth cap of 1024 that silently dropped pixels in large regions; only pushes the start of each new run onto the stack rather than every pixel.

Pre-allocate rowAverage in binarization — single allocation reused across all rows instead of one allocation per row.

Benchmark (BenchmarkTestNX)

Before After
Time/op 99.6 ms 69.2 ms (−30%)
Memory/op 118 MB 100 MB (−15%)
Allocs/op 19,591 5,252 (−73%)

Safety

Added len(result) >= 3 guard before UTF-8 BOM detection in read8BitByteData to prevent a potential index-out-of-range panic on short payloads.

Copilot AI linked an issue Mar 31, 2026 that may be closed by this pull request
Copilot AI changed the title [WIP] Optimize QR code decoding algorithm for accuracy and speed 优化qrcode: improve QR code parsing accuracy and speed Mar 31, 2026
Copilot AI requested a review from echosoar March 31, 2026 16:12
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.

优化qrcode

2 participants