我正在尝试运行一个简单的示例代码,在 python3 上使用 opencv 编写图像。代码参考:1
import cv2
import os
image_path = r'C:\Users\840g1 touch\Desktop\B2.jpg'
directory = r'C:\Users\840g1 touch\Desktop'
img = cv2.imread(image_path)
os.chdir(directory)
print("Before saving image:")
print(os.listdir(directory))
# Filename
filename = 'savedImage.jpg'
cv2.imwrite(filename, img)
print("After saving image:")
print(os.listdir(directory))
print('Successfully saved')
图像正在显示,但图像以外的所有内容都没有保存在任何地方。我在 Windows 上使用 Anaconda。不确定问题是否与代码或我的电脑有关。
非常感谢任何帮助!
您没有提供
imwrite
的路径,因此它会写入您的 python 当前工作目录。
更改线路:
cv2.imwrite(filename, img)
类似:
cv2.imwrite(os.path.join(directory,filename), img)
注意: 你可以通过
获取当前的工作目录os.getcwd()
cv2.imwrite 很难理解字符串路径。
使用os.path!
例如 os.path.join(目录,文件名)