TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'

Question:

I got an error

TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'

My code is the following

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 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?

Asked By: user8817674

||

Answers:

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.

Maybe try:

cv2.imwrite(str(path) + "/" + "photo.png", img)

Alternatively, use the proper concatenation as described in the pathlib docs.

Answered By: SCB

You cannot use operand + on a PosixPath object. Instead, you should use / when dealing with the pathlib library:

    # before
    cv2.imwrite(path + "/" + "photo.png", img)
    # after
    cv2.imwrite(path / "photo.png", img)
Answered By: faisal burhanudin

First convert the PosixPath object (path) to string:

str(path) + "/" + "photo.png"
Answered By: Ahmad

This is working for me:

cv2.imwrite(str(path) + "/" + "photo.png", img)
Answered By: Mahfuz Khandaker
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.