You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

图片去背景脚本在IDE运行正常,CMD执行报错求助

CMD执行图片去背景脚本报错的解决办法

问题描述

以下Python脚本实现了接收图片路径、去除背景并保存至指定文件名的功能,在PyCharm中运行完全正常,但在CMD终端执行时,拖入图片路径回车后会报错:

from rembg import remove
from PIL import Image

input_path = input("Please Drag & Drop an image:")   # Takes image path
output_name = input("Give it a name:")
output_path = rf'C:\Users\user\Desktop\{output_name}.png'

input_image = Image.open(input_path)
output = remove(input_image)
output.save(output_path)

报错原因

在CMD中拖拽图片路径时,系统会自动给路径加上双引号(尤其是路径包含空格时),而input()获取的字符串会完整保留这些引号,导致Image.open()无法识别带引号的无效路径,进而触发报错。

解决方案

对输入的路径做预处理,去除首尾的单引号或双引号,修改后的代码如下:

from rembg import remove
from PIL import Image

# 处理输入路径,移除首尾的引号
input_path = input("Please Drag & Drop an image:").strip('"\'')
output_name = input("Give it a name:")
# 注意:将此处的user替换为你的实际系统用户名
output_path = rf'C:\Users\user\Desktop\{output_name}.png'

input_image = Image.open(input_path)
output = remove(input_image)
output.save(output_path)

如果想让脚本适配所有用户,避免硬编码用户名,可改用通用方式获取桌面路径:

from rembg import remove
from PIL import Image
import os

input_path = input("Please Drag & Drop an image:").strip('"\'')
output_name = input("Give it a name:")
# 自动获取当前用户的桌面路径
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
output_path = os.path.join(desktop_path, f"{output_name}.png")

input_image = Image.open(input_path)
output = remove(input_image)
output.save(output_path)

内容的提问来源于stack exchange,提问作者Adryan Zeigler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 00:45:52