0

I have write this short code:

from cv2 import cv2

img = cv2.imread("1.png")

print("Высота:"+str(img.shape[0]))
print("Ширина:" + str(img.shape[1]))
print("Количество каналов:" + str(img.shape[2]))

for x in img.shape[0]:
    for y in img.shape[1]:
        if img[x, y] == (255, 255, 255):
            img[x, y] = (0, 0, 0)

cv2.imwrite("result.png", img)

And I have this error:

Traceback (most recent call last):
  File "e:\Projects\Captcha Decrypt\main.py", line 9, in <module>
    for x in img.shape[0]:
TypeError: 'int' object is not iterable

Can you solve this problem?

2
  • 3
    The error message is pretty clear, isn't it? img.shape[0] is an integer not an iterable (list, dict, etc.) Commented Jun 5, 2021 at 12:10
  • Regarding the print you wrote just before, you can see that img.shape[0] is an INT, how do you want ot iterate on it ? From 0 to that value ? use a range for that Commented Jun 5, 2021 at 12:11

1 Answer 1

1

The error says it all: you are trying to iterate over a number, which is not possible, you can only iterate over objects having implemented the __iter__ or __next__ method. If img.shape[0] is for example 100, and you want to iterate a hundred times, you should use a range instead. That's basically a list of numbers, over which you can then iterate. Try this one:

from cv2 import cv2

img = cv2.imread("1.png")

print("Высота:" + str(img.shape[0]))
print("Ширина:" + str(img.shape[1]))
print("Количество каналов:" + str(img.shape[2]))

for x in range(img.shape[0]):
    for y in range(img.shape[1]):
        if img[x, y] == (255, 255, 255):
            img[x, y] = (0, 0, 0)

cv2.imwrite("result.png", img)
Sign up to request clarification or add additional context in comments.

1 Comment

@РостиславРоманец No need to add a comment Thanks. It is working, instead, rather accept and optionally upvote my answer ! ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.