本文介绍了TypeError:+不支持的操作数类型:"PosixPath"和"str"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了错误
TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'
我的代码如下
import os
import cv2
import random
from pathlib import Path
path = Path(__file__).parent
path = "../img_folder"
for f in path.iterdir():
print(f)
f = str(f)
img=cv2.imread(f)
line = random.randint(0, 50)
img[3, 3, :] = line
cv2.imwrite(path + "/" + "photo.png", img)
Traceback表示cv2.imwrite~
的代码是错误的.我真的不明白为什么这是错误的.这是路径错误类型吗?还是我使用这种方法不对?我该如何解决?
Traceback says a code of cv2.imwrite~
is wrong. I really cannot understand why this is wrong. Is this type of path error? Or am I wrong to use this method? How should I fix this?
推荐答案
如果您仔细检查类型错误,实际上是因为您试图对PosixPath
类型和str
使用+
运算符.您需要先将PosixPath
转换为字符串,然后才能使用imwrite
.
If you look through your type error, it's actually because you're trying to use the +
operator on a PosixPath
type and a str
. You'll need to convert the PosixPath
to a string before you can use the imwrite
.
也许尝试:
cv2.imwrite(str(path) + "/" + "photo.png", img)
或者,使用 pathlib文档中所述的适当连接
Alternatively, use the proper concatenation as described in the pathlib docs.
这篇关于TypeError:+不支持的操作数类型:"PosixPath"和"str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!