Skip to content

Instantly share code, notes, and snippets.

@AdroitAnandAI
Last active August 12, 2021 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdroitAnandAI/11821025df50344ac9832e56cb225ee3 to your computer and use it in GitHub Desktop.
Save AdroitAnandAI/11821025df50344ac9832e56cb225ee3 to your computer and use it in GitHub Desktop.
Curve Fitting to identify rise or fall of signal
# Code to fit the inverse sigmoid curve to tail end of signal
def sigmoid(x, L ,x0, k, b):
y = L / (1 + np.exp(k*(x-x0)))+b
return (y)
def isCurveSigmoid(pixelCounts, count):
try:
xIndex = len(pixelCounts)
p0 = [max(pixelCounts), np.median(xIndex),1,min(pixelCounts)] # this is an mandatory initial guess
popt, pcov = curve_fit(sigmoid, list(range(xIndex)), pixelCounts, p0, method='lm', maxfev=5000)
yVals = sigmoid(list(range(xIndex)), *popt)
# May have to check for a value much less than Median to avoid false positives.
if np.median(yVals[:10]) - np.median(yVals[-10:]) > 15:
print('Event Triggered...')
return True
except Exception as err:
print(traceback.format_exc())
return False
def findCurveFit(eye, image, pixelCount, frame_count, numFrames = 50):
triggerEvent = False
if (len(image) == 0):
return pixelCount, False
# Convert to gray scale as histogram works well on 256 values.
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# calculate frequency of pixels in range 0-255
histg = cv2.calcHist([gray],[0],None,[256],[0,256])
# hack to know whether eye is closed or not.
# more spread of pixels in a histogram signifies an opened eye
activePixels = np.count_nonzero(histg)
pixelCount.append(activePixels)
if len(pixelCount) > numFrames and frame_count % 15 == 0:
if isCurveSigmoid(pixelCount[-numFrames+10:], len(pixelCount)):
print('Event Triggered...')
pixelCount.clear()
plt.clf()
triggerEvent = True
return pixelCount, triggerEvent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment