#πŸ”’ When debugging my code, the specific function I wish to debug seemingly doesn't get reached?

74 messages Β· Page 1 of 1 (latest)

fiery seal
#

My knowledge of Python feels very weak atm., but I'm essentially creating a project with a group of 4 others, wherein we're performing object detection. My task is to save cropped images containing the detected objects and save them to a directory. However when I test the saving function, if I add a print statement to the very top of the definition of the function, I don't see the print statement when attempting to run the function, making me very confused πŸ₯²

signal yewBOT
#

@fiery seal

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

fiery seal
#

It's a little hard to show all the relevant code in one screenshot, but the save_cropped_blobs function is the one that seemingly doesn't run, and it isn't giving me any errors:

willow hound
#

can't help without all the code. plus detailed instructions on how you're trying to run it

#

but sticking the print in there is a good idea

#

!code

signal yewBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

fiery seal
#

Yeah fair

tropic grove
#

does it exit in one of the functions before?

#

if the file is too big for discord you can paste it here

#

!paste

signal yewBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

#

Hey @fiery seal!

It looks like you pasted Python code without syntax highlighting.

Please use syntax highlighting to improve the legibility of your code and make it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
fiery seal
#

Okay so save_cropped_blobs function looks like this

def save_cropped_blobs(input_image, bounding_boxes):
    save_dir = "Datasets/Patches"
    os.makedirs(save_dir, exist_ok=True)
    print(f"Saving images to: {os.path.abspath(save_dir)}")


    blob_data = []
    for i, (x, y, w, h) in enumerate(bounding_boxes):
        # Crop the region based on bounding box dimensions
        blob_region = input_image[y:y + h, x:x + w]

        # Store blob data in the list
        blob_data.append({"id": i, "region": blob_region})

        # Save the cropped blob region as an image file
        filename = os.path.join(save_dir, f"blob_{i}.jpg")
        cv.imwrite(filename, blob_region)

    return blob_data

This is inside a separate script which when I think about it, it doesn't need to be at all 😭

tropic grove
#
def save_cropped_blobs(input_image, bounding_boxes):
    save_dir = "Datasets/Patches"
    os.makedirs(save_dir, exist_ok=True)
    print(f"Saving images to: {os.path.abspath(save_dir)}")


    blob_data = []
    for i, (x, y, w, h) in enumerate(bounding_boxes):
        # Crop the region based on bounding box dimensions
        blob_region = input_image[y:y + h, x:x + w]

        # Store blob data in the list
        blob_data.append({"id": i, "region": blob_region})

        # Save the cropped blob region as an image file
        filename = os.path.join(save_dir, f"blob{i}.jpg")
        cv.imwrite(filename, blob_region)

    return blob_data```
fiery seal
#

Ty πŸ₯²

tropic grove
#

does it even reach this function?

#

can you try to print("here") in your main.py just before you call this function

fiery seal
#

I believe I pastebinned right

fiery seal
tropic grove
#

try the print thing

fiery seal
#

Yeah no

#

Doesn't print it

tropic grove
#

move the print up by 1 function

fiery seal
#

Yeah it does print it now

tropic grove
#

so the problem must be inside the classify_human function

fiery seal
signal yewBOT
#

Hey @fiery seal!

It looks like you are trying to paste code into this channel.

You seem to be using the wrong symbols to indicate where the code block should start. The correct symbols would be ```, not ´´´.

Here is an example of how it should look:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
tropic grove
#
def classify_human(masked_image):
    # Find contours of the blobs in the masked image
    contours, _ = cv.findContours(masked_image, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    human_detected = False

    bounding_boxes = [] # New: List to store dimensions

    for contour in contours:
        # Calculate area and bounding box of each blob
        area = cv.contourArea(contour)
        x, y, w, h = cv.boundingRect(contour)

        # Print out the blob properties for debugging
        print(f"Blob at ({x}, {y}) with width={w}, height={h}, area={area}")

        # Test with a very low area threshold for classification
        if area > 150:  # Low threshold
            human_detected = True
            # Draw a bounding box and label as "Human" for blobs that meet the criteria listed
            cv.rectangle(masked_image, (x, y), (x + w, y + h), (255, 0, 0), 2)
            cv.putText(masked_image, "Human", (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)

            bounding_boxes.append((x, y, w, h)) # New: Appends the dimensions of the bounding boxes to the list
        else:
            # Label as "Not Human" if the blob does not meet the criteria listed
            cv.rectangle(masked_image, (x, y), (x + w, y + h), (255, 0, 0), 2)
            cv.putText(masked_image, "Not Human", (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)

    print(f"Detected humans: {human_detected}, Bounding boxes: {bounding_boxes}")
    # Show the classified image
    cv.imshow("Human Classification", masked_image)
    cv.waitKey(0)
    cv.destroyAllWindows()

    return human_detected, bounding_boxes # New: Also returns bounding boxes
fiery seal
#

Almost πŸ’€

#

Okay ty

tropic grove
#
print(f"Detected humans: {human_detected}, Bounding boxes: {bounding_boxes}")```
we can see from the output that this line gets executed
fiery seal
#

Yes

tropic grove
#

so the problem must be below this line

fiery seal
#

Yeah I see a cv.destroyAllWindows() which almost sounds like exit..?

tropic grove
#
# Show the classified image
    cv.imshow("Human Classification", masked_image)
    cv.waitKey(0)
    cv.destroyAllWindows()

    return human_detected, bounding_boxes # New: Also returns bounding boxes```
so inside here
tropic grove
#

try it out

fiery seal
#

Hmm nah didn't fix it, moving the print statement back to before the save function, didnt make the print work

tropic grove
#

does it actually exit or is it stuck?

fiery seal
#

After deleting destroywindows

fiery seal
tropic grove
#

when you run it does it exit

#

?

fiery seal
#

Nah not without me having to click exit

tropic grove
#

Process finished with exit code 0 this should be printed at the bottom

fiery seal
#

Nah it says -1

#

I click on the red exit myself after running it

tropic grove
#
cv.waitKey(0)```
is it expecting an input here?
fiery seal
#

to my knowledge that doesn't expect an input

#

I'll try removing it and see if that does anything though

#

Ding ding ding

#

😭

#

Saved the blobs properly and it reached the lower print statements

#

Really appreciate you taking time out of your day to help me troubleshoot my code πŸ₯²

tropic grove
#

yeah no problem

#

pycharm has a really good debugger

#

you should use it

#

its that bug icon next to the run button

#

you can set points in your code by clicking on the line number
if you run your code you can press f8 to go to the next line or you can press f9 to go to the next breakpoint

#

using this in combination with print("here") makes debugging very easy

fiery seal
#

Ooo yeah

#

Idk why I never tried clicking that button 😭

#

Thank you again though

tropic grove
#

no problem

#

you can close this with !close

fiery seal
#

Alrighty :)

#

!close

signal yewBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.