Skip to content

Instantly share code, notes, and snippets.

@dantrim
Last active February 1, 2022 18:57
Show Gist options
  • Save dantrim/5c2a3c7c9a337882a32b1efff2f4de17 to your computer and use it in GitHub Desktop.
Save dantrim/5c2a3c7c9a337882a32b1efff2f4de17 to your computer and use it in GitHub Desktop.
Fitting a 2D pixel matrix over "time" steps (or some other independent quantity)
import numpy as np
# create dummy two-dimensional (3x3) data that represents
# per-pixel measured quantities taken at various "time steps"
# (say, 4 of such steps):
pixel_maps = np.asarray([
[
[0, 0, 0],
[2, 2, 2],
[3, 3, 3],
],
[
[1, 1, 1],
[2, 2, 2],
[2, 2, 2],
],
[
[2, 2, 2],
[2, 2, 2],
[1, 1, 1],
],
[
[3, 3, 3],
[2, 2, 2],
[0, 0, 0],
]
])
pixel_maps_for_fit = np.stack(pixel_maps, axis = 0)
# associate with each of the 2D pixel maps a corresponding
# "time" step value (the independent variable over which
# each pixel's data will fit)
time_steps = np.asarray([0, 0.5, 1, 1.5])
# reshape the pixel map data into a form that polyfit can take,
# see: https://numpy.org/doc/stable/reference/generated/numpy.polyfit.html
# summary:
# y-coordinates of the sample points can contain several data sets of sample
# points sharing the same x-coordinates if the data is re-shaped as a 2D-array
# that contains one dataset per column
pixel_maps_for_fit = pixel_maps_for_fit.reshape(len(pixel_maps_for_fit), -1)
# perform the linear regression over each time step for each individual "pixel"
slopes, intercepts = np.polyfit(time_steps, pixel_maps_for_fit, deg = 1)
print(slopes)
# prints:
# [
# 4.00000000e+00 4.00000000e+00 4.00000000e+00
# -1.13194253e-15 -1.13194253e-15 -1.13194253e-15
# -4.00000000e+00 -4.00000000e+00 -4.00000000e+00
# ]
print(intercepts)
# prints:
# [
# 1.12255857e-16 1.12255857e-16 1.12255857e-16
# 2.00000000e+00 2.00000000e+00 2.00000000e+00
# 3.00000000e+00 3.00000000e+00 3.00000000e+00
# ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment