Running code...
Python Code
Output
Code Example
Here's a simple example of using NumPy, PIL, and SciPy in the browser with Pyodide. The code loads an image from a URL, performs edge detection using convolution, and displays the result.
Click the Run Code button to execute the Python code and see the output below.
from PIL import Image
import numpy as np
from scipy.ndimage import convolve
from js import fetch
from io import BytesIO
import asyncio
import base64
from js import fetch, document
KERNEL_Y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
KERNEL_X = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
async def load_image(url="https://dorpascal.com/favicon.png"):
# Fetch the image from the URL
response = await fetch(url)
array_buffer = await response.arrayBuffer()
binary_data = BytesIO(bytes(array_buffer.to_py())) # Convert to a BytesIO object for PIL
# Open the image using PIL
img = Image.open(binary_data)
print(f"Loaded image: {img.format}, {img.size}, {img.mode}")
return np.array(img)
def edge_detection(image_array):
gray_image = np.mean(image_array, axis=2) # Convert to grayscale
edgeY = convolve(gray_image, KERNEL_Y, mode='constant', cval=0.0)
edgeX = convolve(gray_image, KERNEL_X, mode='constant', cval=0.0)
edgeMAG = np.sqrt(edgeX**2 + edgeY**2)
return edgeMAG
async def main():
url = "https://raw.githubusercontent.com/yotam-biu/ps12/refs/heads/main/.tests/lena.jpg"
image = await load_image(url) # Await the image loading
edges = edge_detection(image)
print(f"Edge-detected image shape: {edges.shape}")
img = Image.fromarray((edges / edges.max() * 255).astype(np.uint8)) # Normalize to 0-255 and convert to uint8
# Convert RGBA to RGB if needed
if img.mode == "RGBA":
img = img.convert("RGB")
# Save the image to a BytesIO object in JPEG format
output_buffer = BytesIO()
img.save(output_buffer, format="JPEG", quality=95)
output_buffer.seek(0)
# Convert the image data to base64
base64_data = base64.b64encode(output_buffer.read()).decode('utf-8')
data_url = f"data:image/jpeg;base64,{base64_data}"
# Create a download link element
link = document.querySelector("#cta1")
link.href = data_url
link.download = "edges.jpg"
document.querySelector("#cta1").textContent = "Download Image"
print("Base64 download link created. Click the link to download the image.")
# Run the async main function in Pyodide
main()