0

The following part of my code is highlighted as code unreachable in pycharm IDE.

 for row in range(frame_height):
                for col in range(frame_width):
                    if i < binary_img.shape[0]:
                        pixel = frame[row][col]
                        binary_pixel = np.unpackbits(np.array(pixel).astype(np.uint8))
                        binary_pixel[-1] = binary_img[i][-1]
                        pixel = np.packbits(binary_pixel).astype(np.int32)
                        frame[row][col] = pixel
                        i += 1
                else:
                    break
 cv2.imshow('Hidden Video', frame)
 if cv2.waitKey(1) & 0xFF == ord('q'):
    break

It is working perfectly, but there is a warning for this code saying that it is unreachable.

Heeya
  • 11
  • 3
  • This code will only execute the outer `for` loop once. Is that what you want? – Mous Feb 24 '23 at 05:31
  • @Mous, incorrect. It will execute the loop to the end and when `StopIteration` call happens it will jump into the `else` block. `for-else` is a rather uncommon structure and I doubt it's the intention here but it will work fine. I think the actual intent was to have an `if-else` in which case it's indented incorrectly. – NotAName Feb 24 '23 at 05:59
  • 2
    If PyCharm is showing this code block as unreachable, you need to include the code above to understand why it might be getting unreachable. – NotAName Feb 24 '23 at 05:59
  • @pavel I understand how `for-else` works. When the inner `for` loop reaches `StopIteration`, we enter the `else` block. The `break` statement within breaks the outer loop. The content of the outer `for` loop is only executed once. I agree that it is meant to be an `if`-`else` construction though. – Mous Feb 24 '23 at 06:03
  • @Mous, oh right. Sorry, I missed that fact there was an outer loop. – NotAName Feb 24 '23 at 06:07
  • True @pavel, for-else was not the intention here. Due to improper indentation, it seemed like that. – Heeya Feb 24 '23 at 14:05

1 Answers1

0

Thank you @pavel and @mous, I looked at the code again and I found out that there was a problem with the indentation in the outer for loop. It should have been like this:

# Iterate through each pixel in the video and hide a bit of the image in it
i = 0
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    for row in range(frame_height): #indentation error was in this line
        for col in range(frame_width):
            if i < binary_img.shape[0]:
                pixel = frame[row][col]
                binary_pixel = np.unpackbits(np.array(pixel).astype(np.uint8))
                binary_pixel[-1] = binary_img[i][-1]
                pixel = np.packbits(binary_pixel).astype(np.int32)
                frame[row][col] = pixel
                i += 1
            else:
                break
    cv2.imshow('Hidden Video', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
Heeya
  • 11
  • 3