Neurova Documentation

A complete Python library for image processing, computer vision, deep learning, and classical machine learning. One install, one namespace - go from raw image to trained model without switching tools.

Image Processing

Color spaces, filters, transformations, morphology, and segmentation.

Computer Vision

Face detection, object detection, feature matching, and video processing.

Machine Learning

Classification, regression, clustering, SVM, and dimensionality reduction.

Deep Learning

Neural networks, CNNs, RNNs, Transformers, and automatic differentiation.

Built-in Datasets

Iris, Titanic, Fashion-MNIST, time series, and cascade classifiers included.

GPU Acceleration

Optional CuPy backend for 10-100x speedups on NVIDIA GPUs.

Installation

Install Neurova from PyPI:

# Basic installation
pip install neurova

With GPU support (NVIDIA GPUs):

pip install neurova cupy-cuda12x  # Replace 12x with your CUDA version

Development installation:

git clone https://github.com/nalystresearch/neurova.git
cd neurova
pip install -e ".[dev]"

Quick Start

Load, process, and save an image in just a few lines:

import neurova as nv

# Load image
img = nv.io.read_image("photo.jpg")

# Apply transformations
gray = nv.core.to_grayscale(img)
blurred = nv.filters.gaussian_blur(gray, kernel_size=5)
edges = nv.filters.canny_edges(blurred, low=50, high=150)

# Save result
nv.io.write_image("edges.jpg", edges)

Core Operations

Basic image manipulation and color space operations:

import neurova as nv
from neurova import io, core, transform

# Load image
img = io.read_image("photo.jpg")

# Color space conversions
gray = core.to_grayscale(img)
hsv = core.convert_color_space(img, core.ColorSpace.BGR, core.ColorSpace.HSV)
lab = core.convert_color_space(img, core.ColorSpace.BGR, core.ColorSpace.LAB)

# Image transformations
resized = transform.resize(img, width=800, height=600)
rotated = core.rotate(img, core.ROTATE_90_CLOCKWISE)  # 90/180/270 degree rotation
rotated_angle = transform.rotate(img, angle=45)       # Any angle rotation
flipped_h = core.flip(img, core.FLIP_HORIZONTAL)
flipped_v = core.flip(img, core.FLIP_VERTICAL)

# Image arithmetic
added = core.add(img1, img2)
subtracted = core.subtract(img1, img2)
weighted = core.addWeighted(img1, 0.7, img2, 0.3, gamma=0)
diff = core.absdiff(img1, img2)

# Channel operations
channels = core.split(img)  # Split into B, G, R channels
merged = core.merge(channels)  # Merge back

Filters & Effects

Apply convolution filters, blur, edge detection, and morphological operations:

import neurova as nv
from neurova import filters

img = nv.io.read_image("photo.jpg")

# Blur filters
blurred = filters.gaussian_blur(img, kernel_size=5)
median = filters.median_blur(img, kernel_size=3)
bilateral = filters.bilateralFilter(img, d=9, sigmaColor=75, sigmaSpace=75)

# Edge detection
edges_canny = filters.canny_edges(img, low=50, high=150)
edges_sobel = filters.sobel(img)
edges_laplacian = filters.laplacian(img)

# Sharpening
sharpened = filters.sharpen(img)

# Morphological operations
from neurova import morphology
dilated = morphology.dilate(binary_img, kernel_size=3)
eroded = morphology.erode(binary_img, kernel_size=3)
opened = morphology.opening(binary_img, kernel_size=3)
closed = morphology.closing(binary_img, kernel_size=3)

Transformations

Geometric transformations and image enhancement:

import neurova as nv
from neurova import transform, core

img = nv.io.read_image("photo.jpg")

# Resize (fixed dimensions)
resized = transform.resize(img, width=800, height=600)

# Rotation (any angle)
rotated = transform.rotate(img, angle=45)

# Flip (using core module)
flipped_h = core.flip(img, core.FLIP_HORIZONTAL)
flipped_v = core.flip(img, core.FLIP_VERTICAL)

