Skip to content

Commit 159867a

Browse files
committed
numerical
Signed-off-by: Saurabh Misra <[email protected]>
1 parent a0650a8 commit 159867a

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

codeflash/after_numerical.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
def _equalize_cv(img: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray:
2+
histogram = cv2.calcHist([img], [0], mask, [256], (0, 256)).ravel()
3+
4+
# Find the first non-zero index with a numpy operation
5+
i = np.flatnonzero(histogram)[0] if np.any(histogram) else 255
6+
7+
total = np.sum(histogram)
8+
if histogram[i] == total:
9+
return np.full_like(img, i)
10+
11+
scale = 255.0 / (total - histogram[i])
12+
13+
# Optimize cumulative sum and scale to generate LUT
14+
cumsum_histogram = np.cumsum(histogram)
15+
lut = np.clip(((cumsum_histogram - cumsum_histogram[i]) * scale)
16+
.round(), 0, 255).astype(np.uint8)
17+
return sz_lut(img, lut, inplace=True)

codeflash/before_numerical.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def _equalize_cv(img: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray:
2+
histogram = cv2.calcHist([img], [0], mask, [256], (0, 256)).ravel()
3+
i = 0
4+
for val in histogram:
5+
if val > 0:
6+
break
7+
i += 1
8+
i = min(i, 255)
9+
10+
total = np.sum(histogram)
11+
if histogram[i] == total:
12+
return np.full_like(img, i)
13+
14+
scale = 255.0 / (total - histogram[i])
15+
_sum = 0
16+
17+
lut = np.zeros(256, dtype=np.uint8)
18+
19+
for idx in range(i + 1, len(histogram)):
20+
_sum += histogram[idx]
21+
lut[idx] = clip(round(_sum * scale), np.uint8)
22+
return sz_lut(img, lut, inplace=True)

0 commit comments

Comments
 (0)