Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop with R string Python

Currently, my code is like this:

for images in range(500):
    image = cv2.imread(r'C:\\mypath\images.png')

How can I loop through? I tried using {}.format(images) but that doesn’t work with r strings?

edit: updated code problem

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for i in range(500):
    image = cv2.imread(fr'mypath\captcha{i}.png')
    img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY)
    cv2.imshow('Binary image', thresh)
    cv2.imwrite(fr'mypath\captcha{i}.png', thresh)

error:

cv2.error: OpenCV(4.5.4) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

>Solution :

Why not just use f-strings ?

for images in range(500):
    image = cv2.imread(f'C:\\mypath\{images}.png')

If r-strings needed, then just use fr-strings, e.g.:

for images in range(500):
    image = cv2.imread(fr'C:\\mypath\{images}.png')

Maybe you need to change \ to / as well. Sometimes it’s necessary.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading