0% found this document useful (0 votes)
4 views2 pages

Curvature

The document outlines a Python script that uses TensorFlow and Keras to build a convolutional neural network (CNN) for classifying images based on curvature. It includes functions for loading images, calculating curvature, and training the model with a dataset of images. The trained model is saved and the training history is visualized using Matplotlib.

Uploaded by

Brindha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Curvature

The document outlines a Python script that uses TensorFlow and Keras to build a convolutional neural network (CNN) for classifying images based on curvature. It includes functions for loading images, calculating curvature, and training the model with a dataset of images. The trained model is saved and the training history is visualized using Matplotlib.

Uploaded by

Brindha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import tensorflow as tf

from tensorflow import keras


from tensorflow.keras import layers
import matplotlib.pyplot as plt
import numpy as np
import os
import cv2
from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array,
load_img

# Define dataset path


data_dir = r"C:\Users\Dell\Documents\image_2" # Change to your dataset path

# Image parameters
img_height, img_width = 128, 128 # Resize images
batch_size = 32

def calculate_curvature(image):
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
edges = cv2.Canny(gray, 50, 150)

contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL,


cv2.CHAIN_APPROX_SIMPLE)

if len(contours) == 0:
return 0 # Assume straight if no edges found

largest_contour = max(contours, key=cv2.contourArea)


points = largest_contour[:, 0, :]
if len(points) < 5:
return 0 # Not enough points

poly_coeff = np.polyfit(points[:, 0], points[:, 1], 2)


curvature = abs(poly_coeff[0]) # Higher value = more curve

return 1 if curvature > 0.0005 else 0 # Threshold for curvy vs. straight

# Load images and compute labels


images = []
labels = []

for filename in os.listdir(data_dir):


img_path = os.path.join(data_dir, filename)
image = load_img(img_path, target_size=(img_height, img_width))
image_array = img_to_array(image) / 255.0 # Normalize
images.append(image_array)

# Convert to OpenCV format and compute curvature


image_cv = np.array(image, dtype=np.uint8)
label = calculate_curvature(image_cv)
labels.append(label)

images = np.array(images)
labels = np.array(labels)

# Split dataset into training and validation


from sklearn.model_selection import train_test_split
x_train, x_val, y_train, y_val = train_test_split(images, labels, test_size=0.2,
random_state=42)
# Build the CNN model
model = keras.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(img_height,
img_width, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(128, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dropout(0.5),
layers.Dense(1, activation='sigmoid')
])

# Compile the model


model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])

# Train the model


epochs = 15
history = model.fit(x_train, y_train, epochs=epochs, validation_data=(x_val,
y_val))

# Save the trained model


model.save("road_type_classifier.h5")

# Plot training history


plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

print("Training samples:", x_train[:5])


print("Validation samples:", x_val[:5])

You might also like