# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python [default]
#     language: python
#     name: python3
# ---

# +
import numpy as np
import skimage as ski

from scipy.signal import find_peaks, butter, filtfilt
import matplotlib.pyplot as plt

# +
# Load the sample image

I = ski.io.imread("track.jpg")
# -

plt.imshow(I)

# +
# Print the image dimensions in pixels

I.shape
# -

# Conversion to gray
Ibw = ski.color.rgb2gray(I)

# +
# Since the image has a black line on a white background 
# we invert the image by substracting it from its maximum value.
# We also select a smaller region of interest

ROI = Ibw.max() - Ibw[1350:1400, 1000:3000]

# +
# Print the minimum and the maximum values

ROI.min(), ROI.max()

# +
# Select the 25th row in the image for line detection
L = ROI[25]

# Plot the intensities across this row
plt.plot(L)
# -

# Due to the noise in the image the algorithm finds many peaks heigher than 0.5
find_peaks(L, height=0.5)

# +
# To filter the noise in the image we use a 3rd order Butterworth filter

# Wn = 0.02, the cut-off frequency, acceptable values are from 0 to 1
b, a = butter(3, 0.02)
# -

# Filter the selected row in the image using the above filter coefficients a, b
Lf = filtfilt(b, a, L)

# +
# Plot the pixel intensities along the selected row
plt.plot(L, label="raw")
plt.plot(Lf, label="filtered")

plt.legend()
# -

# Find the two peaks in the filtered data
find_peaks(Lf, height=0.5)

# +
# %%timeit

## Estimate the run time of the line detection algorithm

# Select the 25th row in the image for line detection
L = ROI[25]

# To filter the noise in the image we use a 3rd order Butterworth filter
b, a = butter(3, 0.02)

# Smooth the transitions so we can detect the peaks 
Lf = filtfilt(b, a, L)

# Find peaks which are higher than 0.5
p = find_peaks(Lf, height=0.5)
# -



StarcoderdataJupyterScriptsDedupFiltered