### Installation de bibliothèques pour GDAL et rioxarray Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/02-RehaussementVisualisationImages.html Installation des paquets GDAL nécessaires pour le traitement d'images géospatiales dans Google Colab. Ces commandes mettent à jour la liste des paquets disponibles et installent GDAL ainsi que ses en-têtes de développement. ```bash %%capture !apt-get update !apt-get install gdal-bin libgdal-dev ``` -------------------------------- ### Installation des Librairies pour le Traitement d'Images en Python Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/notebooks/04-TransformationSpatiales.ipynb Installe les librairies Python nécessaires pour le traitement d'images et l'analyse spatiale, incluant matplotlib, rioxarray, xrscipy, et scikit-image. La commande `%%capture` est utilisée pour supprimer la sortie détaillée de l'installation. ```python %%capture !pip install -qU matplotlib rioxarray xrscipy scikit-image ``` -------------------------------- ### Activer un environnement virtuel Conda Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/00-PriseEnMainPython.html Cette commande permet d'activer l'environnement virtuel nommé 'test' précédemment créé. Une fois activé, les commandes Python et les installations de paquets seront confinées à cet environnement. ```bash conda activate test ``` -------------------------------- ### Compute and Visualize Spectral Indices in Python Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/03-TransformationSpectrales.html This Python script uses pandas to filter a GeoDataFrame, spyndex to compute spectral indices like NDVI, NDWI, and NDBI, and seaborn for pairplot visualization. It requires pandas, spyndex, and matplotlib to be installed. Inputs are a GeoDataFrame with spectral bands and class information, and outputs are computed indices and a visualized pairplot. ```python class_selected= [1,3,9] df= pd.concat([gdf[gdf['class'] ==c] for c in class_selected], ignore_index=True) # Compute the desired spectral indices idx = spyndex.computeIndex( index = ["NDVI","NDWI","NDBI"], params = { "N": df["N"], "R": df["R"], "G": df["G"], "S1": df["S1"] } ) idx["Land Cover"] = [nom_classes[l] for l in df["class"].tolist()] # Add Land Cover to DataFrame colors= [couleurs_classes[c] for c in class_selected] # Plot a pairplot to check the indices behaviour plt.figure(figsize = (15,15)) g = sns.PairGrid(idx,hue = "Land Cover",palette = sns.color_palette(colors)) g.map_lower(sns.scatterplot) g.map_upper(sns.kdeplot,fill = True,alpha = .5) g.map_diag(sns.kdeplot,fill = True) g.add_legend() plt.show() ``` -------------------------------- ### JavaScript Code Annotation Selection Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/01-ImportationManipulationImages.html This JavaScript code defines functions to select and highlight specific lines or blocks of code based on annotation data attributes. It's designed to work with HTML elements that have `data-code-cell` and `data-code-annotation` attributes, likely for interactive code examples. ```javascript let selectedAnnoteEl; const selectorForAnnotation = ( cell, annotation) => { let cellAttr = 'data-code-cell="' + cell + '"'; let lineAttr = 'data-code-annotation="' + annotation + '"'; const selector = 'span[' + cellAttr + '][' + lineAttr + ']'; return selector; } const selectCodeLines = (annoteEl) => { const doc = window.document; const targetCell = annoteEl.getAttribute("data-target-cell"); const targetAnnotation = annoteEl.getAttribute("data-target-annotation"); const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation)); const lines = annoteSpan.getAttribute("data-code-lines").split(","); const lineIds = lines.map((line) => { return targetCell + "-" + line; }) let top = null; let height = null; let parent = null; if (lineIds.length > 0) { //compute the position of the single el (top and bottom and make a div) const el = window.document.getElementById(lineIds[0]); top = el.offsetTop; height = el.offsetHeight; parent = el.parentElement.parentElement; if (lineIds.length > 1) { const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]); const bottom = lastEl.offsetTop + lastEl.offsetHeight; height = bottom - top } } ``` -------------------------------- ### Tippy.js Tooltip Initialization (JavaScript) Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/references.html Cette fonction utilise la bibliothèque Tippy.js pour créer des tooltips interactifs. Elle configure diverses options pour les tooltips, telles que le contenu HTML, le délai d'apparition, le placement et le thème. Elle est utilisée pour afficher des informations contextuelles, notamment pour les références de notes de bas de page. ```javascript function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) { const config = { allowHTML: true, maxWidth: 500, delay: 100, arrow: false, appendTo: function(el) { return el.parentElement; }, interactive: true, interactiveBorder: 10, theme: 'quarto', placement: 'bottom-start', }; if (contentFn) { config.content = contentFn; } if (onTriggerFn) { config.onTrigger = onTriggerFn; } if (onUntriggerFn) { config.onUntrigger = onUntriggerFn; } window.tippy(el, config); } const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]'); for (var i=0; i { let cellAttr = 'data-code-cell="' + cell + '"'; let line ``` -------------------------------- ### Vérifier la version de Python Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/00-PriseEnMainPython.html Cette commande permet de vérifier la version de Python installée sur votre système via le terminal. Elle est utile pour s'assurer que l'installation s'est déroulée correctement. ```bash python --version ``` -------------------------------- ### Tippy.js Tooltip Initialization (JavaScript) Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/00-auteurs.html This function `tippyHover` sets up tooltips using the Tippy.js library. It configures options such as allowing HTML content, setting a maximum width, delay, and placement. It accepts optional functions for content generation and trigger/untrigger events. ```javascript function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) { const config = { allowHTML: true, maxWidth: 500, delay: 100, arrow: false, appendTo: function(el) { return el.parentElement; }, interactive: true, interactiveBorder: 10, theme: 'quarto', placement: 'bottom-start', }; if (contentFn) { config.content = contentFn; } if (onTriggerFn) { config.onTrigger = onTriggerFn; } if (onUntriggerFn) { config.onUntrigger = onUntriggerFn; } window.tippy(el, config); } ``` -------------------------------- ### Cross-Reference Tooltip with Dynamic Loading (JavaScript) Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/00-auteurs.html This snippet selects elements with the class `quarto-xref`. For each, it sets up a `tippyHover` tooltip. When triggered, it attempts to find the cross-reference target by URL hash. If not found locally, it fetches the content from the URL, parses it, extracts the target element, and renders it using `processXRef`. It also handles cases where the URL might point to a full page. ```javascript const xrefs = window.document.querySelectorAll('a.quarto-xref'); for (var i=0; i res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.getElementById(id); if (note !== null) { const html = processXRef(id, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } } else { // See if we can fetch a full url (with no hash to target) // This is a special case and we should probably do some content thinning / targeting fetch(url) .then(res => res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.querySelector('main.content'); if (note !== null) { // This should only happen for chapter cross references // (since there is no id in the URL) // remove the first header if (note.children.length > 0 && note.children[0].tagName === "HEADER") { note.children[0].remove(); } const html = processXRef(null, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } }, function(instance) { }); } ``` -------------------------------- ### Rechercher les versions de Python disponibles avec Conda Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/00-PriseEnMainPython.html Cette commande liste toutes les versions de Python disponibles pour l'installation via Conda. Elle est utile pour choisir la version appropriée lors de la création d'un environnement virtuel. ```bash conda search --full-name python ``` -------------------------------- ### Process Special Sections in DOM (JavaScript) Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/index.html This JavaScript function, `stripColumnClz`, processes DOM elements within a given note. It handles special cases for sections identified by an ID that is null or starts with 'sec-'. For these sections, it selectively appends child elements to a container, potentially skipping empty paragraphs. It also calls `window.Quarto?.typesetMath` for mathematical typesetting if available. For other elements, it removes anchor links and performs similar typesetting. ```JavaScript function stripColumnClz(el) { for (const child of el.children) { stripColumnClz(child); } } stripColumnClz(note) { if (id === null || id.startsWith('sec-')) { // Special case sections, only their first couple elements const container = document.createElement("div"); if (note.children && note.children.length > 2) { container.appendChild(note.children[0].cloneNode(true)); for (let i = 1; i < note.children.length; i++) { const child = note.children[i]; if (child.tagName === "P" && child.innerText === "") { continue; } else { container.appendChild(child.cloneNode(true)); break; } } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(container); } return container.innerHTML } else { if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } return note.innerHTML; } } else { // Remove any anchor links if they are present const anchorLink = note.querySelector('a.anchorjs-link'); if (anchorLink) { anchorLink.remove(); } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } if (note.classList.contains("callout")) { return note.outerHTML; } else { return note.innerHTML; } } } ``` -------------------------------- ### JavaScript: Initialize Tooltips with tippy.js Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/04-TransformationSpatiales.html This function `tippyHover` sets up tooltips using the tippy.js library. It allows for custom content, trigger, and untrigger functions, along with various configuration options like `allowHTML`, `maxWidth`, `delay`, and `placement`. It's used to enhance user experience by providing contextual information on hover. ```javascript function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) { const config = { allowHTML: true, maxWidth: 500, delay: 100, arrow: false, appendTo: function(el) { return el.parentElement; }, interactive: true, interactiveBorder: 10, theme: 'quarto', placement: 'bottom-start', }; if (contentFn) { config.content = contentFn; } if (onTriggerFn) { config.onTrigger = onTriggerFn; } if (onUntriggerFn) { config.onUntrigger = onUntriggerFn; } window.tippy(el, config); } ``` -------------------------------- ### Process Cross-References with Tooltips and Fetching (JavaScript) Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/index.html This snippet handles cross-references (xrefs) by displaying their content in a tooltip. It attempts to find the target element by ID, and if not found, it fetches the content from the URL. It supports both internal and external URLs and processes the fetched content before displaying it. Dependencies include a `tippyHover` function and a `processXRef` function. ```JavaScript for (var i=0; i res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.getElementById(id); if (note !== null) { const html = processXRef(id, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } } else { // See if we can fetch a full url (with no hash to target) // This is a special case and we should probably do some content thinning / targeting fetch(url) .then(res => res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.querySelector('main.content'); if (note !== null) { // This should only happen for chapter cross references // (since there is no id in the URL) // remove the first header if (note.children.length > 0 && note.children[0].tagName === "HEADER") { note.children[0].remove(); } const html = processXRef(null, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } }, function(instance) {}); } ``` -------------------------------- ### JavaScript: Render Callouts and Math with Quarto Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/references.html Renders content blocks, particularly those identified as 'callouts', and integrates with Quarto's mathematical typesetting capabilities. It includes logic to clone and append content to a container, process mathematical expressions, and return the generated HTML. ```javascript if (ren.length > 2) { container.appendChild(note.children[0].cloneNode(true)); for (let i = 1; i < note.children.length; i++) { const child = note.children[i]; if (child.tagName === "P" && child.innerText === "") { continue; } else { container.appendChild(child.cloneNode(true)); break; } } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(container); } return container.innerHTML; } else { if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } return note.innerHTML; } } else { // Remove any anchor links if they are present const anchorLink = note.querySelector('a.anchorjs-link'); if (anchorLink) { anchorLink.remove(); } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } if (note.classList.contains("callout")) { return note.outerHTML; } else { return note.innerHTML; } } ``` -------------------------------- ### JavaScript Tooltip Functionality Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/01-ImportationManipulationImages.html This snippet defines a `tippyHover` function to initialize tooltips on elements. It handles custom content functions, trigger events, and themes, leveraging the 'tippy.js' library. It's used for footnotes and cross-references. ```javascript const tippyHover = (el, contentFn, onTriggerFn, onUntriggerFn) => { const config = { allowHTML: true, animation: 'scale', delay: 200, trigger: 'mouseenter focus', content: el => el.parentElement.n(el) || el.parentElement, interactive: true, interactiveBorder: 10, theme: 'quarto', placement: 'bottom-start' }; if (contentFn) { config.content = contentFn; } if (onTriggerFn) { config.onTrigger = onTriggerFn; } if (onUntriggerFn) { config.onUntrigger = onUntriggerFn; } window.tippy(el, config); } ``` -------------------------------- ### Importations de bibliothèques pour le traitement d'images en Python Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/02-RehaussementVisualisationImages.html Importe les bibliothèques nécessaires pour la manipulation et la visualisation d'images en Python. Ces bibliothèques incluent NumPy pour les opérations numériques, rioxarray et xarray pour la manipulation de données multidimensionnelles géospatiales, scipy.signal pour les opérations de signal, et matplotlib.pyplot pour la visualisation. ```python import numpy as np import rioxarray as rxr from scipy import signal import xarray as xr import xrscipy import matplotlib.pyplot as plt ``` -------------------------------- ### JavaScript for Cross-Reference Tooltips and Content Loading Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/02-RehaussementVisualisationImages.html This code handles tooltips for cross-references ('a.quarto-xref'). It uses 'tippyHover' to display content dynamically loaded from other parts of the document or external URLs. It includes logic to process and sanitize the content before displaying it, especially for sections and callouts. ```javascript const xrefs = window.document.querySelectorAll('a.quarto-xref'); const processXRef = (id, note) => { // Strip column container classes const stripColumnClz = (el) => { el.classList.remove("page-full", "page-columns"); if (el.children) { for (const child of el.children) { stripColumnClz(child); } } } stripColumnClz(note) if (id === null || id.startsWith('sec-')) { // Special case sections, only their first couple elements const container = document.createElement("div"); if (note.children && note.children.length > 2) { container.appendChild(note.children[0].cloneNode(true)); for (let i = 1; i < note.children.length; i++) { const child = note.children[i]; if (child.tagName === "P" && child.innerText === "") { continue; } else { container.appendChild(child.cloneNode(true)); break; } } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(container); } return container.innerHTML } else { if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } return note.innerHTML; } } else { // Remove any anchor links if they are present const anchorLink = note.querySelector('a.anchorjs-link'); if (anchorLink) { anchorLink.remove(); } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } if (note.classList.contains("callout")) { return note.outerHTML; } else { return note.innerHTML; } } } for (var i=0; i res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.getElementById(id); if (note !== null) { const html = processXRef(id, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } } else { // See if we can fetch a full url (with no hash to target) // This is a special case and we should probably do some content thinning / targeting fetch(url) .then(res => res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.querySelector('main.content'); if (note !== null) { // This should only happen for chapter cross references // (since there is no id in the URL) // remove the first header if (note.children.length > 0 && note.children[0].tagName === "HEADER") { note.children[0].remove(); } const html = processXRef(null, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } }, function(instance) { }); } ``` -------------------------------- ### Créer un environnement virtuel avec Conda Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/00-PriseEnMainPython.html Utilise la commande `conda` pour créer un nouvel environnement virtuel nommé 'test' avec une version spécifique de Python (ici 3.11). Ceci est essentiel pour isoler les dépendances de projet. ```bash conda create --name test python=3.11 ``` -------------------------------- ### Obtenir les Statistiques d'une Image avec gdalinfo Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/notebooks/02-RehaussementVisualisationImages.ipynb Commande en ligne de commande pour interroger rapidement un fichier image (ex: landsat7.tif) et obtenir ses statistiques univariées de base, telles que les valeurs minimales, maximales, moyennes, l'écart-type, etc. ```bash !gdalinfo -stats landsat7.tif ``` -------------------------------- ### Create and Render Interactive Quiz Source: https://context7.com/sfoucher/traitementimagespythonvol1/llms.txt Defines an interactive quiz structure using YAML, saves it to a file, and then loads and renders the quiz using a custom `Quiz` class and `render_quizz` function. This system supports automatic grading. Dependencies include PyYAML and custom modules. ```python import yaml from code_complementaire.quizz_functions import Quiz, render_quizz # Create quiz YAML file (quiz_example.yml) quiz_yaml = """ - label: "What is the typical range of NDVI values?" type: uc response: 2 answers: - "0 to 100" - "-1 to 1" - "0 to 255" - "-100 to 100" help: "NDVI uses normalized difference, resulting in values between -1 and 1" - label: "Which bands are used to calculate NDVI?" type: mc response: [2, 3] answers: - "Blue and Green" - "Red" - "Near-Infrared" - "Thermal" help: "NDVI = (NIR - Red) / (NIR + Red)" - label: "What does high NDVI indicate?" type: stat response: "healthy vegetation" help: "Higher NDVI values indicate more chlorophyll and healthier vegetation" """ # Save YAML file with open('quiz_example.yml', 'w') as f: f.write(quiz_yaml) # Load and render quiz quiz = Quiz('quiz_example.yml', quizz_id='quiz_01') render_quizz(quiz) # Renders HTML or PDF based on output format ``` -------------------------------- ### Obtenir les Statistiques d'une Image avec rasterio Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/notebooks/02-RehaussementVisualisationImages.ipynb Utilise la librairie rasterio pour ouvrir un fichier image et calculer ses statistiques de base. La fonction 'stats()' retourne un dictionnaire contenant les valeurs minimales, maximales, moyennes et l'écart-type pour chaque bande. ```python #| eval: false import rasterio as rio import numpy as np with rio.open('landsat7.tif') as src: stats= src.stats() print(stats) ``` -------------------------------- ### Téléchargement des images pour le traitement Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/04-TransformationSpatiales.html Télécharge des fichiers image depuis Google Drive en utilisant la bibliothèque `gdown`. Les images téléchargées incluent des formats tels que '.tif' et '.jpg', destinés à être utilisés dans les exemples de traitement d'images du notebook. ```python %%capture import gdown gdown.download('https://drive.google.com/uc?export=download&confirm=pbef&id=1a6Ypg0g1Oy4AJt9XWKWfnR12NW1XhNg_', output= 'RGBNIR_of_S2A.tif') gdown.download('https://drive.google.com/uc?export=download&confirm=pbef&id=1a4PQ68Ru8zBphbQ22j0sgJ4D2quw-Wo6', output= 'landsat7.tif') gdown.download('https://drive.google.com/uc?export=download&confirm=pbef&id=1_zwCLN-x7XJcNHJCH6Z8upEdUXtVtvs1', output= 'berkeley.jpg') gdown.download('https://drive.google.com/uc?export=download&confirm=pbef&id=1dM6IVqjba6GHwTLmI7CpX8GP2z5txUq6', output= 'SAR.tif') ``` -------------------------------- ### Quarto Math Typesetting and Callout Handling in JavaScript Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/04-TransformationSpatiales.html This JavaScript code snippet handles content processing, specifically focusing on mathematical typesetting using Quarto's `typesetMath` function and managing callout elements. It includes logic for cloning and appending nodes, identifying and skipping empty paragraph elements, and returning HTML content for processed notes. ```javascript if (ren.length > 2) { container.appendChild(note.children[0].cloneNode(true)); for (let i = 1; i < note.children.length; i++) { const child = note.children[i]; if (child.tagName === "P" && child.innerText === "") { continue; } else { container.appendChild(child.cloneNode(true)); break; } } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(container); } return container.innerHTML } else { if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } return note.innerHTML; } } else { // Remove any anchor links if they are present const anchorLink = note.querySelector('a.anchorjs-link'); if (anchorLink) { anchorLink.remove(); } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } if (note.classList.contains("callout")) { return note.outerHTML; } else { return note.innerHTML; } } ``` -------------------------------- ### Lecture et Affichage d'Images Géospatiales en Python Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/notebooks/04-TransformationSpatiales.ipynb Ouvre et affiche des informations sur différents fichiers images géospatiales (Berkeley.jpg, RGBNIR_of_S2A.tif, SAR.tif) en utilisant la librairie `rioxarray`. Ceci permet de vérifier que les images ont été correctement téléchargées et peuvent être lues par le système. ```python #| output: false with rxr.open_rasterio('berkeley.jpg', mask_and_scale= True) as img_rgb: print(img_rgb) with rxr.open_rasterio('RGBNIR_of_S2A.tif', mask_and_scale= True) as img_rgbnir: print(img_rgbnir) with rxr.open_rasterio('SAR.tif', mask_and_scale= True) as img_SAR: print(img_SAR) ``` -------------------------------- ### Créer et activer un environnement virtuel avec Conda (Exemple) Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/00-PriseEnMainPython.html Il s'agit d'une procédure en deux étapes pour créer un environnement virtuel nommé 'test' avec Python 3.10 en utilisant Conda, puis l'activer pour l'utiliser. ```bash conda env -n test python=3.10 conda activate test ``` -------------------------------- ### JavaScript Cross-Reference Processing and Tooltip Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/01-ImportationManipulationImages.html This snippet processes elements with the class 'quarto-xref' to enable interactive tooltips for cross-references. It includes logic to fetch content from external URLs if the target is not found locally, and formats the content for display. It also handles special formatting for section-based references. ```javascript const xrefs = window.document.querySelectorAll('a.quarto-xref'); const processXRef = (id, note) => { // Strip column container classes const stripColumnClz = (el) => { el.classList.remove("page-full", "page-columns"); if (el.children) { for (const child of el.children) { stripColumnClz(child); } } } stripColumnClz(note) if (id === null || id.startsWith('sec-')) { // Special case sections, only their first couple elements const container = document.createElement("div"); if (note.children && note.children.length > 2) { container.appendChild(note.children[0].cloneNode(true)); for (let i = 1; i < note.children.length; i++) { const child = note.children[i]; if (child.tagName === "P" && child.innerText === "") { continue; } else { container.appendChild(child.cloneNode(true)); break; } } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(container); } return container.innerHTML } else { if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } return note.innerHTML; } } else { // Remove any anchor links if they are present const anchorLink = note.querySelector('a.anchorjs-link'); if (anchorLink) { anchorLink.remove(); } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } if (note.classList.contains("callout")) { return note.outerHTML; } else { return note.innerHTML; } } } for (var i=0; i res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.getElementById(id); if (note !== null) { const html = processXRef(id, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } } else { // See if we can fetch a full url (with no hash to target) // This is a special case and we should probably do some content thinning / targeting fetch(url) .then(res => res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.querySelector('main.content'); if (note !== null) { // This should only happen for chapter cross references // (since there is no id in the URL) // remove the first header if if (note.children.length > 0 && note.children[0].tagName === "HEADER") { note.children[0].remove(); } const html = processXRef(null, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } }, function(instance) { }); } ``` -------------------------------- ### Supervised Classification with K-Nearest Neighbors in Python Source: https://context7.com/sfoucher/traitementimagespythonvol1/llms.txt Implements supervised land cover classification using the K-Nearest Neighbors (K-NN) algorithm. Requires scikit-learn, numpy, rioxarray, geopandas, pandas, and matplotlib. It involves loading multi-spectral imagery and training data (sampling points) to train a K-NN classifier. ```python from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix import numpy as np import rioxarray as rxr import geopandas as gpd import pandas as pd import matplotlib.pyplot as plt # Load multi-spectral image img = rxr.open_rasterio('RGBNIR_of_S2A.tif', mask_and_scale=True) # Load training points (e.g., from a shapefile or CSV) training_data = pd.read_csv('sampling_points.csv') # Assume columns: 'x', 'y', 'class_id' ``` -------------------------------- ### Compute Spectral Indices with spyndex (Python) Source: https://context7.com/sfoucher/traitementimagespythonvol1/llms.txt Illustrates the use of the spyndex library to calculate various spectral indices like NDVI, EVI, and SAVI from multi-spectral satellite imagery. It requires a dictionary of bands as input and can compute single or multiple indices. ```Python import spyndex import xarray as xr import rioxarray as rxr import numpy as np # Load multi-spectral image (e.g., Sentinel-2) img = rxr.open_rasterio('RGBNIR_of_S2A.tif', mask_and_scale=True) # Prepare band dictionary for spyndex bands_dict = { 'R': img.sel(band=1), # Red band 'G': img.sel(band=2), # Green band 'B': img.sel(band=3), # Blue band 'N': img.sel(band=4) # NIR band } # Calculate NDVI (Normalized Difference Vegetation Index) ndvi = spyndex.computeIndex(index='NDVI', params=bands_dict) # Calculate multiple indices at once indices = spyndex.computeIndex( index=['NDVI', 'EVI', 'SAVI'], params=bands_dict ) # List all available indices available_indices = spyndex.indices print(f"Total available indices: {len(available_indices)}") ``` -------------------------------- ### JavaScript: Process Cross-References and Fetch Content Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/references.html Handles cross-references by fetching content from URLs, parsing HTML, and extracting specific elements. It supports both internal and external links, including those with hash fragments. It also includes logic to fetch and display content from full URLs without hashes. ```javascript for (var i=0; i res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.getElementById(id); if (note !== null) { const html = processXRef(id, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } } else { // See if we can fetch a full url (with no hash to target) // This is a special case and we should probably do some content thinning / targeting fetch(url) .then(res => res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.querySelector('main.content'); if (note !== null) { // This should only happen for chapter cross references // (since there is no id in the URL) // remove the first header if (note.children.length > 0 && note.children[0].tagName === "HEADER") { note.children[0].remove(); } const html = processXRef(null, note); instance.setContent(html); }).finally(() => { instance.enable(); instance.show(); }); } }, function(instance) { }); } ``` -------------------------------- ### Create Composite Color Visualizations Source: https://context7.com/sfoucher/traitementimagespythonvol1/llms.txt Loads a multi-spectral image using Rioxarray, extracts individual bands, normalizes them, and creates both true color (RGB) and false color infrared (NIR-R-G) composites for visualization. Dependencies include NumPy, Matplotlib, and Rioxarray. ```python import numpy as np import matplotlib.pyplot as plt import rioxarray as rxr # Load multi-spectral image img = rxr.open_rasterio('RGBNIR_of_S2A.tif', mask_and_scale=True) # Extract bands red = img.sel(band=1).values green = img.sel(band=2).values blue = img.sel(band=3).values nir = img.sel(band=4).values # Function to normalize bands for visualization def normalize_band(band, percentile_clip=(2, 98)): vmin, vmax = np.percentile(band, percentile_clip) band_normalized = (band - vmin) / (vmax - vmin) return np.clip(band_normalized, 0, 1) # Create different composite types # True color (RGB) true_color = np.dstack([ normalize_band(red), normalize_band(green), normalize_band(blue) ]) # False color infrared (NIR-R-G) false_color_ir = np.dstack([ normalize_band(nir), normalize_band(red), normalize_band(green) ]) # To display these composites, you would typically use matplotlib: # plt.figure(figsize=(10, 8)) # plt.imshow(true_color) # plt.title('True Color Composite') # plt.show() # plt.figure(figsize=(10, 8)) # plt.imshow(false_color_ir) # plt.title('False Color Infrared Composite') # plt.show() ``` -------------------------------- ### JavaScript Footnote Tooltip Initialization Source: https://github.com/sfoucher/traitementimagespythonvol1/blob/main/docs/01-ImportationManipulationImages.html This code selects all footnote reference links and applies `tippyHover` to display footnote content in a tooltip. It extracts the footnote ID from the `href` or `data-footnote-href` attribute and retrieves the corresponding element's HTML content. ```javascript const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]'); for (var i=0; i