# Affine warp (using 2x3 transformation matrix)
M = transform.get_rotation_matrix2d(center=(img.shape[1]//2, img.shape[0]//2), angle=30, scale=1.0)
warped = transform.warp_affine(img, M, output_size=(img.shape[1], img.shape[0]))

Segmentation

Image segmentation techniques:

import neurova as nv
from neurova import segmentation

img = nv.io.read_image("photo.jpg")
gray = nv.core.to_grayscale(img)

# Thresholding
binary = segmentation.apply_threshold(gray, value=127)
otsu = segmentation.otsu_threshold(gray)

# Contour detection
contours = segmentation.find_contours(binary)
print(f"Found {len(contours)} contours")

# Connected component labeling
labeled, num_labels = segmentation.label_connected_components(binary)
print(f"Found {num_labels} connected components")

# Region properties analysis
regions = segmentation.regionprops(labeled)
for region in regions:
    print(f"Region {region.label}: area={region.area}, centroid={region.centroid}")

# Watershed segmentation (for overlapping objects)
labels = segmentation.watershed_segmentation(img, markers)

Feature Detection

Detect and match keypoints, corners, and edges:

import neurova as nv
from neurova import features

# Load images
img1 = nv.io.read_image("scene1.jpg")
img2 = nv.io.read_image("scene2.jpg")
gray1 = nv.core.to_grayscale(img1)
gray2 = nv.core.to_grayscale(img2)

# Corner detection
harris_corners = features.detect_corners(gray1, method="harris")
shi_tomasi = features.detect_corners(gray1, method="shi_tomasi", max_corners=100)

# ORB keypoint detection and description
orb = features.ORB_create(nfeatures=500)
kp1, desc1 = orb.detectAndCompute(gray1, None)
kp2, desc2 = orb.detectAndCompute(gray2, None)

# SIFT features (more accurate, slower)
sift = features.SIFT_create()
kp_sift, desc_sift = sift.detectAndCompute(gray1, None)

# Brute-force matching
bf = features.BFMatcher_create(features.NORM_HAMMING, crossCheck=True)
matches = bf.match(desc1, desc2)
matches = sorted(matches, key=lambda x: x.distance)

# Visualize matches
result = features.drawMatches(img1, kp1, img2, kp2, matches[:50], None)
nv.io.write_image("matches.jpg", result)

Face Detection & Recognition

Detect and recognize faces using built-in cascade classifiers:

import neurova as nv
from neurova import datasets, imgproc
from neurova.face import FaceDetector, FaceRecognizer

# Load sample image (bundled with neurova)
img = datasets.load_sample_image('lena')

# Face detection with Haar cascades
detector = FaceDetector(method='haar')
faces = detector.detect(img)

for (x, y, w, h) in faces:
    print(f"Face at ({x}, {y}) size {w}x{h}")
    imgproc.rectangle(img, (x, y), (x+w, y+h), color=(0, 255, 0), thickness=2)

# Save result
nv.io.write_image("detected_faces.jpg", img)

Face recognition with training:

from neurova.face import FaceRecognizer, FaceDataset, FaceTrainer

# Load face dataset
dataset = FaceDataset("path/to/faces")

# Train recognizer
trainer = FaceTrainer()
recognizer = trainer.train(dataset)

# Recognize faces
label, confidence = recognizer.predict(face_image)

Object Detection

Neurova object detection with training support:

from neurova.object_detection import ObjectDetector, DetectionDataset, DetectionTrainer

# Load pre-trained detector
detector = ObjectDetector()

# Detect objects in image
detections = detector.detect(img)

for det in detections:
    print(f"Class: {det.class_name}, Confidence: {det.confidence:.2f}")
    print(f"Bounding box: {det.bbox}")

# Train custom detector
dataset = DetectionDataset("path/to/dataset")
trainer = DetectionTrainer()
model = trainer.train(dataset, epochs=100)

Video Processing

Video capture, processing, and tracking:

import neurova as nv
from neurova import video, highgui
from neurova.nvc import VideoCapture

# Open video file or webcam
cap = VideoCapture("input.mp4")  # or VideoCapture(0) for webcam

while True:
    ret, frame = cap.read()
    if not ret:
        break
    
    # Process frame
    gray = nv.core.to_grayscale(frame)
    edges = nv.filters.canny_edges(gray, low=50, high=150)
    
    # Display
    highgui.imshow("Edges", edges)
    if highgui.waitKey(1) == ord('q'):
        break

cap.release()

Object tracking:

from neurova.video import TrackerKCF_create, TrackerCSRT_create

# Create tracker (KCF is fast, CSRT is more accurate)
tracker = TrackerKCF_create()

# Initialize with first frame and bounding box (x, y, w, h)
bbox = (100, 100, 200, 150)
tracker.init(frame, bbox)

# Track in subsequent frames
while True:
    ret, frame = cap.read()
    if not ret:
        break
    success, new_bbox = tracker.update(frame)
    if success:
        x, y, w, h = [int(v) for v in new_bbox]
        imgproc.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

ML: Preprocessing

Essential data preprocessing tools:

from neurova.ml import (
    StandardScaler, MinMaxScaler, RobustScaler, MaxAbsScaler,
    LabelEncoder, OneHotEncoder, 
    SimpleImputer, KNNImputer
)

# SCALING DATA
# StandardScaler: zero mean, unit variance
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# MinMaxScaler: scale to [0, 1] range
minmax = MinMaxScaler()
X_minmax = minmax.fit_transform(X)

# RobustScaler: handles outliers using median/IQR
robust = RobustScaler()
X_robust = robust.fit_transform(X)

# MaxAbsScaler: scale to [-1, 1] preserving sparsity
maxabs = MaxAbsScaler()
X_maxabs = maxabs.fit_transform(X)

# ENCODING CATEGORICAL DATA
# LabelEncoder: convert labels to integers
encoder = LabelEncoder()
y_encoded = encoder.fit_transform(['cat', 'dog', 'bird', 'cat'])

# OneHotEncoder: convert to one-hot vectors
onehot = OneHotEncoder()
y_onehot = onehot.fit_transform(y.reshape(-1, 1))

# HANDLING MISSING DATA
# SimpleImputer: fill with mean, median, or constant
imputer = SimpleImputer(strategy='mean')
X_filled = imputer.fit_transform(X_with_nan)

# KNNImputer: fill using k-nearest neighbors
knn_imputer = KNNImputer(n_neighbors=5)
X_filled = knn_imputer.fit_transform(X_with_nan)

Feature Selection

Select the most important features:

from neurova.ml import (
    SelectKBest, SelectPercentile, RFE, VarianceThreshold,
    f_classif, f_regression, mutual_info_classif
)

# Remove low variance features
selector = VarianceThreshold(threshold=0.1)
X_high_var = selector.fit_transform(X)

# Select K best features using statistical test
kbest = SelectKBest(score_func=f_classif, k=10)
X_best = kbest.fit_transform(X, y)
print(f"Selected features: {kbest.get_support(indices=True)}")
print(f"Feature scores: {kbest.scores_}")

# Select top percentile features
percentile = SelectPercentile(score_func=f_classif, percentile=50)
X_top = percentile.fit_transform(X, y)

# Recursive Feature Elimination
from neurova.ml import RandomForestClassifier
model = RandomForestClassifier()
rfe = RFE(estimator=model, n_features_to_select=5)
X_rfe = rfe.fit_transform(X, y)
print(f"Feature ranking: {rfe.ranking_}")

ML: Classification

Classification algorithms with built-in datasets:

from neurova import datasets
from neurova.ml import (
    KNearestNeighbors, LogisticRegression, NaiveBayes,
    DecisionTreeClassifier, RandomForestClassifier, SVM
)

# Load built-in dataset
df = datasets.load_iris()
X = df[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']].values
y = df['species'].astype('category').cat.codes.values

# K-Nearest Neighbors
knn = KNearestNeighbors(n_neighbors=3)
knn.fit(X, y)
predictions = knn.predict(X[:5])

# Logistic Regression
logreg = LogisticRegression(C=1.0)
logreg.fit(X, y)
probabilities = logreg.predict_proba(X[:5])

# Naive Bayes
nb = NaiveBayes()
nb.fit(X, y)

# Decision Tree
tree = DecisionTreeClassifier(max_depth=5)
tree.fit(X, y)

# Random Forest
rf = RandomForestClassifier(n_estimators=100)
rf.fit(X, y)

# Support Vector Machine
svm = SVM(kernel='rbf')
svm.fit(X, y)

ML: Regression

Comprehensive regression algorithms:

from neurova import datasets
from neurova.ml import (
    LinearRegression, Ridge, Lasso, ElasticNet,
    BayesianRidge, HuberRegressor, QuantileRegressor,
    SVR, KernelRidge, GaussianProcessRegressor,
    Lars, OrthogonalMatchingPursuit
)

# Load dataset
df = datasets.load_boston_housing()
X = df.drop('MEDV', axis=1).values
y = df['MEDV'].values

# Linear Regression
lr = LinearRegression()
lr.fit(X, y)
predictions = lr.predict(X)

# Ridge Regression (L2 regularization)
ridge = Ridge(alpha=1.0)
ridge.fit(X, y)

# Lasso Regression (L1 regularization - sparse solutions)
lasso = Lasso(alpha=0.1)
lasso.fit(X, y)
print(f"Non-zero coefficients: {(lasso.coef_ != 0).sum()}")

# ElasticNet (L1 + L2 regularization)
elastic = ElasticNet(alpha=1.0, l1_ratio=0.5)
elastic.fit(X, y)

# Bayesian Ridge (probabilistic regression)
bayesian = BayesianRidge()
bayesian.fit(X, y)
mean, std = bayesian.predict(X, return_std=True)

# Huber Regressor (robust to outliers)
huber = HuberRegressor(epsilon=1.35)
huber.fit(X, y)

# Support Vector Regression
svr = SVR(kernel='rbf', C=1.0, epsilon=0.1)
svr.fit(X, y)

# Kernel Ridge Regression
kr = KernelRidge(kernel='rbf', alpha=1.0)
kr.fit(X, y)

# Gaussian Process Regression
gpr = GaussianProcessRegressor()
gpr.fit(X, y)
mean, std = gpr.predict(X, return_std=True)

SVM & Gaussian Processes

Support Vector Machines and Gaussian Process models:

from neurova.ml import (
    SVC, SVR, KernelRidge,
    GaussianProcessClassifier, GaussianProcessRegressor
)

# Support Vector Classification
svc = SVC(kernel='rbf', C=1.0, gamma='scale')
svc.fit(X_train, y_train)
predictions = svc.predict(X_test)

# Get probability estimates
svc_prob = SVC(kernel='rbf', probability=True)
svc_prob.fit(X_train, y_train)
probabilities = svc_prob.predict_proba(X_test)

# Different kernels
svc_linear = SVC(kernel='linear')
svc_poly = SVC(kernel='poly', degree=3)
svc_sigmoid = SVC(kernel='sigmoid')

# Gaussian Process Classifier
gpc = GaussianProcessClassifier()
gpc.fit(X_train, y_train)
probabilities = gpc.predict_proba(X_test)

ML: Clustering

Clustering algorithms:

from neurova import datasets
from neurova.ml import (
    KMeans, MiniBatchKMeans, DBSCAN, AgglomerativeClustering,
    MeanShift, SpectralClustering, OPTICS, GaussianMixture, Birch
)

# Load clustering dataset
df = datasets.load_mall_customers()
X = df[['Annual Income (k$)', 'Spending Score (1-100)']].values

# K-Means
kmeans = KMeans(n_clusters=5)
kmeans.fit(X)
labels = kmeans.predict(X)
centers = kmeans.cluster_centers_

# Mini-Batch K-Means (faster for large datasets)
mbkmeans = MiniBatchKMeans(n_clusters=5, batch_size=100)
mbkmeans.fit(X)

# DBSCAN (density-based, no n_clusters needed)
dbscan = DBSCAN(eps=5, min_samples=3)
dbscan.fit(X)
labels = dbscan.labels_

# OPTICS (improved DBSCAN)
optics = OPTICS(min_samples=5, xi=0.05)
optics.fit(X)

# Agglomerative Clustering (hierarchical)
hc = AgglomerativeClustering(n_clusters=5, linkage='ward')
hc.fit(X)

# Mean Shift (finds clusters automatically)
meanshift = MeanShift(bandwidth=2)
meanshift.fit(X)

# Spectral Clustering (graph-based)
spectral = SpectralClustering(n_clusters=5, affinity='rbf')
spectral.fit(X)

# Gaussian Mixture Model (probabilistic)
gmm = GaussianMixture(n_components=5, covariance_type='full')
gmm.fit(X)
probabilities = gmm.predict_proba(X)

# BIRCH (for large datasets)
birch = Birch(n_clusters=5, threshold=0.5)
birch.fit(X)

ML: Dimensionality Reduction

Reduce feature dimensions for visualization and efficiency:

from neurova import datasets
from neurova.ml import (
    PCA, TSNE, LDA, KernelPCA,
    Isomap, MDS, LocallyLinearEmbedding, SpectralEmbedding,
    TruncatedSVD, FactorAnalysis, NMF
)

# Load high-dimensional data
df = datasets.load_iris()
X = df[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']].values
y = df['species'].astype('category').cat.codes.values

# Principal Component Analysis
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)
print(f"Explained variance: {pca.explained_variance_ratio_}")

# Kernel PCA (for non-linear data)
kpca = KernelPCA(n_components=2, kernel='rbf')
X_kpca = kpca.fit_transform(X)

# t-SNE for visualization
tsne = TSNE(n_components=2, perplexity=30)
X_tsne = tsne.fit_transform(X)

# Linear Discriminant Analysis (supervised)
lda = LDA(n_components=2)
X_lda = lda.fit_transform(X, y)

# Isomap (manifold learning)
isomap = Isomap(n_components=2, n_neighbors=5)
X_isomap = isomap.fit_transform(X)

# MDS (Multidimensional Scaling)
mds = MDS(n_components=2)
X_mds = mds.fit_transform(X)

# Locally Linear Embedding
lle = LocallyLinearEmbedding(n_components=2, n_neighbors=10)
X_lle = lle.fit_transform(X)

# Spectral Embedding
se = SpectralEmbedding(n_components=2)
X_se = se.fit_transform(X)

# Truncated SVD (for sparse data)
svd = TruncatedSVD(n_components=2)
X_svd = svd.fit_transform(X)

# Factor Analysis
fa = FactorAnalysis(n_components=2)
X_fa = fa.fit_transform(X)

# Non-negative Matrix Factorization
nmf = NMF(n_components=2)
X_nmf = nmf.fit_transform(X_positive)

ML: Model Evaluation

Evaluate your models with comprehensive metrics:

from neurova.ml import (
    accuracy_score, precision_score, recall_score, f1_score,
    confusion_matrix, classification_report,
    mean_squared_error, mean_absolute_error, r2_score
)

# CLASSIFICATION METRICS
y_true = [0, 1, 1, 0, 1, 0, 1, 1]
y_pred = [0, 1, 0, 0, 1, 1, 1, 1]

# Basic metrics
acc = accuracy_score(y_true, y_pred)
prec = precision_score(y_true, y_pred)
rec = recall_score(y_true, y_pred)
f1 = f1_score(y_true, y_pred)

print(f"Accuracy: {acc:.3f}")
print(f"Precision: {prec:.3f}")
print(f"Recall: {rec:.3f}")
print(f"F1 Score: {f1:.3f}")

# Confusion Matrix
cm = confusion_matrix(y_true, y_pred)
print(f"Confusion Matrix:\n{cm}")

# Full classification report
report = classification_report(y_true, y_pred)
print(report)

# REGRESSION METRICS
y_true_reg = [3.0, 2.5, 4.0, 5.5]
y_pred_reg = [2.8, 2.6, 3.9, 5.2]

mse = mean_squared_error(y_true_reg, y_pred_reg)
mae = mean_absolute_error(y_true_reg, y_pred_reg)
r2 = r2_score(y_true_reg, y_pred_reg)

print(f"MSE: {mse:.4f}")
print(f"MAE: {mae:.4f}")
print(f"R² Score: {r2:.4f}")

ML: Cross-Validation

Robust model validation techniques:

from neurova.ml import (
    train_test_split, cross_validate,
    KFold, StratifiedKFold, GroupKFold, LeaveOneOut, TimeSeriesSplit,
    GridSearchCV, RandomizedSearchCV
)

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# K-Fold Cross-Validation
kfold = KFold(n_splits=5, shuffle=True, random_state=42)
for train_idx, val_idx in kfold.split(X):
    X_train, X_val = X[train_idx], X[val_idx]
    y_train, y_val = y[train_idx], y[val_idx]
    # Train and evaluate...

# Stratified K-Fold (preserves class distribution)
skfold = StratifiedKFold(n_splits=5)
for train_idx, val_idx in skfold.split(X, y):
    # Train and evaluate...

# Time Series Split (for temporal data)
tscv = TimeSeriesSplit(n_splits=5)
for train_idx, val_idx in tscv.split(X):
    # Train on past, validate on future...

# Cross-validate with scoring
from neurova.ml import RandomForestClassifier
model = RandomForestClassifier()
scores = cross_validate(model, X, y, cv=5, scoring='accuracy')
print(f"CV Scores: {scores['test_score']}")
print(f"Mean: {scores['test_score'].mean():.3f} ± {scores['test_score'].std():.3f}")

Hyperparameter Tuning

Find optimal hyperparameters:

from neurova.ml import GridSearchCV, RandomizedSearchCV, RandomForestClassifier

# Grid Search - exhaustive search
param_grid = {
    'n_estimators': [50, 100, 200],
    'max_depth': [5, 10, None],
    'min_samples_split': [2, 5, 10]
}
model = RandomForestClassifier()
grid_search = GridSearchCV(model, param_grid, cv=5, scoring='accuracy')
grid_search.fit(X_train, y_train)

print(f"Best params: {grid_search.best_params_}")
print(f"Best score: {grid_search.best_score_:.3f}")
best_model = grid_search.best_estimator_

# Randomized Search - faster for large search spaces
param_dist = {
    'n_estimators': [50, 100, 150, 200],
    'max_depth': [5, 10, 15, 20, None],
    'min_samples_split': range(2, 20)
}
random_search = RandomizedSearchCV(
    model, param_dist, n_iter=20, cv=5, random_state=42
)
random_search.fit(X_train, y_train)
print(f"Best params: {random_search.best_params_}")

ML: Pipelines

Chain preprocessing and modeling steps:

from neurova.ml import (
    Pipeline, ColumnTransformer, FeatureUnion, make_pipeline,
    StandardScaler, SimpleImputer, SelectKBest, f_classif,
    RandomForestClassifier
)

# Simple pipeline
pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('selector', SelectKBest(k=10)),
    ('classifier', RandomForestClassifier())
])

# Fit entire pipeline
pipe.fit(X_train, y_train)

# Predict (automatically applies all transformations)
predictions = pipe.predict(X_test)

# Using make_pipeline (auto-generates step names)
pipe = make_pipeline(
    StandardScaler(),
    SelectKBest(k=10),
    RandomForestClassifier()
)

# ColumnTransformer for mixed data types
from neurova.ml import OneHotEncoder, MinMaxScaler

numeric_features = ['age', 'income', 'score']
categorical_features = ['gender', 'city', 'category']

preprocessor = ColumnTransformer([
    ('num', Pipeline([
        ('imputer', SimpleImputer(strategy='mean')),
        ('scaler', StandardScaler())
    ]), numeric_features),
    ('cat', Pipeline([
        ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
        ('onehot', OneHotEncoder(handle_unknown='ignore'))
    ]), categorical_features)
])

# Full pipeline with mixed preprocessing
full_pipeline = Pipeline([
    ('preprocessor', preprocessor),
    ('classifier', RandomForestClassifier())
])
full_pipeline.fit(X_train, y_train)

ML: Statistical Tests

Statistical hypothesis testing:

from neurova.ml import (
    ttest_ind, ttest_1samp, ttest_rel,
    f_oneway, chi2_contingency, kstest
)

# T-test: compare means of two groups
group_a = [23, 25, 28, 31, 27, 29, 24, 26]
group_b = [30, 32, 35, 33, 31, 34, 36, 32]

# Independent two-sample t-test
t_stat, p_value = ttest_ind(group_a, group_b)
print(f"T-statistic: {t_stat:.3f}, P-value: {p_value:.4f}")
if p_value < 0.05:
    print("Significant difference between groups")

# One-sample t-test (compare to known mean)
t_stat, p_value = ttest_1samp(group_a, popmean=25)
print(f"Sample mean vs 25: p={p_value:.4f}")

# Paired t-test (before/after comparison)
before = [150, 160, 155, 170, 165]
after = [145, 155, 150, 160, 160]
t_stat, p_value = ttest_rel(before, after)
print(f"Paired test: p={p_value:.4f}")

# ANOVA: compare means of 3+ groups
group_c = [28, 30, 29, 32, 31]
f_stat, p_value = f_oneway(group_a, group_b, group_c)
print(f"ANOVA F={f_stat:.3f}, p={p_value:.4f}")

# Chi-square test for categorical data
observed = [[10, 20, 30], [6, 9, 17]]
chi2, p_value, dof, expected = chi2_contingency(observed)
print(f"Chi-square: {chi2:.3f}, p={p_value:.4f}")

# Kolmogorov-Smirnov test (test distribution)
from neurova.ml import kstest
data = [0.5, 0.3, 0.8, 0.2, 0.9, 0.4]
stat, p_value = kstest(data, 'norm')
print(f"KS test: statistic={stat:.3f}, p={p_value:.4f}")

ML: Ensemble Methods

Combine multiple models for better performance:

from neurova.ml import (
    RandomForestClassifier, RandomForestRegressor,
    GradientBoostingClassifier, GradientBoostingRegressor,
    AdaBoostClassifier, AdaBoostRegressor,
    BaggingClassifier, BaggingRegressor,
    DecisionTreeClassifier
)

# Random Forest (bagging with decision trees)
rf = RandomForestClassifier(
    n_estimators=100,
    max_depth=10,
    min_samples_split=5,
    random_state=42
)
rf.fit(X_train, y_train)
print(f"Feature importances: {rf.feature_importances_}")

# Gradient Boosting
gb = GradientBoostingClassifier(
    n_estimators=100,
    learning_rate=0.1,
    max_depth=3
)
gb.fit(X_train, y_train)

# AdaBoost
ada = AdaBoostClassifier(
    base_estimator=DecisionTreeClassifier(max_depth=1),
    n_estimators=50,
    learning_rate=1.0
)
ada.fit(X_train, y_train)

# Bagging (with any base estimator)
bagging = BaggingClassifier(
    base_estimator=DecisionTreeClassifier(),
    n_estimators=10,
    max_samples=0.8,
    max_features=0.8
)
bagging.fit(X_train, y_train)

Time Series Analysis

Comprehensive time series modeling and analysis:

from neurova.timeseries import (
    ARIMA, auto_arima,
    SimpleExponentialSmoothing, ExponentialSmoothing,
    seasonal_decompose, stl_decompose,
    acf, pacf, adfuller, ljung_box
)
from neurova import datasets

# Load time series data
df = datasets.load_airline_passengers()
ts = df['Passengers'].values

# ARIMA Model
model = ARIMA(order=(1, 1, 1))
model.fit(ts)
forecast = model.predict(steps=12)

# Auto ARIMA (automatic parameter selection)
auto_model = auto_arima(ts, seasonal=True, m=12)
forecast = auto_model.predict(steps=12)

# Exponential Smoothing
# Simple exponential smoothing
ses = SimpleExponentialSmoothing(ts)
ses.fit()
forecast = ses.predict(steps=12)

# Holt-Winters exponential smoothing
hw = ExponentialSmoothing(ts, trend='add', seasonal='add', seasonal_periods=12)
hw.fit()
forecast = hw.predict(steps=12)

# Time Series Decomposition
# Classical decomposition
result = seasonal_decompose(ts, period=12)
trend = result.trend
seasonal = result.seasonal
residual = result.resid

# STL decomposition (more robust)
stl_result = stl_decompose(ts, period=12)

# Statistical Tests
# Autocorrelation function
acf_values = acf(ts, nlags=20)
pacf_values = pacf(ts, nlags=20)

# Augmented Dickey-Fuller test (stationarity)
adf_stat, p_value = adfuller(ts)
if p_value < 0.05:
    print("Series is stationary")
else:
    print("Series is non-stationary, differencing needed")

# Ljung-Box test (autocorrelation)
lb_stat, lb_p_value = ljung_box(ts, lags=10)

Data Augmentation

Image augmentation for deep learning:

from neurova.augmentation import (
    Compose, RandomApply, RandomChoice, RandomOrder,
    # Geometric transforms
    Resize, RandomCrop, CenterCrop, RandomResizedCrop,
    RandomHorizontalFlip, RandomVerticalFlip,
    RandomRotation, RandomAffine, RandomPerspective,
    # Color transforms
    ColorJitter, RandomGrayscale, GaussianBlur,
    RandomInvert, RandomPosterize, RandomSolarize,
    # Advanced transforms
    ElasticTransform, GridDistortion, OpticalDistortion, CLAHE
)

# Compose multiple transforms
transform = Compose([
    Resize((256, 256)),
    RandomCrop((224, 224)),
    RandomHorizontalFlip(p=0.5),
    RandomRotation(degrees=15),
    ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
    GaussianBlur(kernel_size=3, sigma=(0.1, 2.0))
])

# Apply to image
augmented = transform(image)

# Random apply (50% chance)
transform = RandomApply([
    RandomRotation(30),
    ColorJitter(brightness=0.5)
], p=0.5)

# Random choice (pick one randomly)
transform = RandomChoice([
    RandomHorizontalFlip(p=1.0),
    RandomVerticalFlip(p=1.0),
    RandomRotation(90)
])

# Training augmentation pipeline
train_transform = Compose([
    RandomResizedCrop(224, scale=(0.8, 1.0)),
    RandomHorizontalFlip(p=0.5),
    ColorJitter(brightness=0.2, contrast=0.2),
    RandomGrayscale(p=0.1),
])

# Color space conversions
from neurova.augmentation import RGBToHSV, HSVToRGB, RGBToLAB, LABToRGB
hsv_image = RGBToHSV()(rgb_image)
lab_image = RGBToLAB()(rgb_image)

Neural Networks

Build and train neural networks with automatic differentiation:

from neurova import datasets
from neurova.neural import layers, Tensor, optim

# Load Fashion-MNIST (bundled with neurova)
(train_images, train_labels), (test_images, test_labels) = datasets.load_fashion_mnist()

# Create a simple neural network
model = layers.Sequential([
    layers.Linear(784, 256),
    layers.ReLU(),
    layers.Dropout(p=0.2),
    layers.Linear(256, 128),
    layers.ReLU(),
    layers.Linear(128, 10),
    layers.Softmax()
])

# Define optimizer
optimizer = optim.Adam(model.parameters(), lr=0.001)

# Training loop
for epoch in range(10):
    for batch_x, batch_y in dataloader:
        output = model.forward(batch_x)
        loss = compute_loss(output, batch_y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    print(f"Epoch {epoch + 1}, Loss: {loss.value:.4f}")

Convolutional Neural Network:

from neurova.neural import layers

# Create CNN
cnn = layers.Sequential([
    layers.Conv2D(in_channels=1, out_channels=32, kernel_size=3, padding=1),
    layers.ReLU(),
    layers.MaxPool2D(kernel_size=2),
    layers.Conv2D(in_channels=32, out_channels=64, kernel_size=3, padding=1),
    layers.ReLU(),
    layers.MaxPool2D(kernel_size=2),
    layers.Flatten(),
    layers.Linear(64 * 7 * 7, 128),
    layers.ReLU(),
    layers.Dropout(p=0.5),
    layers.Linear(128, 10)
])

Pre-built Architectures

Ready-to-use neural network architectures:

from neurova.architecture import (
    MLP, CNN, LSTM, GRU, Transformer,
    Autoencoder, VAE, GAN,
    create_cnn, create_mlp, create_transformer
)

# Multi-Layer Perceptron
mlp = MLP(input_size=784, hidden_sizes=[256, 128], output_size=10)

# Convolutional Neural Network
cnn = CNN(input_channels=3, num_classes=10)

# LSTM for sequences
lstm = LSTM(input_size=100, hidden_size=256, num_layers=2)

# Transformer
transformer = Transformer(
    d_model=512,
    nhead=8,
    num_encoder_layers=6,
    num_decoder_layers=6
)

# Autoencoder
autoencoder = Autoencoder(input_dim=784, latent_dim=32)

# Variational Autoencoder
vae = VAE(input_dim=784, latent_dim=32)

# Generative Adversarial Network
gan = GAN(latent_dim=100, output_shape=(1, 28, 28))

Hyperparameter tuning:

from neurova.architecture import GridSearchCV, RandomSearchCV, AutoML

# Grid Search
grid_search = GridSearchCV(model, param_grid, cv=5)
best_params = grid_search.fit(X, y)

# Random Search
random_search = RandomSearchCV(model, param_distributions, n_iter=100)
best_params = random_search.fit(X, y)

# AutoML
automl = AutoML(task='classification', max_time=3600)
best_model = automl.fit(X, y)

GPU Acceleration

Enable GPU acceleration for massive speedups:

import neurova as nv

# Check GPU availability
print(f"GPU available: {nv.cuda_is_available()}")
print(f"GPU device: {nv.get_device_name()}")
print(f"Device count: {nv.get_device_count()}")

# Enable GPU globally
nv.set_device("cuda")

# Or use context manager for specific operations
with nv.device_context("cuda"):
    img = nv.io.read_image("large_image.jpg")
    processed = nv.filters.gaussian_blur(img, kernel_size=15)
    edges = nv.filters.canny_edges(processed)

# Memory management
nv.empty_cache()  # Free GPU memory
print(nv.get_memory_usage())  # Check memory usage
Operation CPU Time GPU Time Speedup
Gaussian Blur (4K) 150ms 3ms 50x
Canny Edge (4K) 200ms 5ms 40x
Feature Detection 500ms 10ms 50x
CNN Forward Pass 1000ms 10ms 100x

Built-in Datasets: Tabular

Ready-to-use datasets bundled with Neurova (no download needed):

from neurova import datasets

# Classification datasets
iris = datasets.load_iris()           # 150 samples, 4 features, 3 classes
titanic = datasets.load_titanic()     # Survival prediction
wine = datasets.load_wine()           # Wine classification

# Regression datasets
boston = datasets.load_boston_housing()  # Housing price prediction
diabetes = datasets.load_diabetes()      # Diabetes progression

# Clustering datasets
mall = datasets.load_mall_customers()    # Customer segmentation
penguins = datasets.load_penguins()      # Palmer Penguins dataset

# List all available datasets
print(datasets.list_datasets())

Built-in Datasets: Images

Sample images, Fashion-MNIST, and cascade classifiers included:

from neurova import datasets

# Load sample images (bundled - no download needed)
fruits = datasets.load_sample_image('fruits')       # Colorful fruit image
lena = datasets.load_sample_image('lena')           # Classic test image
building = datasets.load_sample_image('building')   # Architectural features
baboon = datasets.load_sample_image('baboon')       # Texture analysis
chessboard = datasets.load_sample_image('chessboard')  # Calibration pattern
sudoku = datasets.load_sample_image('sudoku')       # Document/grid processing

# List all available sample images
print(datasets.get_sample_images())  # ['baboon', 'building', 'chessboard', 'fruits', 'lena', 'sudoku']

# Fashion-MNIST (70,000 grayscale 28x28 images)
(train_images, train_labels), (test_images, test_labels) = datasets.load_fashion_mnist()
# Classes: T-shirt, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag, Ankle boot

Cascade classifiers for detection (17 Haar, 5 LBP, 1 HOG):

from neurova import datasets

# Haar cascades (17 classifiers)
face = datasets.get_haarcascade('frontalface_default')   # Face detection
face_alt = datasets.get_haarcascade('frontalface_alt')   # Alternative face
eye = datasets.get_haarcascade('eye')                    # Eye detection
smile = datasets.get_haarcascade('smile')                # Smile detection
fullbody = datasets.get_haarcascade('fullbody')          # Full body
upperbody = datasets.get_haarcascade('upperbody')        # Upper body
lowerbody = datasets.get_haarcascade('lowerbody')        # Lower body
profileface = datasets.get_haarcascade('profileface')    # Side face
catface = datasets.get_haarcascade('frontalcatface')     # Cat face
license_plate = datasets.get_haarcascade('russian_plate_number')  # License plates

# LBP cascades (faster, less accurate)
lbp_face = datasets.get_lbpcascade('frontalface')        # LBP face detection
lbp_face_improved = datasets.get_lbpcascade('frontalface_improved')
lbp_profile = datasets.get_lbpcascade('profileface')     # LBP profile face
lbp_catface = datasets.get_lbpcascade('frontalcatface')  # LBP cat face
lbp_silverware = datasets.get_lbpcascade('silverware')   # Silverware detection

# HOG cascade
hog_pedestrians = datasets.get_hogcascade('pedestrians')  # Pedestrian detection

Built-in Datasets: Time Series

Time series datasets for forecasting:

from neurova import datasets
from neurova.timeseries import ARIMA, ExponentialSmoothing

# Load time series data
air_passengers = datasets.load_air_passengers()    # Monthly airline passengers
temperatures = datasets.load_daily_temperatures()   # Daily temperature readings
sunspots = datasets.load_sunspots()                # Monthly sunspot counts

# Time series analysis
from neurova.timeseries import decomposition
trend, seasonal, residual = decomposition.seasonal_decompose(air_passengers)

# Forecasting with ARIMA
model = ARIMA(order=(5, 1, 0))
model.fit(air_passengers)
forecast = model.predict(steps=12)

# Exponential Smoothing
es = ExponentialSmoothing(trend='add', seasonal='add', seasonal_periods=12)
es.fit(air_passengers)
forecast = es.predict(steps=12)

Built-in Datasets: Recommendation

MovieLens-100K dataset for recommendation systems:

from neurova import datasets

# MovieLens-100K (100,000 ratings from 943 users on 1682 movies)
ratings = datasets.load_movielens_ratings()  # User-item ratings
movies = datasets.load_movielens_movies()    # Movie information
users = datasets.load_movielens_users()      # User demographics

# Pre-split train/test sets for evaluation
train, test = datasets.load_movielens_split('u1')  # 5 official splits available

Complete Module Reference

Module Description
neurova.io Image and video reading/writing (read_image, write_image, imread, imwrite)
neurova.core Color spaces, basic ops (to_grayscale, flip, rotate, split, merge, add, subtract)
neurova.imgproc Image processing (cvtColor, drawing, contours, thresholding)
neurova.filters Convolution, blurring, edge detection (gaussian_blur, canny, sobel, bilateralFilter)
neurova.morphology Morphological operations (dilate, erode, morphologyEx)
neurova.transform Geometric transformations (resize, rotate, warp_affine)
neurova.segmentation Thresholding, watershed, contours, region analysis
neurova.features Keypoint detection (ORB, SIFT, AKAZE), matching (BFMatcher)
neurova.face Face detection (FaceDetector, Haar/LBP/HOG) and recognition
neurova.object_detection Neurova object detection with training
neurova.detection Template and cascade-based detection
neurova.video Video capture, optical flow, background subtraction, trackers
neurova.highgui GUI functions (imshow, waitKey, window management)
neurova.ml Machine learning (KNN, SVM, Trees, Clustering, PCA, metrics)
neurova.neural Neural network layers and training
neurova.architecture Pre-built architectures (CNN, LSTM, Transformer, GAN, AutoML)
neurova.nn Low-level neural network operations (Tensor, Module)
neurova.datasets Built-in datasets (Iris, Titanic, Fashion-MNIST, cascades)
neurova.timeseries Time series analysis (ARIMA, decomposition)
neurova.augmentation Data augmentation pipelines for training
neurova.calibration Camera calibration and 3D geometry
neurova.nvc VideoCapture and native utility functions

Example Chapters

Neurova includes 12 comprehensive tutorial chapters in the examples/ directory:

Chapter Topic Description
01 Getting Started Installation, imports, device config, array ops
02 Image Transforms Color spaces, resize, rotate, flip, affine
03 Filters Blur, sharpen, edge detection, morphology
04 Features HOG, LBP, Harris corners, gradients, GLCM
05 Detection Haar, LBP, HOG cascades, multi-scale, NMS
06 Face FaceDetector, FaceRecognizer, FaceTrainer
07 Machine Learning KNN, Trees, SVM, clustering, PCA, metrics
08 Neural Networks Dense, Conv2D, activations, optimizers, CNN
09 Datasets All built-in datasets, data loaders, augmentation
10 Video VideoCapture, motion, background subtraction
11 Segmentation Thresholding, Otsu, connected components
12 GPU Performance CuPy acceleration, benchmarks, memory
# Run any chapter
python examples/chapter_07_machine_learning.py
python examples/chapter_09_datasets.py

Complete Projects

Two end-to-end projects with full pipelines:

Project Description Scripts
Face Recognition Collect faces, train model, webcam recognition 5 scripts + pipeline
Object Detection Annotate images, train Neurova detector 5 scripts + pipeline
# Face recognition project
python examples/face_recognition_project/01_collect_faces.py
python examples/face_recognition_project/02_prepare_dataset.py
python examples/face_recognition_project/03_train_model.py
python examples/face_recognition_project/04_evaluate_model.py
python examples/face_recognition_project/05_test_webcam.py

# Object detection project
python examples/object_detection_project/01_annotate_images.py
python examples/object_detection_project/02_prepare_dataset.py
python examples/object_detection_project/03_train_detector.py
python examples/object_detection_project/04_evaluate_detector.py
python examples/object_detection_project/05_test_webcam.py

Need Help?

Check out the resources below or reach out to the community:

Examples GitHub Issues Contact