Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
64b0109
autocorrelation (articles version)
GabGabG Jun 17, 2020
c02dabf
added the "fiji like" method
GabGabG Jun 17, 2020
f2e3211
modifications of the FIJI-like script
GabGabG Jun 18, 2020
7a59e46
fixed useless use of where
GabGabG Jun 18, 2020
2dfee87
Added a gaussian fit on the vertical slice
GabGabG Jun 19, 2020
8b13554
showing a "potential" FWHM
GabGabG Jun 19, 2020
0937f2d
normalized tif files (gaussian filter normalization with std dev = 75)
GabGabG Jul 8, 2020
32373f0
new file for speckle simulations
GabGabG Jul 8, 2020
4c7e3f3
new images for simulation
GabGabG Jul 8, 2020
461e86d
new file for gaussian normalization
GabGabG Jul 8, 2020
ad06e3c
small changes
GabGabG Jul 8, 2020
b8c76f7
wrong names
GabGabG Jul 9, 2020
61113a3
simplified some code
GabGabG Jul 9, 2020
5095c89
small changes
GabGabG Jul 9, 2020
0bda360
normalized tif files
GabGabG Jul 9, 2020
31eb120
new simulations with gaussian spots
GabGabG Jul 13, 2020
43cdf94
Update specklesSimulation.py
GabGabG Jul 13, 2020
fc0b70a
png is not the right format
GabGabG Jul 14, 2020
c3e68f1
new simultation methods with uniformaly distributed phases
GabGabG Jul 14, 2020
73a8417
new simulation files
GabGabG Jul 14, 2020
6e9dcf2
forgot one file in the revious commit
GabGabG Jul 14, 2020
be8e677
started using dcclab
GabGabG Jul 15, 2020
3bbbf55
moved simulations of fully developped speckles to another file
GabGabG Jul 15, 2020
21d043a
added a class for not fully developped speckles (sum of fully develop…
GabGabG Jul 15, 2020
aad0e23
Delete autocorrFIJILike.py
GabGabG Jul 24, 2020
90b39f6
minor changes
GabGabG Jul 24, 2020
cb10229
new simulated images and removal of previous simulations
GabGabG Jul 24, 2020
a9e8dcb
minor changes
GabGabG Jul 24, 2020
428d0eb
OOP approach
GabGabG Jul 27, 2020
ca3ac69
new utilitary classes started
GabGabG Jul 27, 2020
636603b
new methods for the autocorrelation
GabGabG Jul 27, 2020
6244d48
new methods to find FWHM (not tested yet)
GabGabG Jul 28, 2020
716dc9b
we now apply a median fitler
GabGabG Jul 29, 2020
4db6f12
new class for speckles caracterization
GabGabG Jul 29, 2020
499092e
update FWHM finding methods
GabGabG Jul 29, 2020
0a935a6
ajout de méthodes permettant d'ajouter du bruit
ludo4015 Jul 29, 2020
f81f623
Merge branch 'PythonAutocorr' into AutocorrLudo
ludo4015 Jul 29, 2020
4782531
added a way to change the size of the image with linear interpolation
ludo4015 Jul 29, 2020
6bc0986
updated the code for the scaling to improve performance
ludo4015 Jul 30, 2020
7ef9358
new methods, algorithms and minor changes
GabGabG Jul 30, 2020
f8a6e33
minor changes in nomenclature
GabGabG Jul 30, 2020
7cafd36
Merge branch 'PythonAutocorr' into AutocorrLudo
ludo4015 Jul 31, 2020
b71b435
only using FFT autocorrelation
GabGabG Jul 31, 2020
11c64bf
changed FWHM / HWHM methods
GabGabG Jul 31, 2020
041cb07
update to fit with previous changes
GabGabG Jul 31, 2020
bb67c06
minor removal
GabGabG Aug 3, 2020
a00e1a4
minor changes, removal of useless stuff
GabGabG Aug 3, 2020
e1a554c
Delete utils.py
GabGabG Aug 3, 2020
31e1dbd
méthodes pour ajuster l'uniformité
ludo4015 Aug 4, 2020
de81944
sigma and n values are now modifiable in the nonUniformIntensity method
ludo4015 Aug 5, 2020
deeff41
major updates
GabGabG Aug 5, 2020
3b57862
Merge branch 'PythonAutocorr' into AutocorrLudo
ludo4015 Aug 5, 2020
d02c227
minor fixes
GabGabG Aug 5, 2020
c848464
saving simulations to look at how the avg diameter is affected
ludo4015 Aug 5, 2020
d5e7933
Merge branch 'PythonAutocorr' into AutocorrLudo
ludo4015 Aug 5, 2020
5a6532b
path fix
GabGabG Aug 5, 2020
5e06e8c
Merge branch 'AutocorrLudo' into PythonAutocorr
GabGabG Aug 12, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
108 changes: 108 additions & 0 deletions SpeckleSizeCode/PythonAutocorr/autocorr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import numpy as np
import matplotlib.pyplot as plt
import tifffile
import os
from scipy.ndimage import gaussian_filter
import cv2

nb = 13
fname = rf"20190924-200ms_20mW_Ave15_Gray_10X0.4_{nb}.tif"

p = os.path.dirname(os.path.join(os.getcwd(), "..", ".."))
path = os.path.join(p, "MATLAB", fname)

prefix = "circularWithPhasesSimulations"
otherPrefix = "50sims"
path = "4pixelsCircularWithPhasesSimulations.tiff"
args = [prefix, path]
#args = [prefix, otherPrefix, path]
path = os.path.join(*args)

if path.endswith("tif") or path.endswith("tiff"):
img = tifffile.imread(path)
else:
img = cv2.imread(path)

plt.imshow(img)
plt.show()

imgDivide = gaussian_filter(img, 75)

img = img / imgDivide - np.mean(img)
plt.imshow(img)
plt.show()

fft = np.fft.fft2(img)
ifft = np.fft.ifftshift(np.fft.ifft2(np.abs(fft) ** 2)).real
ifft /= np.size(ifft)

r = (ifft - np.mean(img) ** 2) / np.var(img)
plt.imshow(r)
plt.colorbar()
plt.show()

xSlice, ySlice = r.shape[1] // 2, r.shape[0] // 2

verticalSlice = r[:, xSlice]
horizontalSlice = r[ySlice, :]


def normalize(verticalSlice, horizontalSlice):
verticalSlice = verticalSlice - np.min(verticalSlice)
verticalSlice = verticalSlice / np.max(verticalSlice)

horizontalSlice = horizontalSlice - np.min(horizontalSlice)
horizontalSlice = horizontalSlice / np.max(horizontalSlice)
return verticalSlice, horizontalSlice


plt.plot(verticalSlice)
plt.title("Autocorrelation profile (x centered)")
plt.xlabel("Vertical position y [px]")
plt.ylabel("Normalized correlation coefficient [-]")
plt.show()

plt.plot(horizontalSlice)
plt.title("Autocorrelation profile (y centered)")
plt.xlabel("Horizontal position x [px]")
plt.ylabel("Normalized correlation coefficient [-]")
plt.show()

relativeErrorHalfMax = 25

# Y FWHM
print("Y FWHM")
halfMax = 0.5
inferiorBound = halfMax - halfMax * relativeErrorHalfMax / 100
superiorBound = halfMax + halfMax * relativeErrorHalfMax / 100

# Range of values to compute FWHM
pointsForFW = np.where((verticalSlice >= inferiorBound) & (verticalSlice <= superiorBound))[0]
print(pointsForFW)
middlePoint = np.argmax(verticalSlice) # Find the middle point to separate the values at the left and at the right
left = np.mean(pointsForFW[pointsForFW < middlePoint])
right = np.mean(pointsForFW[pointsForFW > middlePoint])
print(f"left: {left}")
print(f"right: {right}")
FWHM = right - left
print("Diameter : ", FWHM)
print("Radius : ", FWHM / 2)

# X FWHM
print("= = = = = = = = = = = = = = = = = = = = = = = =")
print("X FWHM")
halfMax = 0.5
inferiorBound = halfMax - halfMax * relativeErrorHalfMax / 100
superiorBound = halfMax + halfMax * relativeErrorHalfMax / 100

# Range of values to compute FWHM
pointsForFW = np.where((horizontalSlice >= inferiorBound) & (horizontalSlice <= superiorBound))[0]
print(pointsForFW)
middlePoint = np.argmax(horizontalSlice) # Find the middle point to separate the values at the left and at the right
left = np.mean(pointsForFW[pointsForFW < middlePoint])
right = np.mean(pointsForFW[pointsForFW > middlePoint])
print(f"left: {left}")
print(f"right: {right}")
FWHM = right - left
print("Diameter : ", FWHM)
print("Radius : ", FWHM / 2)
132 changes: 132 additions & 0 deletions SpeckleSizeCode/PythonAutocorr/autocorrelation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import numpy as np
import matplotlib.pyplot as plt
import tifffile
from scipy.ndimage import gaussian_filter, median_filter
from scipy.signal import correlate2d
import cv2


class FileReader:
# FIXME: This is only until pydcclab is ok

@staticmethod
def readFile(path: str):
if path.endswith(".tif") or path.endswith(".tiff"):
pixels = tifffile.imread(path)
else:
pixels = cv2.imread(path)
return pixels.T # we want shape[0] as the width and shape[1] as the height


class Autocorrelation:
# FIXME: Use pydcclab when ok

def __init__(self, imagePath: str):
self.__image = FileReader.readFile(imagePath)
self.__original = self.image
self.__autocorrelation = None
self.__slicesObj = None

@property
def image(self):
return self.__image.copy()

@property
def autocorrelation(self):
if self.__autocorrelation is None:
return None
return self.__autocorrelation.copy()

def getSlices(self, indices: tuple = None):
if self.__slicesObj is None:
raise ValueError("Please compute the autocorrelation to access its slices.")
if indices is None:
return self.__slicesObj.middleSlices()
return self.__slicesObj.slicesAt(indices)

def computeAutocorrelation(self, gaussianFilterStdDev: float = 75, medianFilterSize: int = 3):
self._gaussianNormalization(gaussianFilterStdDev) # First, gaussian filter normalization
self._medianFilter(medianFilterSize) # Then, median filter to remove noise
self._autocorrelationWithFourierTransform() # Compute the autocorrelation

def _gaussianNormalization(self, filterStdDev: float = 75):
filteredImage = gaussian_filter(self.__image, filterStdDev)
self.__image = self.__image / filteredImage - np.mean(self.__image)

def _autocorrelationWithFourierTransform(self):
fft = np.fft.fft2(self.__image)
ifft = np.fft.ifftshift(np.fft.ifft2(np.abs(fft) ** 2)).real
ifft /= np.size(ifft)
self.__autocorrelation = (ifft - np.mean(self.__image) ** 2) / np.var(self.__image)
self.__slicesObj = AutocorrelationSlices(self.__autocorrelation)


def _medianFilter(self, filterSize: int = 3):
self.__image = median_filter(self.__image, filterSize)

def showImage(self):
plt.imshow(self.__image)
plt.show()

def showAutocorrelation(self, showColorbar: bool = True):
if self.__autocorrelation is None:
raise ValueError("No autocorrelation computed.")
plt.imshow(self.__autocorrelation)
if showColorbar:
plt.colorbar()
plt.show()

def showAutocorrelationSlices(self, indices: tuple = None, showHorizontal: bool = True, showVertical: bool = True):
vSlice, hSlice = self.getSlices(indices)
if showHorizontal and showVertical:
fig, (ax1, ax2) = plt.subplots(2, sharey="col")
fig.suptitle("Autocorrelation slices")

ax1.plot(hSlice)
ax1.set_title(f"Horizontal slice (at index {indices[0]})")
ax1.set_xlabel("Horizontal position $x$ [pixel]")

ax2.plot(vSlice)
ax1.set_title(f"Vertical slice (at index {indices[1]})")
ax1.set_xlabel("Vertical position $y$ [pixel]")

ylabel = "Normalized autocorrelation coefficient [-]"
fig.text(0.06, 0.5, ylabel, ha='center', va='center', rotation='vertical')
plt.subplots_adjust(hspace=0.32)
plt.show()
elif showVertical:
plt.plot(vSlice)
plt.title(f"Vertical slice (at index {indices[1]})")
plt.xlabel("Vertical position $y$ [pixel]")
plt.ylabel("Normalized autocorrelation coefficient [-]")
plt.show()
elif showHorizontal:
plt.plot(hSlice)
plt.title(f"Horizontal slice (at index {indices[0]})")
plt.xlabel("Horizontal position $x$ [pixel]")
plt.ylabel("Normalized autocorrelation coefficient [-]")
plt.show()


class AutocorrelationSlices:

def __init__(self, autocorrelation: np.ndarray):
if not isinstance(autocorrelation, np.ndarray):
raise TypeError("The autocorrelation parameter must be a numpy array.")
if not autocorrelation.ndim == 2:
raise ValueError("The autocorrelation must be in 2D.")
self.__autocorrelation = autocorrelation

def slicesAt(self, indices: tuple):
if len(indices) != 2:
raise ValueError("There must be 2 indices of slicing, one horizontal and one vertical.")
# Assumes indices[0] is the width and indices[1] is the height
xSlice, ySlice = indices[0], indices[1]
verticalSlice = self.__autocorrelation[:, ySlice]
horizontalSlice = self.__autocorrelation[xSlice, :]
return verticalSlice, horizontalSlice

def middleSlices(self):
# Assumes the shape of the autocorrelation is (width, height) or (nb columns, nb lines)
middleX, middleY = self.__autocorrelation.shape[0] // 2, self.__autocorrelation.shape[1] // 2
return self.slicesAt((middleX, middleY))
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
61 changes: 61 additions & 0 deletions SpeckleSizeCode/PythonAutocorr/gaussianNormalization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import tifffile
from scipy.ndimage import gaussian_filter
import numpy as np
import cv2
import os


class GaussianNormalization:

def __init__(self, image: np.ndarray):
self.image = image
self.normalized = None

def normalize(self, stdDev: float):
gaussianFiltered = gaussian_filter(self.image, stdDev)
self.normalized = self.image / gaussianFiltered - np.mean(self.image)

def saveToOriginalFormat(self, name: str, stdDevNormalization: float = 75):
raise NotImplementedError("You must implement this method in format-specific classes.")


class TiffFileGaussianNormalization(GaussianNormalization):

def __init__(self, path: str):
image = tifffile.imread(path)
super(TiffFileGaussianNormalization, self).__init__(image)

def saveToOriginalFormat(self, name: str, stdDevNormalization: float = 75):
if self.normalized is None:
self.normalize(stdDevNormalization)
if not name.endswith(".tif") and not name.endswith(".tiff"):
name += ".tif"
tifffile.imwrite(name, self.image)


class PNGFileGaussianNormalization(GaussianNormalization):

def __init__(self, path: str):
image = cv2.imread(path)
super(PNGFileGaussianNormalization, self).__init__(image)

def saveToOriginalFormat(self, name: str, stdDevNormalization: float = 75):
if self.normalized is None:
self.normalize(stdDevNormalization)
if not name.endswith(".png"):
name += ".png"
cv2.imwrite(name, self.image)


if __name__ == '__main__':
# This is where you can normalize and save files.
# This is an example that normalizes avery tif file in MATLAB folder.
for nb in range(1, 32):
fname = r"20190924-200ms_20mW_Ave15_Gray_10X0.4_{}.tif".format(nb)
p = os.path.dirname(os.path.join(os.getcwd(), "..", ".."))
path = os.path.join(p, "MATLAB", fname)
newName = path[:-4] + "_GaussianNorm_75StdDev.tif" # We don't want the previous .tif in the new name

tif = TiffFileGaussianNormalization(path)
tif.saveToOriginalFormat(newName)
print(f"{nb} / 31 processed")
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading