search
HomeBackend DevelopmentPython TutorialTire Groove Analysis with Artificial Intelligence in Python!

Tyre tread analysis is a crucial task to identify wear and ensure safety, especially in vehicles that travel long distances. Using Artificial Intelligence (AI) and Python, we can automate this process quickly and accurately. Here, we show how a convolutional neural network (CNN) model, based on the VGG16 architecture, classifies tires into "new" or "used", while OpenCV helps analyze images to measure tread depth.

Technologies Used

  • Python:
    Popular programming language for AI and Machine Learning, especially for its advanced libraries.

  • OpenCV:
    Used to process images, detect contours and measure tire tread area.

  • TensorFlow and Keras:
    Deep learning libraries. We use Keras to work with the VGG16 model, a pre-trained CNN for image recognition.

  • Matplotlib:
    Library for data visualization and graph creation, making classification results more interpretable.

Code:

1. Load and Pre-process Images:
Tire images are uploaded and resized to a standard format (150x150 pixels) required for model input. This resizing maintains the aspect ratio and normalizes pixel values ​​between 0 and 1 to make it easier for the model to process.

import cv2
import numpy as np
from tensorflow.keras.applications.vgg16 import preprocess_input

def process_image(image_path, target_size=(150, 150)):
    image = cv2.imread(image_path)
    if image is None:
        print(f"Erro ao carregar a imagem: {image_path}. Verifique o caminho e a integridade do arquivo.")
        return None, None

    image_resized = cv2.resize(image, target_size, interpolation=cv2.INTER_AREA)
    image_array = np.array(image_resized) / 255.0  
    image_array = np.expand_dims(image_array, axis=0)
    image_preprocessed = preprocess_input(image_array)

    return image_resized, image_preprocessed

2. Classification with the Trained Model:
We loaded a pre-trained convolutional neural network model, which was fine-tuned to classify tires as “new” or “used”. This model provides a confidence score that indicates the probability that a tire is new.

from tensorflow.keras.models import load_model

model = load_model('pneu_classificador.keras')
prediction = model.predict(image_preprocessed)

3. Contour Analysis for Groove Depth:
Groove depth detection is performed using computer vision techniques. The grayscale image goes through a blur filter and Canny edge detection, which helps identify groove contours. We then calculate the total area of ​​the contours, which allows us to estimate wear.

def detect_tread_depth(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    edges = cv2.Canny(blurred, 30, 100)
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    total_area = sum(cv2.contourArea(c) for c in contours if cv2.contourArea(c) > 100)
    return total_area

4. Visualization and Analysis of Results:
After classifying and analyzing each tire, the results are displayed with Matplotlib. We compared the classification confidence score and the groove area detected in each image.

import matplotlib.pyplot as plt

confidence_scores = []
total_area_green_values = []
predicted_classes = []

for image_file in os.listdir(ver_dir):
    image_path = os.path.join(ver_dir, image_file)
    image_resized, image_preprocessed = process_image(image_path)
    if image_preprocessed is not None:
        prediction = model.predict(image_preprocessed)
        confidence_score = prediction[0][0]
        total_area_green = detect_tread_depth(image_resized)

        predicted_class = "novo" if total_area_green > 500 else "usado"
        confidence_scores.append(confidence_score)
        total_area_green_values.append(total_area_green)
        predicted_classes.append(predicted_class)

        plt.imshow(cv2.cvtColor(image_resized, cv2.COLOR_BGR2RGB))
        plt.title(f"Pneu {predicted_class} (Área: {total_area_green:.2f}, Confiança: {confidence_score:.2f})")
        plt.axis('off')
        plt.show()

fig, axs = plt.subplots(2, 1, figsize=(10, 10))

axs[0].bar(os.listdir(ver_dir), confidence_scores, color='skyblue')
axs[0].set_title('Confiança na Classificação')
axs[0].set_ylim(0, 1)
axs[0].tick_params(axis='x', rotation=45)

axs[1].bar(os.listdir(ver_dir), total_area_green_values, color='lightgreen')
axs[1].set_title('Área Verde Detectada')
axs[1].tick_params(axis='x', rotation=45)

plt.tight_layout()
plt.show()

Análise de Sulco de Pneus com Inteligência Artificial em Python!

Análise de Sulco de Pneus com Inteligência Artificial em Python!

Análise de Sulco de Pneus com Inteligência Artificial em Python!

This project of mine demonstrates how it is possible to automate tire wear analysis using AI and computer vision, resulting in accurate and fast classification. The VGG16 architecture and use of OpenCV are key to combining neural network model accuracy with visual sulci analysis. This system can be expanded for continuous monitoring across vehicle fleets, helping to reduce accidents and optimize tire management.

The above is the detailed content of Tire Groove Analysis with Artificial Intelligence in Python!. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

What is NumPy, and why is it important for numerical computing in Python?What is NumPy, and why is it important for numerical computing in Python?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Discuss the concept of 'contiguous memory allocation' and its importance for arrays.Discuss the concept of 'contiguous memory allocation' and its importance for arrays.May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.