Represent images as arrays, slice regions of interest, apply element-wise transforms, transpose channels, and build convolution filters.
Images are naturally represented as multi-dimensional arrays. A grayscale image is a 2-D array of pixel intensities, while a color image is a 3-D array with a channel dimension. numpy-ts provides the array operations needed for common image processing tasks.
Representing images as 2D/3D arrays
Slicing regions of interest
Extract sub-images using NumPy-style slicing.
Element-wise transforms: brightness and contrast
Adjust pixel values using vectorized arithmetic — no loops required.
Reshaping and transposing for channel reordering
Different frameworks expect different axis orderings. Use transpose and reshape to convert between them.
Simple convolution filter
Apply spatial filters to images using convolution. For a 2-D image, convolve each row and column separately using 1-D convolution, or build a simple approach using element-wise operations.
For large-scale 2-D convolution, consider using the FFT approach: pad the image and kernel to the same size, multiply their FFTs, and inverse-transform the result. This runs in O(N log N) instead of O(N * K).
{"docsConfig":{"theme":"mint","$schema":"https://mintlify.com/docs.json","name":"numpy-ts","description":"Complete NumPy implementation for TypeScript and JavaScript","colors":{"primary":"#3179C7","light":"#3179C7","dark":"#3179C7"},"logo":{"light":"https://mintcdn.com/none-4568e96a/TklIwzPdQ8Sv_cxD/images/logo-light.svg?fit=max\u0026auto=format\u0026n=TklIwzPdQ8Sv_cxD\u0026q=85\u0026s=85a09d3e9971808ec73bf6e2eddcb989","dark":"https://mintcdn.com/none-4568e96a/TklIwzPdQ8Sv_cxD/images/logo-dark.svg?fit=max\u0026auto=format\u0026n=TklIwzPdQ8Sv_cxD\u0026q=85\u0026s=57584fb2637b84d53a79c187e3242f72"},"favicon":"https://mintcdn.com/none-4568e96a/TklIwzPdQ8Sv_cxD/images/favicon.svg?fit=max\u0026auto=format\u0026n=TklIwzPdQ8Sv_cxD\u0026q=85\u0026s=1a1b3c01a14ea06742777b11c71d0a7e","navbar":{"links":[{"href":"https://github.com/dupontcyborg/numpy-ts","type":"github"}]},"footer":{"socials":{"github":"https://github.com/dupontcyborg/numpy-ts","linkedin":"https://linkedin.com/in/cyborgnico","earth-americas":"https://www.cyborg.co/?ref=numpyts.dev"}},"seo":{"metatags":{"canonical":"https://numpyts.dev"}},"integrations":{"plausible":{"domain":"numpyts.dev","server":"d1w0psmo3bkh8z.cloudfront.net"}},"contextual":{"options":["copy","view","chatgpt","claude","cursor","vscode"],"display":"header"},"styling":{"latex":true},"navigation":{"pages":[]}},"deployment":{"deploymentMetadataValue":{"subdomain":"none-4568e96a","hasAudioNarration":false,"actualSubdomain":"none-4568e96a","customDomains":["numpyts.dev"],"gitSource":{"type":"github","owner":"dupontcyborg","repo":"numpy-ts","deployBranch":"main","contentDirectory":"docs","isPrivate":true,"mountPath":"","label":""},"entitlements":{"AI_CHAT":{"status":"ENABLED"},"WEB_MCP":{"status":"ENABLED"},"NARRATION":{"status":"ENABLED"}},"buildId":"6afb517dee0aa4defa1db962","clientVersion":"0.0.4270","searchFilterCounts":[{"language":"default","tag":"API Reference","count":477},{"language":"default","tag":"Guides","count":226},{"language":"default","tag":"Examples","count":126},{"language":"default","tag":"Array Manipulation","count":54},{"language":"default","tag":"Math","count":54},{"language":"default","tag":"Reductions \u0026 Statistics","count":45},{"language":"default","tag":"Array Creation","count":36},{"language":"default","tag":"Linear Algebra","count":36},{"language":"default","tag":"Logic \u0026 Comparison","count":36},{"language":"default","tag":"Random (np.random)","count":36}]},"assistantConfig":{"enableAskAiButton":false,"enableStarterQuestions":false,"enableAskAiSearchBar":true},"basePath":"","hasChatPermissions":true,"hasWebMcpPermissions":true,"toggles":[{"name":"kill-isr","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"custom-rbac-roles","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"agent-mintlify-slack","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"agent-integrations-settings","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"rbac-expansion","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"automations-pr-grouping","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"custom-prefix","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"analytics-v7","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"user-flows-analytics","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"no-publish-flow","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-onboarding","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"snapshot-serving-live","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"stripTemperatureMiddleware","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"support-platform-pylon-zendesk","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"snapshot-serving","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"instant-rollback","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"granular-notifications-server","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"granular-notifications","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"automations-fable","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"fixed-ai-action-pricing","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"site-roles","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"automation-resolve-merge-conflict","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"scoped-publishing","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"mintql","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"page-level-analytics","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"editor-version-history-v2","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"billing-page-v2","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"full-page-search","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workspace-projects","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"assistant-v5","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"fork-pr-previews","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"revalidation-jwt","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-sso-scim","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"hobby-abuse-scan","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"dashboard-inbox","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-signup","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"turbopuffer-dual-write","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"workos-enabled","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"approve-review-flow","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"editor-metadata","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"sso-setup-deadline-banner","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"turbopuffer-serve","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"live-agents","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"starter-pricing","enabled":true,"variant":{"name":"treatment","enabled":true,"payload":{"type":"string","value":"treatment"},"feature_enabled":true},"impressionData":false},{"name":"llms-txt-v2","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false},{"name":"wildcard-email-auth","enabled":true,"variant":{"name":"disabled","enabled":false,"feature_enabled":true},"impressionData":false}],"googleFontsInlined":false},"customCss":[{"filePath":"style.css","content":"div[class*=\"mt-8\"][class*=\"lg:mt-0\"][class*=\"flex\"][class*=\"xl:hidden\"]{display:none!important}.chat-assistant-floating-input{visibility:hidden!important;pointer-events:none!important}"}]}
{"page":{"pagePath":"v1.7.x/examples/image-processing","slug":"/v1.7.x/examples/image-processing","pageMetadata":{"title":"Image Processing","description":"Represent images as arrays, slice regions of interest, apply element-wise transforms, transpose channels, and build convolution filters.","canonical":"https://numpyts.dev/latest/examples/image-processing","href":"/v1.7.x/examples/image-processing"},"description":{"compiledSource":"\"use strict\";\nconst {jsx: _jsx} = arguments[0];\nconst {useMDXComponents: _provideComponents} = arguments[0];\nfunction _createMdxContent(props) {\n const _components = {\n p: \"p\",\n ..._provideComponents(),\n ...props.components\n };\n return _jsx(_components.p, {\n children: \"Represent images as arrays, slice regions of interest, apply element-wise transforms, transpose channels, and build convolution filters.\"\n });\n}\nfunction MDXContent(props = {}) {\n const {wrapper: MDXLayout} = {\n ..._provideComponents(),\n ...props.components\n };\n return MDXLayout ? _jsx(MDXLayout, {\n ...props,\n children: _jsx(_createMdxContent, {\n ...props\n })\n }) : _createMdxContent(props);\n}\nreturn {\n default: MDXContent\n};\n","frontmatter":{},"scope":{}},"pageType":"default","mdx":{"mdxSource":{"compiledSource":"\"use strict\";const{Fragment:_Fragment,jsx:_jsx,jsxs:_jsxs}=arguments[0];const{useMDXComponents:_provideComponents}=arguments[0];const Playground=({code:singleCode=``,label=``,height=null,startingHeight=null,showImportHeader=false,showCopyButton=false,showTiming=true})=>{const NUMPY_TS_CDN_VERSION=`1.3.0`;const CDN_URLS={numpyTs:`https://cdn.jsdelivr.net/npm/numpy-ts@${NUMPY_TS_CDN_VERSION}/dist/numpy-ts.browser.js`,prismCore:`https://cdn.jsdelivr.net/npm/prismjs@1/prism.min.js`,prismTS:`https://cdn.jsdelivr.net/npm/prismjs@1/components/prism-typescript.min.js`,prismCSSLight:`https://cdn.jsdelivr.net/npm/prismjs@1/themes/prism.min.css`,prismCSSDark:`https://cdn.jsdelivr.net/npm/prismjs@1/themes/prism-tomorrow.min.css`};const SHARED_FONT={fontFamily:`'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace`,fontSize:`13px`,lineHeight:`1.5`,tabSize:2};const THEME_COLORS={light:{editorBg:`#f5f5f5`,editorText:`#24292e`,editorBorder:`#d1d5da`,toolbarBg:`#ffffff`,outputBg:`#fafbfc`,outputText:`#24292e`,selectBg:`#ffffff`,selectText:`#24292e`,selectBorder:`#d1d5da`,caretColor:`#000000`,placeholderText:`#6a737d`,resizeHandleBg:`#d1d5da`,resizeHandleHoverBg:`#959da5`},dark:{editorBg:`#1e1e1e`,editorText:`#d4d4d4`,editorBorder:`#333333`,toolbarBg:`#161616`,outputBg:`#1a1a1a`,outputText:`#d4d4d4`,selectBg:`#2a2a2a`,selectText:`#cccccc`,selectBorder:`#444444`,caretColor:`#ffffff`,placeholderText:`#666666`,resizeHandleBg:`#333333`,resizeHandleHoverBg:`#555555`}};const BASE_MIN_HEIGHT=100;const MAX_HEIGHT=800;const IMPORT_HEADER_TEXT=`import * as np from 'numpy-ts';\\n\\n`;const parseHeightPx=value=>{if(value==null)return null;if(typeof value===`number`\u0026\u0026Number.isFinite(value))return value;if(typeof value===`string`){const parsed=parseFloat(value);if(Number.isFinite(parsed))return parsed}return null};const minHeightPx=BASE_MIN_HEIGHT;const clampHeight=h=>Math.max(minHeightPx,Math.min(MAX_HEIGHT,h));const estimateSingleCodeHeight=(script,includeImportHeader)=>{const normalized=(script||``).replace(/\\r\\n/g,`\n`);const lineCount=normalized.length>0?normalized.split(`\n`).length:1;const fontSizePx=parseFloat(SHARED_FONT.fontSize)||13;const lineHeightRaw=parseFloat(SHARED_FONT.lineHeight);const lineHeightPx=(Number.isFinite(lineHeightRaw)?lineHeightRaw:1.5)*fontSizePx;const topPadding=includeImportHeader?16+3*fontSizePx:16;const bottomPadding=16;return Math.ceil(topPadding+bottomPadding+lineCount*lineHeightPx+4)};function loadScript(src){return new Promise((resolve,reject)=>{const existing=document.querySelector(`script[src=\"${src}\"]`);if(existing){if(existing.dataset.loaded===`true`){resolve();return}existing.addEventListener(`load`,resolve,{once:true});existing.addEventListener(`error`,reject,{once:true});return}const s=document.createElement(`script`);s.src=src;s.onload=()=>{s.dataset.loaded=`true`;resolve()};s.onerror=reject;document.head.appendChild(s)})}function loadCSS(href,removeOldId=null){if(document.querySelector(`link[href=\"${href}\"]`))return;if(removeOldId){const old=document.querySelector(`link[data-prism-theme=\"${removeOldId}\"]`);if(old)old.remove()}const l=document.createElement(`link`);l.rel=`stylesheet`;l.href=href;if(removeOldId)l.setAttribute(`data-prism-theme`,removeOldId);document.head.appendChild(l)}const startHeightPx=parseHeightPx(startingHeight)??parseHeightPx(height);const initialEditorHeight=startHeightPx!=null?clampHeight(startHeightPx):clampHeight(estimateSingleCodeHeight(singleCode,showImportHeader));const[code,setCode]=useState(singleCode);const[output,setOutput]=useState(``);const[loaded,setLoaded]=useState(false);const[loadError,setLoadError]=useState(null);const[running,setRunning]=useState(false);const[isDarkMode,setIsDarkMode]=useState(()=>document.documentElement.classList.contains(`dark`));const[editorHeight,setEditorHeight]=useState(initialEditorHeight);const[isResizing,setIsResizing]=useState(false);const[copied,setCopied]=useState(false);const[timing,setTiming]=useState(null);const[copyHover,setCopyHover]=useState(false);const[scrollbarWidth,setScrollbarWidth]=useState(0);const[toolbarNarrow,setToolbarNarrow]=useState(false);const textareaRef=useRef(null);const preRef=useRef(null);const codeRef=useRef(null);const toolbarRef=useRef(null);const resizeStartY=useRef(null);const resizeStartHeight=useRef(null);const runSeqRef=useRef(0);const npRef=useRef(null);const colors=THEME_COLORS[isDarkMode?`dark`:`light`];const copyTimeoutRef=useRef(null);useEffect(()=>{let cancelled=false;async function load(){try{loadCSS(isDarkMode?CDN_URLS.prismCSSDark:CDN_URLS.prismCSSLight,`prism`);const dynamicImport=new Function(`url`,`return import(url)`);const npModule=await dynamicImport(CDN_URLS.numpyTs);npRef.current=npModule.default??npModule;await loadScript(CDN_URLS.prismCore);await loadScript(CDN_URLS.prismTS);if(!cancelled){console.info(`[Playground] Loaded numpy-ts v${NUMPY_TS_CDN_VERSION} from CDN.`);setLoaded(true)}}catch(e){if(!cancelled)setLoadError(`Failed to load dependencies. Check your connection.`)}}load();return()=>{cancelled=true}},[]);const syncScroll=useCallback(()=>{if(!textareaRef.current||!codeRef.current)return;const ta=textareaRef.current;codeRef.current.style.transform=`translate(${-ta.scrollLeft}px, ${-ta.scrollTop}px)`},[]);useEffect(()=>{const observer=new MutationObserver(()=>{const isDark=document.documentElement.classList.contains(`dark`);setIsDarkMode(isDark);loadCSS(isDark?CDN_URLS.prismCSSDark:CDN_URLS.prismCSSLight,`prism`);if(loaded\u0026\u0026window.Prism){setTimeout(()=>{window.Prism.highlightAll();requestAnimationFrame(syncScroll)},50)}});observer.observe(document.documentElement,{attributes:true,attributeFilter:[`class`]});return()=>observer.disconnect()},[loaded,syncScroll]);useEffect(()=>{if(loaded\u0026\u0026window.Prism){window.Prism.highlightAll();requestAnimationFrame(syncScroll)}},[code,loaded,syncScroll]);const handleScroll=useCallback(()=>{syncScroll()},[syncScroll]);const handleKeyDown=useCallback(e=>{const ta=e.target;const start=ta.selectionStart;const end=ta.selectionEnd;const hasSelection=start!==end;if(e.key===`Tab`){e.preventDefault();const newVal=ta.value.substring(0,start)+` `+ta.value.substring(end);setCode(newVal);requestAnimationFrame(()=>{ta.selectionStart=ta.selectionEnd=start+2});return}if(e.key===`Enter`){e.preventDefault();const lineStart=ta.value.lastIndexOf(`\n`,start-1)+1;const lineTextUpToCursor=ta.value.substring(lineStart,start);const indent=(lineTextUpToCursor.match(/^[ \\t]*/)||[``])[0];const insert=`\\n${indent}`;const newVal=ta.value.substring(0,start)+insert+ta.value.substring(end);const nextPos=start+insert.length;setCode(newVal);requestAnimationFrame(()=>{ta.selectionStart=ta.selectionEnd=nextPos});return}if((e.metaKey||e.ctrlKey)\u0026\u0026!e.shiftKey\u0026\u0026!e.altKey\u0026\u0026e.key.toLowerCase()===`a`){e.preventDefault();ta.focus();ta.selectionStart=0;ta.selectionEnd=ta.value.length;return}if((e.metaKey||e.ctrlKey)\u0026\u0026!e.shiftKey\u0026\u0026!e.altKey\u0026\u0026e.key.toLowerCase()===`c`){e.preventDefault();const prevStart=ta.selectionStart;const prevEnd=ta.selectionEnd;let copyStart=prevStart;let copyEnd=prevEnd;if(!hasSelection){const lineStart=ta.value.lastIndexOf(`\n`,start-1)+1;const lineEndRaw=ta.value.indexOf(`\n`,start);const lineEnd=lineEndRaw===-1?ta.value.length:lineEndRaw;copyStart=lineStart;copyEnd=lineEnd}ta.focus();ta.selectionStart=copyStart;ta.selectionEnd=copyEnd;let copied=false;try{copied=typeof document.execCommand===`function`?document.execCommand(`copy`):false}catch{copied=false}if(!copied\u0026\u0026navigator.clipboard?.writeText){void navigator.clipboard.writeText(ta.value.substring(copyStart,copyEnd)).catch(()=>{})}requestAnimationFrame(()=>{ta.selectionStart=prevStart;ta.selectionEnd=prevEnd});return}if((e.metaKey||e.ctrlKey)\u0026\u0026!e.shiftKey\u0026\u0026!e.altKey\u0026\u0026(e.key===`/`||e.code===`Slash`)){e.preventDefault();const lineStart=ta.value.lastIndexOf(`\n`,start-1)+1;const endForLineCalc=hasSelection\u0026\u0026ta.value[end-1]===`\n`?end-1:end;const lineEndRaw=ta.value.indexOf(`\n`,endForLineCalc);const lineEnd=lineEndRaw===-1?ta.value.length:lineEndRaw;const block=ta.value.substring(lineStart,lineEnd);const lines=block.split(`\n`);const isCommentedLine=line=>/^(\\s*)\\/\\//.test(line);const nonEmptyLines=lines.filter(line=>line.trim().length>0);const shouldUncomment=nonEmptyLines.length>0\u0026\u0026nonEmptyLines.every(isCommentedLine);const toggleLine=line=>{if(line.trim().length===0)return line;if(shouldUncomment)return line.replace(/^(\\s*)\\/\\/ ?/,`$1`);const match=line.match(/^(\\s*)/);const indent=match?match[1]:``;return`${indent}// ${line.slice(indent.length)}`};const updatedLines=lines.map(toggleLine);const replacedBlock=updatedLines.join(`\n`);const newVal=ta.value.substring(0,lineStart)+replacedBlock+ta.value.substring(lineEnd);setCode(newVal);requestAnimationFrame(()=>{if(hasSelection){ta.selectionStart=lineStart;ta.selectionEnd=lineStart+replacedBlock.length;return}const line=lines[0]||``;const cursorCol=start-lineStart;let newCursorCol=cursorCol;if(line.trim().length>0){if(shouldUncomment){const uncommentMatch=line.match(/^(\\s*)\\/\\/ ?/);if(uncommentMatch){const indentLen=uncommentMatch[1].length;const removedLen=uncommentMatch[0].length-indentLen;if(cursorCol>indentLen){newCursorCol=Math.max(indentLen,cursorCol-removedLen)}}}else{const indentLen=(line.match(/^(\\s*)/)||[``])[0].length;if(cursorCol>indentLen){newCursorCol=cursorCol+3}}}const newCursor=lineStart+newCursorCol;ta.selectionStart=ta.selectionEnd=newCursor})}},[]);const handleResizeStart=useCallback(e=>{e.preventDefault();setIsResizing(true);resizeStartY.current=e.clientY;resizeStartHeight.current=editorHeight},[editorHeight]);useEffect(()=>{if(!isResizing)return;const handleMouseMove=e=>{const delta=e.clientY-resizeStartY.current;const newHeight=Math.max(minHeightPx,Math.min(MAX_HEIGHT,resizeStartHeight.current+delta));setEditorHeight(newHeight)};const handleMouseUp=()=>{setIsResizing(false)};window.addEventListener(`mousemove`,handleMouseMove);window.addEventListener(`mouseup`,handleMouseUp);return()=>{window.removeEventListener(`mousemove`,handleMouseMove);window.removeEventListener(`mouseup`,handleMouseUp)}},[isResizing,minHeightPx]);useEffect(()=>{if(startHeightPx!=null){setEditorHeight(clampHeight(startHeightPx))}else{setEditorHeight(clampHeight(estimateSingleCodeHeight(singleCode,showImportHeader)))}},[startHeightPx,singleCode,showImportHeader]);const run=useCallback(async()=>{if(!loaded||!npRef.current)return;const runId=runSeqRef.current+1;runSeqRef.current=runId;setRunning(true);setTiming(null);const logs=[];const origLog=console.log;const origError=console.error;const origWarn=console.warn;const fmt=(...args)=>args.map(a=>{if(a==null)return String(a);if(typeof a===`object`\u0026\u0026typeof a.toString===`function`\u0026\u0026a.toString!==Object.prototype.toString)return a.toString();if(typeof a===`object`){try{return JSON.stringify(a)}catch{return String(a)}}return String(a)}).join(` `);console.log=(...args)=>logs.push(fmt(...args));console.error=(...args)=>logs.push(`Error: `+fmt(...args));console.warn=(...args)=>logs.push(`Warning: `+fmt(...args));let hasError=false;const shouldRunAsync=/\\bawait\\b/.test(code);const t0=performance.now();try{let result;if(shouldRunAsync){const executeAsync=new Function(`np`,`\"use strict\"; return (async () => {\\n${code}\\n})();`);result=await executeAsync(npRef.current)}else{const executeSync=new Function(`np`,code);result=executeSync(npRef.current)}if(result!==undefined){logs.push(typeof result===`object`\u0026\u0026typeof result?.toString===`function`\u0026\u0026result.toString!==Object.prototype.toString?result.toString():String(result))}}catch(e){hasError=true;logs.push(`Error: `+(e?.message||String(e)))}finally{console.log=origLog;console.error=origError;console.warn=origWarn}const elapsed=performance.now()-t0;if(runId!==runSeqRef.current)return;setOutput(logs.join(`\n`));if(showTiming\u0026\u0026!hasError){const formatted=elapsed\u003c.15?`\u003c 0.10 ms`:elapsed\u003c1?elapsed.toFixed(2)+` ms`:elapsed\u003c1e3?elapsed.toFixed(1)+` ms`:(elapsed/1e3).toFixed(2)+` s`;setTiming(formatted)}setRunning(false)},[loaded,code,showTiming]);const handleCopy=useCallback(async()=>{const textToCopy=`${showImportHeader?IMPORT_HEADER_TEXT:``}${code}`;try{await navigator.clipboard.writeText(textToCopy);setCopied(true);if(copyTimeoutRef.current)clearTimeout(copyTimeoutRef.current);copyTimeoutRef.current=setTimeout(()=>setCopied(false),1200)}catch{setCopied(false)}},[code,showImportHeader]);useEffect(()=>{return()=>{if(copyTimeoutRef.current)clearTimeout(copyTimeoutRef.current)}},[]);useEffect(()=>{const measureScrollbar=()=>{if(!textareaRef.current)return;const el=textareaRef.current;const width=Math.max(el.offsetWidth-el.clientWidth,0);setScrollbarWidth(width)};measureScrollbar();window.addEventListener(`resize`,measureScrollbar);return()=>window.removeEventListener(`resize`,measureScrollbar)},[editorHeight,code,showImportHeader]);useEffect(()=>{if(!toolbarRef.current)return;const ro=new ResizeObserver(([entry])=>{setToolbarNarrow(entry.contentRect.width\u003c380)});ro.observe(toolbarRef.current);return()=>ro.disconnect()},[]);if(loadError){return _jsx(`div`,{style:{padding:`20px`,color:`#e55`,background:colors.outputBg,borderRadius:`8px`,fontSize:`14px`},children:loadError})}const editorRadius=`8px 8px 0 0`;const editorContentRadius=`8px 8px 0 0`;const editorWrap={position:`relative`,height:`${editorHeight}px`,overflow:`hidden`};const editorBorderOverlay={position:`absolute`,inset:0,borderRadius:editorRadius,border:`1px solid ${colors.editorBorder}`,borderBottom:`none`,pointerEvents:`none`,zIndex:4};const copyWrapStyle={position:`absolute`,top:`8px`,right:`${10+scrollbarWidth}px`,zIndex:3,display:`inline-flex`,alignItems:`center`,gap:`6px`};const copyTooltipVisible=copied||copyHover;const copyTooltipStyle={fontSize:`11px`,lineHeight:1,color:`#ffffff`,background:`#3b82f6`,border:`1px solid #3b82f6`,borderRadius:`6px`,padding:`4px 8px`,opacity:copyTooltipVisible?1:0,transform:copyTooltipVisible?`translateY(0)`:`translateY(2px)`,transition:`opacity 0.15s, transform 0.15s`,pointerEvents:`none`,whiteSpace:`nowrap`};const copyBtnStyle={width:`24px`,height:`24px`,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`6px`,border:`none`,background:`transparent`,color:isDarkMode?`rgba(255,255,255,0.4)`:`#9ca3af`,cursor:`pointer`,padding:0,lineHeight:1};const sharedTextStyle={margin:0,border:0,padding:`16px`,whiteSpace:`pre`,overflowWrap:`normal`,wordBreak:`normal`,verticalAlign:`baseline`,textRendering:`auto`};const preStyle={...SHARED_FONT,...sharedTextStyle,position:`absolute`,top:0,left:0,right:0,bottom:0,background:colors.editorBg,overflow:`hidden`,pointerEvents:`none`,padding:0,borderRadius:editorContentRadius};const codeStyle={display:`block`,...SHARED_FONT,background:`transparent`,padding:`16px`,margin:0,border:0,whiteSpace:`pre`,overflowWrap:`normal`,wordBreak:`normal`,lineHeight:`inherit`,willChange:`transform`};const textareaStyle={...SHARED_FONT,...sharedTextStyle,position:`absolute`,top:0,left:0,right:0,bottom:0,paddingTop:showImportHeader?`calc(16px + 3em)`:`16px`,background:`transparent`,color:`transparent`,caretColor:colors.caretColor,outline:`none`,resize:`none`,overflow:`auto`,WebkitTextFillColor:`transparent`,zIndex:1,width:`100%`,height:`100%`,borderRadius:editorContentRadius};const resizeHandle={height:`4px`,background:isResizing?colors.resizeHandleHoverBg:colors.resizeHandleBg,cursor:`ns-resize`,transition:`background 0.15s`,borderLeft:`1px solid ${colors.editorBorder}`,borderRight:`1px solid ${colors.editorBorder}`};const toolbarStyle={display:`flex`,alignItems:`center`,gap:`8px`,padding:`8px 12px`,background:colors.toolbarBg,borderLeft:`1px solid ${colors.editorBorder}`,borderRight:`1px solid ${colors.editorBorder}`,flexWrap:`wrap`};const btnStyle={display:`inline-flex`,alignItems:`center`,gap:`6px`,padding:`6px 16px`,background:`#3179C7`,color:`#fff`,border:`none`,borderRadius:`6px`,fontSize:`13px`,fontWeight:500,cursor:loaded?`pointer`:`not-allowed`,opacity:loaded?1:.5,transition:`background 0.15s`};const selectStyle={padding:`6px 10px`,background:colors.selectBg,color:colors.selectText,border:`1px solid ${colors.selectBorder}`,borderRadius:`6px`,fontSize:`13px`,cursor:`pointer`,outline:`none`};const badgeStyle={marginLeft:`auto`,fontSize:`11px`,color:colors.placeholderText,display:`flex`,alignItems:`center`,gap:`4px`,whiteSpace:`nowrap`};const outputStyle={margin:0,padding:`16px`,minHeight:`60px`,maxHeight:`240px`,overflow:`auto`,...SHARED_FONT,fontSize:`12.5px`,background:colors.outputBg,color:colors.outputText,borderRadius:`0 0 8px 8px`,border:`1px solid ${colors.editorBorder}`,borderTop:`none`,whiteSpace:`pre-wrap`,overflowWrap:`break-word`};const renderedCode=`${showImportHeader?IMPORT_HEADER_TEXT:``}${code}`;const runSpinnerStyle={animation:`playgroundSpin 0.9s linear infinite`,display:`inline-block`};return _jsxs(`div`,{children:[_jsx(`style`,{children:`\n @keyframes playgroundSpin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n @keyframes playgroundPulse {\n 0%, 100% { opacity: 0.45; transform: scale(1); }\n 50% { opacity: 1; transform: scale(1.12); }\n }\n code[class*=\"language-\"] {\n white-space: pre !important;\n word-break: normal !important;\n overflow-wrap: normal !important;\n }\n `}),label?_jsx(`div`,{style:{marginTop:`8px`,marginBottom:`8px`,fontSize:`14px`,fontWeight:500,color:colors.editorText},children:label}):null,_jsxs(`div`,{style:editorWrap,children:[_jsx(`div`,{style:editorBorderOverlay,\"aria-hidden\":`true`}),showCopyButton?_jsxs(`div`,{style:copyWrapStyle,children:[_jsx(`span`,{style:copyTooltipStyle,children:copied?`Copied`:`Copy`}),_jsx(`button`,{type:`button`,onClick:handleCopy,style:copyBtnStyle,onMouseEnter:e=>{setCopyHover(true);e.currentTarget.style.color=isDarkMode?`rgba(255,255,255,0.6)`:`#6b7280`},onMouseLeave:e=>{setCopyHover(false);e.currentTarget.style.color=isDarkMode?`rgba(255,255,255,0.4)`:`#9ca3af`},\"aria-label\":`Copy code`,children:copied?_jsx(`svg`,{width:`18`,height:`18`,viewBox:`0 0 20 20`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,\"aria-hidden\":`true`,children:_jsx(`path`,{d:`M4.5 10.5L8.2 14.2L15.5 6.8`,stroke:`#3b82f6`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})}):_jsxs(`svg`,{width:`18`,height:`18`,viewBox:`0 0 18 18`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,\"aria-hidden\":`true`,children:[_jsx(`path`,{d:`M14.25 5.25H7.25C6.14543 5.25 5.25 6.14543 5.25 7.25V14.25C5.25 15.3546 6.14543 16.25 7.25 16.25H14.25C15.3546 16.25 16.25 15.3546 16.25 14.25V7.25C16.25 6.14543 15.3546 5.25 14.25 5.25Z`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`}),_jsx(`path`,{d:`M2.80103 11.998L1.77203 5.07397C1.61003 3.98097 2.36403 2.96397 3.45603 2.80197L10.38 1.77297C11.313 1.63397 12.19 2.16297 12.528 3.00097`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]})})]}):null,_jsx(`pre`,{ref:preRef,style:preStyle,children:_jsx(`code`,{ref:codeRef,className:`language-typescript`,style:codeStyle,children:renderedCode})}),_jsx(`textarea`,{ref:textareaRef,value:code,onChange:e=>setCode(e.target.value),onScroll:handleScroll,onKeyDown:handleKeyDown,style:textareaStyle,spellCheck:false,wrap:`off`,autoCapitalize:`off`,autoCorrect:`off`,\"aria-label\":`Code editor`})]}),_jsx(`div`,{style:resizeHandle,onMouseDown:handleResizeStart,onMouseEnter:e=>!isResizing\u0026\u0026(e.target.style.background=colors.resizeHandleHoverBg),onMouseLeave:e=>!isResizing\u0026\u0026(e.target.style.background=colors.resizeHandleBg),\"aria-label\":`Resize editor`,role:`separator`}),_jsxs(`div`,{ref:toolbarRef,style:toolbarStyle,children:[_jsx(`button`,{onClick:run,disabled:!loaded,style:btnStyle,onMouseEnter:e=>loaded\u0026\u0026(e.target.style.background=`#2668b0`),onMouseLeave:e=>loaded\u0026\u0026(e.target.style.background=`#3179C7`),children:running?_jsxs(_Fragment,{children:[_jsx(`span`,{style:runSpinnerStyle,children:`↻`}),` Run`]}):_jsxs(_Fragment,{children:[_jsx(`span`,{children:`▶`}),` Run`]})}),timing\u0026\u0026!running\u0026\u0026_jsx(`span`,{style:{fontSize:`12px`,color:`#4caf50`,fontWeight:500,whiteSpace:`nowrap`},children:toolbarNarrow?timing:`Completed in ${timing}`}),_jsx(`span`,{style:badgeStyle,children:loaded?_jsxs(_Fragment,{children:[_jsx(`span`,{style:{color:`#4caf50`,display:`inline-block`,animation:`playgroundPulse 2.2s ease-in-out infinite`,transformOrigin:`center`},children:`●`}),` Runs in your browser`]}):_jsxs(_Fragment,{children:[_jsx(`span`,{style:{animation:`spin 1s linear infinite`,display:`inline-block`},children:`↻`}),` Loading numpy-ts...`]})})]}),_jsx(`pre`,{style:outputStyle,children:output||_jsx(`span`,{style:{color:colors.placeholderText,fontStyle:`italic`},children:`Click Run to execute the code above`})})]})};function _createMdxContent(props){const _components={code:`code`,hr:`hr`,p:`p`,..._provideComponents(),...props.components},{Heading,Tip,_MdxComponentBoundary}=_components;if(!Heading)_missingMdxReference(`Heading`,true);if(!Tip)_missingMdxReference(`Tip`,true);if(!_MdxComponentBoundary)_missingMdxReference(`_MdxComponentBoundary`,true);return _jsxs(_Fragment,{children:[_jsx(_components.p,{children:`Images are naturally represented as multi-dimensional arrays. A grayscale image is a 2-D array of pixel intensities, while a color image is a 3-D array with a channel dimension. numpy-ts provides the array operations needed for common image processing tasks.`}),`\n`,_jsx(Heading,{level:`2`,id:`representing-images-as-2d/3d-arrays`,children:`Representing images as 2D/3D arrays`}),`\n`,_jsx(_MdxComponentBoundary,{name:`Playground`,children:_jsx(Playground,{code:String.raw`// Grayscale image: 2-D array of shape [height, width]\n// Values typically in [0, 255] for uint8 or [0.0, 1.0] for float\nconst grayscale = np.zeros([480, 640], 'uint8');\nconsole.log('Grayscale shape:', grayscale.shape, '\\n');\n\n// RGB image: 3-D array of shape [height, width, channels]\nconst rgb = np.zeros([480, 640, 3], 'uint8');\nconsole.log('RGB shape:', rgb.shape, '\\n');\n\n// Create a synthetic test image: horizontal gradient\nconst width = 256;\nconst height = 256;\nconst row = np.arange(0, width, 1, 'uint8');\nconst gradient = np.tile(row, [height, 1]);\nconsole.log('Gradient shape:', gradient.shape, '\\n');\n\n// Create a checkerboard pattern\nconst blockSize = 32;\nconst board = np.zeros([256, 256], 'uint8');\n\n// Fill using numpy operations\nconst rowIdx = np.arange(256).reshape([256, 1]).floor_divide(blockSize);\nconst colIdx = np.arange(256).reshape([1, 256]).floor_divide(blockSize);\nconst checker = np.mod(np.add(rowIdx, colIdx), 2);\nconsole.log('Checkerboard shape:', checker.shape, '\\n');`,showImportHeader:true,showCopyButton:true})}),`\n`,_jsx(_components.hr,{}),`\n`,_jsx(Heading,{level:`2`,id:`slicing-regions-of-interest`,children:`Slicing regions of interest`}),`\n`,_jsx(_components.p,{children:`Extract sub-images using NumPy-style slicing.`}),`\n`,_jsx(_MdxComponentBoundary,{name:`Playground`,children:_jsx(Playground,{code:String.raw`// Simulated 480x640 RGB image\nconst image = np.random.randint(0, 256, [480, 640, 3], 'uint8');\n\n// Extract a 100x100 region starting at (50, 100)\nconst roi = image.slice('50:150', '100:200', ':');\nconsole.log('ROI shape:', roi.shape, '\\n');\n\n// Extract a single channel (e.g., red channel)\nconst red = image.slice(':', ':', '0');\nconsole.log('Red channel shape:', red.shape, '\\n');\n\n// Extract the center 200x200 patch\nconst cy = 240, cx = 320, halfSize = 100;\nconst y = (cy - halfSize) + ':' + (cy + halfSize);\nconst x = (cx - halfSize) + ':' + (cx + halfSize);\nconst center = image.slice(y, x, ':')\nconsole.log('Center patch shape:', center.shape, '\\n');\n\n// Downsample by taking every other pixel\nconst downsampled = image.slice('::2', '::2', ':');\nconsole.log('Downsampled shape:', downsampled.shape, '\\n');\n\n// Flip the image vertically (reverse rows)\nconst flipped = np.flip(image, 0);\nconsole.log('Flipped shape:', flipped.shape, '\\n');\n\n// Rotate 90 degrees\nconst rotated = np.rot90(image);\nconsole.log('Rotated shape:', rotated.shape, '\\n');`,showImportHeader:true,showCopyButton:true})}),`\n`,_jsx(_components.hr,{}),`\n`,_jsx(Heading,{level:`2`,id:`element-wise-transforms-brightness-and-contrast`,children:`Element-wise transforms: brightness and contrast`}),`\n`,_jsx(_components.p,{children:`Adjust pixel values using vectorized arithmetic — no loops required.`}),`\n`,_jsx(_MdxComponentBoundary,{name:`Playground`,children:_jsx(Playground,{code:[`// Work in float for precision, then convert back to uint8`,`const image = np.random.randint(0, 256, [256, 256, 3])`,` .divide(255.0);`,``,`// Print a tiny patch so we can see actual values`,`console.log('Original patch [0:2, 0:5, :]:\\\\n' + image.slice('0:2', '0:5', ':'), '\\\\n');`,`console.log('Original range (min/max):', np.amin(image), '-', np.amax(image), '\\\\n');`,``,`// Brightness adjustment: add a constant`,`const brightnessOffset = 0.2;`,`const brighter = np.clip(np.add(image, brightnessOffset), 0, 1);`,`const darker = np.clip(np.subtract(image, brightnessOffset), 0, 1);`,``,`console.log('Brighter patch [0:2, 0:5, :]:\\\\n' + brighter.slice('0:2', '0:5', ':'), '\\\\n');`,`console.log('Darker patch [0:2, 0:5, :]:\\\\n' + darker.slice('0:2', '0:5', ':'), '\\\\n');`,``,`// Contrast adjustment: scale around the mean`,`const mean = np.mean(image);`,`const contrastFactor = 1.5;`,`const highContrast = image`,` .subtract(mean)`,` .multiply(contrastFactor)`,` .add(mean)`,` .clip(0, 1);`,``,`console.log('High-contrast patch [0:2, 0:5, :]:\\\\n' + highContrast.slice('0:2', '0:5', ':'), '\\\\n');`,``,`// Gamma correction: raise to a power`,`const gamma = 2.2;`,`const gammaCorrected = np.power(image, 1 / gamma);`,`console.log('Gamma-corrected patch [0:2, 0:5, :]:\\\\n' + gammaCorrected.slice('0:2', '0:5', ':'), '\\\\n');`,``,`// Invert the image`,`const inverted = image`,` .multiply(-1.0)`,` .add(1.0);`,`console.log('Inverted patch [0:2, 0:5, :]:\\\\n' + inverted.slice('0:2', '0:5', ':'), '\\\\n');`,``,`// Convert back to uint8 for display`,`const result = np.multiply(brighter, 255).astype('uint8');`,`console.log('Result dtype:', result.dtype);`,`console.log('Result range (min/max):', np.amin(result), '-', np.amax(result), '\\\\n');`,`console.log('Result patch [0:2, 0:5, :]:\\\\n' + result.slice('0:2', '0:5', ':'), '\\\\n');`].join(`\n`),showImportHeader:true,showCopyButton:true})}),`\n`,_jsx(_components.hr,{}),`\n`,_jsx(Heading,{level:`2`,id:`reshaping-and-transposing-for-channel-reordering`,children:`Reshaping and transposing for channel reordering`}),`\n`,_jsxs(_components.p,{children:[`Different frameworks expect different axis orderings. Use `,_jsx(_components.code,{children:`transpose`}),` and `,_jsx(_components.code,{children:`reshape`}),` to convert between them.`]}),`\n`,_jsx(_MdxComponentBoundary,{name:`Playground`,children:_jsx(Playground,{code:String.raw`// HWC format (height, width, channels) -- common in image APIs\nconst hwc = np.random.randint(0, 256, [224, 224, 3], 'uint8');\nconsole.log('HWC shape:', hwc.shape, '\\n');\n\n// Convert to CHW format (channels, height, width) -- used by ML frameworks\nconst chw = np.transpose(hwc, [2, 0, 1]);\nconsole.log('CHW shape:', chw.shape, '\\n');\n\n// Convert back to HWC\nconst backToHwc = np.transpose(chw, [1, 2, 0]);\nconsole.log('Back to HWC:', backToHwc.shape, '\\n');\n\n// Add a batch dimension (NCHW for batched inference)\nconst batch = np.expand_dims(chw, 0);\nconsole.log('NCHW batch shape:', batch.shape, '\\n');\n\n// Stack multiple images into a batch\nconst img1 = np.random.randint(0, 256, [3, 224, 224], 'uint8');\nconst img2 = np.random.randint(0, 256, [3, 224, 224], 'uint8');\nconst img3 = np.random.randint(0, 256, [3, 224, 224], 'uint8');\nconst batchOf3 = np.stack([img1, img2, img3]);\nconsole.log('Batch of 3:', batchOf3.shape, '\\n');\n\n// Extract a single channel and squeeze\nconst greenChannel = chw.slice('1:2', ':', ':'); // shape [1, 224, 224]\nconst greenSqueezed = np.squeeze(greenChannel, 0); // shape [224, 224]\nconsole.log('Green channel:', greenSqueezed.shape, '\\n');`,showImportHeader:true,showCopyButton:true})}),`\n`,_jsx(_components.hr,{}),`\n`,_jsx(Heading,{level:`2`,id:`simple-convolution-filter`,children:`Simple convolution filter`}),`\n`,_jsx(_components.p,{children:`Apply spatial filters to images using convolution. For a 2-D image, convolve each row and column separately using 1-D convolution, or build a simple approach using element-wise operations.`}),`\n`,_jsx(_MdxComponentBoundary,{name:`Playground`,children:_jsx(Playground,{code:[`// Create a simple 8x8 grayscale 'image'`,`const image = np.array([`,` [0, 0, 0, 0, 0, 0, 0, 0],`,` [0, 0, 0, 1, 1, 0, 0, 0],`,` [0, 0, 1, 1, 1, 1, 0, 0],`,` [0, 1, 1, 1, 1, 1, 1, 0],`,` [0, 1, 1, 1, 1, 1, 1, 0],`,` [0, 0, 1, 1, 1, 1, 0, 0],`,` [0, 0, 0, 1, 1, 0, 0, 0],`,` [0, 0, 0, 0, 0, 0, 0, 0],`,`]);`,``,`const smoothKernel = np.array([1 / 3, 1 / 3, 1 / 3]);`,`const rows = image.shape[0];`,``,`// Apply row-by-row convolution`,`const smoothedRows = [];`,`for (let i = 0; i \u003c rows; i++) {`,` const row = image.row(i);`,` smoothedRows.push(np.convolve(row, smoothKernel, 'same'));`,`}`,`const rowSmoothed = np.stack(smoothedRows);`,``,`// Then smooth columns by transposing, convolving rows, and transposing back`,`const cols = rowSmoothed.shape[1];`,`const smoothedCols = [];`,`for (let j = 0; j \u003c cols; j++) {`,` const col = image.col(j);`,` smoothedCols.push(np.convolve(col, smoothKernel, 'same'));`,`}`,`const fullySmoothed = np.transpose(np.stack(smoothedCols));`,``,`console.log('Smoothed image:', '\\\\n');`,`console.log(fullySmoothed, '\\\\n');`].join(`\n`),showImportHeader:true,showCopyButton:true})}),`\n`,_jsx(Tip,{children:_jsx(_components.p,{children:`For large-scale 2-D convolution, consider using the FFT approach: pad the image and kernel to the same size, multiply their FFTs, and inverse-transform the result. This runs in O(N log N) instead of O(N * K).`})})]})}function MDXContent(props={}){const{wrapper:MDXLayout}={..._provideComponents(),...props.components};return MDXLayout?_jsx(MDXLayout,{...props,children:_jsx(_createMdxContent,{...props})}):_createMdxContent(props)}return{Playground,default:MDXContent};function _missingMdxReference(id,component){throw new Error(`Expected `+(component?`component`:`object`)+\" `\"+id+\"` to be defined: you likely forgot to import, pass, or provide it.\")}","frontmatter":{},"scope":{"config":{},"pageMetadata":{"title":"Image Processing","description":"Represent images as arrays, slice regions of interest, apply element-wise transforms, transpose channels, and build convolution filters.","canonical":"https://numpyts.dev/latest/examples/image-processing","href":"/v1.7.x/examples/image-processing"}}},"mdxSourceWithNoJs":null,"noJsSplices":[[146,20781,")=>null;function _cr"],[21628,22645,""],[22980,24049,""],[24448,26298,""],[26817,28009,""],[28483,29569,""]]},"mdxExtracts":{"tableOfContents":[{"title":"Representing images as 2D/3D arrays","slug":"representing-images-as-2d/3d-arrays","depth":2,"children":[]},{"title":"Slicing regions of interest","slug":"slicing-regions-of-interest","depth":2,"children":[]},{"title":"Element-wise transforms: brightness and contrast","slug":"element-wise-transforms-brightness-and-contrast","depth":2,"children":[]},{"title":"Reshaping and transposing for channel reordering","slug":"reshaping-and-transposing-for-channel-reordering","depth":2,"children":[]},{"title":"Simple convolution filter","slug":"simple-convolution-filter","depth":2,"children":[]}],"codeExamples":{}},"jsLinks":[],"subdomain":"none-4568e96a","siteName":"numpy-ts","title":"Image Processing - numpy-ts","navMaps":{"firstHrefInVersion":{"v1.8.x":{"href":"/latest/examples/image-processing","matchLevel":1},"v1.7.x":{"href":"/v1.7.x/examples/image-processing","matchLevel":0},"v1.6.x":{"href":"/v1.6.x/examples/image-processing","matchLevel":1,"canonicalOverride":true},"v1.5.x":{"href":"/v1.5.x/examples/image-processing","matchLevel":1,"canonicalOverride":true},"v1.4.x":{"href":"/v1.4.x/examples/image-processing","matchLevel":1,"canonicalOverride":true},"v1.3.x":{"href":"/v1.3.x/examples/image-processing","matchLevel":1,"canonicalOverride":true},"v1.2.x":{"href":"/v1.2.x/examples/image-processing","matchLevel":1,"canonicalOverride":true},"v1.1.x":{"href":"/v1.1.x/examples/image-processing","matchLevel":1,"canonicalOverride":true},"v1.0.x":{"href":"/v1.0.x/examples/image-processing","matchLevel":1,"canonicalOverride":true}},"firstHrefInLanguage":{}},"lastModified":"2026-11-16T18:55:04.121Z","originalFileLocation":"v1.7.x/examples/image-processing.mdx"},"headHtml":"\u003cscript data-mint-head>(function(){var d=document.documentElement,p=null;if(!p){try{p=localStorage.getItem(\"isDarkMode\")}catch(e){}if(p==='true')p='dark';else if(p==='false')p='light';if(p!=='light'\u0026\u0026p!=='dark'\u0026\u0026p!=='system')p=\"system\"}var r=p==='system'?(matchMedia(\"(prefers-color-scheme: dark)\").matches?'dark':'light'):p;d.classList.remove(r==='dark'?'light':'dark');d.classList.add(r);d.setAttribute(\"data-theme-preference\",p)})();\u003c/script>\u003cmeta data-mint-head name=\"description\" content=\"Represent images as arrays, slice regions of interest, apply element-wise transforms, transpose channels, and build convolution filters.\">\u003cmeta data-mint-head name=\"application-name\" content=\"numpy-ts\">\u003cmeta data-mint-head name=\"generator\" content=\"Mintlify\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"192x192\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/android-chrome-192x192.png\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"apple-touch-icon\" type=\"image/png\" sizes=\"180x180\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/apple-touch-icon.png\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/favicon-16x16.png\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/favicon-32x32.png\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/favicon.ico\" media=\"(prefers-color-scheme: light)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"192x192\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon-dark/android-chrome-192x192.png\" media=\"(prefers-color-scheme: dark)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon-dark/favicon-16x16.png\" media=\"(prefers-color-scheme: dark)\">\u003clink data-mint-head rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon-dark/favicon-32x32.png\" media=\"(prefers-color-scheme: dark)\">\u003clink data-mint-head rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon-dark/favicon.ico\" media=\"(prefers-color-scheme: dark)\">\u003cmeta data-mint-head property=\"og:title\" content=\"Image Processing - numpy-ts\">\u003cmeta data-mint-head property=\"og:description\" content=\"Represent images as arrays, slice regions of interest, apply element-wise transforms, transpose channels, and build convolution filters.\">\u003cmeta data-mint-head property=\"og:site_name\" content=\"numpy-ts\">\u003cmeta data-mint-head property=\"og:url\" content=\"https://numpyts.dev/latest/examples/image-processing\">\u003cmeta data-mint-head property=\"og:type\" content=\"website\">\u003cmeta data-mint-head property=\"og:image\" content=\"https://none-4568e96a.mintlify.site/_mintlify/api/og/v2?division=Examples\u0026amp;title=Image+Processing\u0026amp;description=Represent+images+as+arrays%2C+slice+regions+of+interest%2C+apply+element-wise+transforms%2C+transpose+channels%2C+and+build+convolution+filters.\u0026amp;theme=b5014473248618418b013a87\u0026amp;signature=4abd8fdd37ad7e715b3e2215ad61d5589e1129320454da89fd6f45f1d2d87a79\">\u003cmeta data-mint-head property=\"og:image:width\" content=\"1200\">\u003cmeta data-mint-head property=\"og:image:height\" content=\"630\">\u003cmeta data-mint-head name=\"twitter:card\" content=\"summary_large_image\">\u003cmeta data-mint-head name=\"twitter:title\" content=\"Image Processing - numpy-ts\">\u003cmeta data-mint-head name=\"twitter:description\" content=\"Represent images as arrays, slice regions of interest, apply element-wise transforms, transpose channels, and build convolution filters.\">\u003cmeta data-mint-head name=\"twitter:image\" content=\"https://none-4568e96a.mintlify.site/_mintlify/api/og/v2?division=Examples\u0026amp;title=Image+Processing\u0026amp;description=Represent+images+as+arrays%2C+slice+regions+of+interest%2C+apply+element-wise+transforms%2C+transpose+channels%2C+and+build+convolution+filters.\u0026amp;theme=b5014473248618418b013a87\u0026amp;signature=4abd8fdd37ad7e715b3e2215ad61d5589e1129320454da89fd6f45f1d2d87a79\">\u003cmeta data-mint-head name=\"twitter:image:width\" content=\"1200\">\u003cmeta data-mint-head name=\"twitter:image:height\" content=\"630\">\u003cmeta data-mint-head name=\"msapplication-config\" content=\"/mintlify-assets/_mintlify/favicons/none-4568e96a/8LNVT7tjW2wqWjTD/_generated/favicon/browserconfig.xml\">\u003cmeta data-mint-head name=\"apple-mobile-web-app-title\" content=\"numpy-ts\">\u003cmeta data-mint-head name=\"msapplication-TileColor\" content=\"#3179C7\">\u003clink data-mint-head rel=\"canonical\" href=\"https://numpyts.dev/latest/examples/image-processing\">\u003clink data-mint-head rel=\"alternate\" type=\"application/xml\" href=\"/sitemap.xml\">\u003clink data-mint-head rel=\"alternate\" type=\"text/markdown\" href=\"/v1.7.x/examples/image-processing.md\">\u003cscript data-mint-head type=\"application/ld+json\">{\"@context\":\"https://schema.org\",\"@graph\":[{\"@type\":\"Organization\",\"@id\":\"https://numpyts.dev/#organization\",\"name\":\"numpy-ts\",\"url\":\"https://numpyts.dev\",\"logo\":{\"@type\":\"ImageObject\",\"url\":\"https://mintcdn.com/none-4568e96a/TklIwzPdQ8Sv_cxD/images/logo-light.svg?fit=max\u0026auto=format\u0026n=TklIwzPdQ8Sv_cxD\u0026q=85\u0026s=85a09d3e9971808ec73bf6e2eddcb989\"}},{\"@type\":\"WebSite\",\"@id\":\"https://numpyts.dev#website\",\"name\":\"numpy-ts\",\"url\":\"https://numpyts.dev\",\"publisher\":{\"@id\":\"https://numpyts.dev/#organization\"}},{\"@type\":\"WebPage\",\"@id\":\"https://numpyts.dev/latest/examples/image-processing#webpage\",\"url\":\"https://numpyts.dev/latest/examples/image-processing\",\"name\":\"Image Processing\",\"description\":\"Represent images as arrays, slice regions of interest, apply element-wise transforms, transpose channels, and build convolution filters.\",\"dateModified\":\"2026-11-16T18:55:04.121Z\",\"isPartOf\":{\"@id\":\"https://numpyts.dev#website\"},\"breadcrumb\":{\"@id\":\"https://numpyts.dev/latest/examples/image-processing#breadcrumb\"}},{\"@type\":\"BreadcrumbList\",\"@id\":\"https://numpyts.dev/latest/examples/image-processing#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Examples\",\"item\":\"https://numpyts.dev/v1.7.x/examples/overview\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Image Processing\",\"item\":\"https://numpyts.dev/latest/examples/image-processing\"}]},{\"@type\":[\"Article\",\"TechArticle\"],\"@id\":\"https://numpyts.dev/latest/examples/image-processing#article\",\"headline\":\"Image Processing\",\"name\":\"Image Processing\",\"description\":\"Represent images as arrays, slice regions of interest, apply element-wise transforms, transpose channels, and build convolution filters.\",\"url\":\"https://numpyts.dev/latest/examples/image-processing\",\"mainEntityOfPage\":{\"@id\":\"https://numpyts.dev/latest/examples/image-processing#webpage\"},\"dateModified\":\"2026-11-16T18:55:04.121Z\",\"publisher\":{\"@id\":\"https://numpyts.dev/#organization\"},\"isPartOf\":{\"@id\":\"https://numpyts.dev#website\"}}]}\u003c/script>\u003cscript data-mint-head type=\"application/ld+json\">{\"@context\":\"https://schema.org\",\"@type\":\"WebSite\",\"name\":\"numpy-ts\",\"publisher\":{\"@type\":\"Organization\",\"name\":\"numpy-ts\"},\"provider\":{\"@type\":\"Organization\",\"name\":\"Mintlify\",\"url\":\"https://mintlify.com\"}}\u003c/script>","agentPointerHref":"/v1.7.x/examples/image-processing.md","siteName":"numpy-ts","nav":{"global":null,"versions":[{"version":"v1.8.x","tag":"Latest","pages":[{"title":"v1.8.x","href":"/latest/examples/image-processing"}]},{"version":"v1.7.x","tabs":[{"tab":"Guides","pages":[{"title":"Guides","href":""}]},{"tab":"API Reference","pages":[{"title":"API Reference","href":"/v1.7.x/api/overview"}]},{"tab":"Performance","pages":[{"title":"Performance","href":"/v1.7.x/performance/overview"}]},{"tab":"Examples","groups":[{"group":"Examples","pages":[{"title":"Examples","sidebarTitle":"Overview","href":"/v1.7.x/examples/overview"},{"title":"Linear Algebra","href":"/v1.7.x/examples/linear-algebra"},{"title":"Signal Processing with FFT","href":"/v1.7.x/examples/signal-processing"},{"title":"Statistics \u0026 Analysis","description":"Descriptive statistics, histograms, correlation matrices, Monte Carlo simulations, and weighted averages with numpy-ts.","href":"/v1.7.x/examples/statistics-analysis"},{"title":"Image Processing","href":"/v1.7.x/examples/image-processing"},{"title":"Data Loading \u0026 I/O","description":"Load and save arrays in .npy, .npz, and text formats across Node.js and browser environments.","href":"/v1.7.x/examples/data-loading"},{"title":"Performance Tips","href":"/v1.7.x/examples/performance-tips"}]}]},{"tab":"Playground","pages":[{"title":"Playground","href":"/v1.7.x/playground"}]}]},{"version":"v1.6.x","pages":[{"title":"v1.6.x","href":"/v1.6.x/examples/image-processing"}]},{"version":"v1.5.x","pages":[{"title":"v1.5.x","href":"/v1.5.x/examples/image-processing"}]},{"version":"v1.4.x","pages":[{"title":"v1.4.x","href":"/v1.4.x/examples/image-processing"}]},{"version":"v1.3.x","pages":[{"title":"v1.3.x","href":"/v1.3.x/examples/image-processing"}]},{"version":"v1.2.x","pages":[{"title":"v1.2.x","href":"/v1.2.x/examples/image-processing"}]},{"version":"v1.1.x","pages":[{"title":"v1.1.x","href":"/v1.1.x/examples/image-processing"}]},{"version":"v1.0.x","pages":[{"title":"v1.0.x","href":"/v1.0.x/examples/image-processing"}]}]},"basePath":"","title":"Image Processing - numpy-ts","deploymentId":"dpl_DyXGnKeCjZyA3sUdfMJ7FjkdBefg","buildId":"dpl_DyXGnKeCjZyA3sUdfMJ7FjkdBefg","dynamics":[],"chunks":[]}