如何在 FastAPI 中将 NumPy 数组显示为图像
问题:
尽管有表示图像的 NumPy 数组,在尝试渲染时显示为白色方块。
解决方案:
选项 1:以字节形式返回图像
使用自定义 Response 类,请按照以下步骤操作:
- 从磁盘加载图像或使用 PIL 或 OpenCV 将内存中的 NumPy 数组转换为图像。
- 分别使用 save() 或 imencode() 方法将图像保存到 BytesIO 缓冲区中。
- 设置 Content-Disposition 标头以指定内联查看或下载。
- 返回响应中的图像字节,其中 media_type 设置为适当的图像格式(例如“image/png”)。
选项 2:以 JSON 编码的 NumPy 数组形式返回图像
此选项不适合在浏览器中显示图像,但允许您将 NumPy 数组编码为 JSON 并在客户端将其解码回图像。
- 将使用 tolist() 方法将 NumPy 数组转换为列表。
- 将列表编码为 JSON 并在响应中返回。
- 在客户端,将 JSON 字符串解码回 NumPy 数组并使用 PIL 或 OpenCV 从其创建图像。
注意:
- 对于这两个选项,设置 Content-Disposition 标头至关重要用于在浏览器中显示图像。
- 如果 NumPy 数组已加载到内存中并且可以在单个响应中有效返回,则不需要 StreamingResponse。
以上是如何在 FastAPI 中将 NumPy 数组渲染为图像:解决白方块问题?的详细内容。更多信息请关注PHP中文网其他相关文章!

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3汉化版
中文版,非常好用

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Dreamweaver CS6
视觉化网页开发工具

Atom编辑器mac版下载
最流行的的开源编辑器