Skielex / structure-tensor

Structure tensor 2D and 3D implementation for Python.
MIT License
47 stars 14 forks source link

Example for Visualizing Orientation #17

Open schirrmacher opened 1 month ago

schirrmacher commented 1 month ago

Can you add one simple example how you can visualize the orientation fields?

images

schirrmacher commented 1 month ago

Here my code which is probably not right:

import numpy as np
import matplotlib.pyplot as plt
from imageio import imread
from structure_tensor import eig_special_2d, structure_tensor_2d

# Parameters for the structure tensor
sigma = 1.5  # Noise scale
rho = 5.5    # Integration scale

# Load the image
image_path = '/content/hug_lab.png'
image = imread(image_path)

# Convert to grayscale if it's a color image
if image.ndim == 3:
    # Assuming the image is in RGB format
    image = np.dot(image[..., :3], [0.2989, 0.5870, 0.1140])

# Normalize the image to have values between 0 and 1
image = image.astype(np.float64) / 255.0

# Compute the structure tensor
S = structure_tensor_2d(image, sigma, rho)

# Compute eigenvalues and eigenvectors
val, vec = eig_special_2d(S)

# Compute the orientation angles
angles = np.arctan2(vec[1], vec[0])

# Sample the orientation field at a grid of points
step = 50  # Adjust step size as needed
Y_sample, X_sample = np.mgrid[0:image.shape[0]:step, 0:image.shape[1]:step]
angles_sample = angles[::step, ::step]

# Create quiver components
U = np.cos(angles_sample)
V = np.sin(angles_sample)

# Plot the original image
plt.figure(figsize=(50, 50))
plt.imshow(image, cmap='gray', origin='lower')
plt.colorbar()
plt.title('Image with Orientation Field')

# Overlay the orientation field using quiver
plt.quiver(
    X_sample, Y_sample, U, V,
    color='red', scale=30, width=0.005, headwidth=3, headlength=5
)

plt.xlabel('X')
plt.ylabel('Y')
plt.show()

Creates:

output

Skielex commented 1 month ago

Hey, I'm very busy at the moment. I can take a look, but won't have time for at least a week or so.