Reputation: 1141
I got an error TypeError: bad argument type for built-in operation . I wrote
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?
Upvotes: 18
Views: 56635
Reputation: 95
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.
Like:
<!-- language: py-->
for pathObj in path.iterdir():
pathStr = str(pathObj)
img=cv2.imread(pathStr)
Upvotes: 1
Reputation: 5609
Looks like path.iterdir()
returns an object of type <class 'pathlib.PosixPath'>
and not str
. And cv2.imread()
accepts a string filename.
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)
Upvotes: 23