Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: bad argument type for built-in operation

Tags:

python

opencv

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?

like image 480
user8817674 Avatar asked Dec 27 '17 10:12

user8817674


2 Answers

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)
like image 50
nitred Avatar answered Nov 11 '22 20:11

nitred


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)
like image 34
Lucas Costa Avatar answered Nov 11 '22 18:11

Lucas Costa