Skip to content

Commit

Permalink
Update detect_touch.py
Browse files Browse the repository at this point in the history
  • Loading branch information
haardie authored Feb 15, 2025
1 parent 2e051ac commit ea17010
Showing 1 changed file with 34 additions and 33 deletions.
67 changes: 34 additions & 33 deletions misc/detect_touch.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,45 @@
import numpy as np
import scipy.sparse as sp
import os


def detect_touch(npz_path, window_size, threshold=10):
def detect_touch(npz_path, window_size, intensity_threshold=100):
"""
Checks whether any sliding window along the border of the matrix contains more than `threshold` nonzero values.
Checks whether any sliding window along the border of the matrix has a cumulative intensity
(sum of values) greater than `intensity_threshold`.
Parameters:
npz_path (str): Path to the .npz file containing the sparse matrix.
window_size (int): Size of the sliding window.
threshold (int): The number of nonzero elements that must be exceeded in a window to register a touch.
intensity_threshold (float): Threshold for the cumulative intensity of a patch.
Returns:
int: 1 if any sliding window along the border has more than `threshold` nonzero values, 0 otherwise.
int: 1 if any sliding window along the border exceeds the intensity threshold, 0 otherwise.
"""

mat = sp.load_npz(npz_path)
mat = mat.toarray()

mat = sp.load_npz(npz_path).toarray()
height, width = mat.shape


for c in range(width - window_size + 1):
patch = mat[:window_size, c:c + window_size]
if np.count_nonzero(patch) > threshold:
return 1

for c in range(width - window_size + 1):
patch = mat[height - window_size:, c:c + window_size]
if np.count_nonzero(patch) > threshold:
return 1

for r in range(height - window_size + 1):
patch = mat[r:r + window_size, :window_size]
if np.count_nonzero(patch) > threshold:
return 1

for r in range(height - window_size + 1):
patch = mat[r:r + window_size, width - window_size:]
if np.count_nonzero(patch) > threshold:
return 1

def get_patches(edge):

"""Yield sliding window patches from the specified edge."""

if edge == "top":
for c in range(width - window_size + 1):
yield mat[:window_size, c:c + window_size]
elif edge == "bottom":
for c in range(width - window_size + 1):
yield mat[height - window_size:, c:c + window_size]
elif edge == "left":
for r in range(height - window_size + 1):
yield mat[r:r + window_size, :window_size]
elif edge == "right":
for r in range(height - window_size + 1):
yield mat[r:r + window_size, width - window_size:]
else:
raise ValueError("Invalid edge specified.")

# Check each edge for patches with intensity greater than the threshold.
for edge in ["top", "bottom", "left", "right"]:
for patch in get_patches(edge):
intensity = np.sum(patch)
if intensity > intensity_threshold:
print(f"{edge.capitalize()} edge intensity: {intensity}")
return 1

return 0

0 comments on commit ea17010

Please sign in to comment.