Python 类型错误:内置操作的参数类型错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47990952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:28:01  来源:igfitidea点击:

TypeError: bad argument type for built-in operation

pythonopencv

提问by user8817674

I got an error TypeError: bad argument type for built-in operation . I wrote

我收到错误 TypeError: bad argument type for built-in operation 。我写

import os
import cv2
from pathlib import Path
path = Path(__file__).parent
path /= "../../img_folder"
for f in path.iterdir():
    print(f)
    img=cv2.imread(f)

In img=cv2.imread(f), the error happens.Is this a Python error or directory wrong error?In print(f),I think right directories can be gotten.How should I fix this?

在 img=cv2.imread(f) 中,发生错误。这是 Python 错误还是目录错误错误?在 print(f) 中,我认为可以获取正确的目录。我应该如何解决这个问题?

回答by nitred

Looks like path.iterdir()returns an object of type <class 'pathlib.PosixPath'>and not str. And cv2.imread()accepts a string filename.

看起来path.iterdir()返回一个类型的对象<class 'pathlib.PosixPath'>而不是str。并cv2.imread()接受字符串文件名。

So this fixes it:

所以这修复了它:

import os
import cv2
from pathlib import Path
path = Path(__file__).parent
path /= "../../img_folder"
for f in path.iterdir():
    print(f)    # <--- type: <class 'pathlib.PosixPath'>
    f = str(f)  # <--- convert to string
    img=cv2.imread(f)

回答by Lucas Costa

path is not a object of type STRING, is a object pathLib Type, so you have to do is, on the loop, cast the value of iterator in a String object with the method str() before to pass to the imread.

path 不是 STRING 类型的对象,是一个对象 pathLib 类型,所以你必须做的是,在循环中,在传递给 imread 之前,使用 str() 方法将迭代器的值转换为 String 对象。

Like:

喜欢:

<!-- language: py-->
for pathObj in path.iterdir():   
    pathStr = str(pathObj) 
    img=cv2.imread(pathStr)