Python Forum
How to return values from For Loop via return in a function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to return values from For Loop via return in a function
#4
(Jan-03-2019, 03:04 PM)stullis Wrote: To return those values, you have to store them in a list outside of the loop and then return the loop:

def detected_objects_2():
    b_values = []
    for image_path in TEST_IMAGE_PATHS:
        image = Image.open(image_path)
     
        folder_path = "test_images/" #folder path to your images 
     
        File_Lst = []
     
        for file in os.listdir(folder_path):
            File_Lst.append(file)
         
        dog_index = File_Lst.index('image1.jpg')           
        dog_str = File_Lst[dog_index]
     
        img = cv2.imread(folder_path + dog_str )
        cv2.destroyAllWindows()         
        cv2.imshow("Press KEYS to know which direction you want to go with your robot", img)
     
        image_np = load_image_into_numpy_array(image)
        image_np_expanded = np.expand_dims(image_np, axis=0)
        output_dict = run_inference_for_single_image(image_np, detection_graph)
     
        a, b = vis_util.visualize_boxes_and_labels_on_image_array(
          image_np,
          output_dict['detection_boxes'],
          output_dict['detection_classes'],
          output_dict['detection_scores'],
          category_index,
          instance_masks=output_dict.get('detection_masks'),
          use_normalized_coordinates=True,
          line_thickness=8)
        b_values.append(b)
        plt.figure(figsize=IMAGE_SIZE)
        cv2.destroyAllWindows()
        cv2.imshow("Object Detector", image_np)
        #print(b)
        #if b == 'turnLeft':
          #print("Turn Left !!!")
        #elif b == 'turnRight':
          #print("Turn Right !!!")
        #else:
          #print("NO DETECTION !!!")   
         
        k = cv2.waitKey(0)
        if k == ord('a'): # wait for 'a' key to upload traffic signs one by one
            cv2.destroyAllWindows()
            cv2.imshow("Object Detector", image_np)
           
        elif k == ord('s'):
            cv2.waitKey(0)
            cv2.destroyAllWindows()
            break    
    return b_values

When I add the line of codes you put, I get this error now:

Traceback (most recent call last):
  File "/home/aykut/models/research/object_detection/Object_detection_main_file.py", line 237, in <module>
    detected_objects_2()
  File "/home/aykut/models/research/object_detection/Object_detection_main_file.py", line 209, in detected_objects_2
    line_thickness=8)
ValueError: too many values to unpack (expected 2)
How to destroy this error: ValueError: too many values to unpack (expected 2) ? thank you.

I believe that the error cause in the beginning of the for loop:

This is the path of my files I used in the for loop:
PATH_TO_TEST_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'test{}.jpg'.format(i)) for i in range(1, 7) ]
This ValueError: too many values to unpack (expected 2) starts in here at the beginning of the for loop (I tried to print the image path and I got the same error so the error happens)
for image_path in TEST_IMAGE_PATHS:
    c = image_path
    print(c)
    image = Image.open(image_path) 
    image_np = load_image_into_numpy_array(image)
    image_np_expanded = np.expand_dims(image_np, axis=0)
    output_dict = run_inference_for_single_image(image_np, detection_graph)
......
However, I don't know how to solve this error. I have 6 images in my folder to test for object detection and when I press the buttons, cv2.show changes images to detect visually.

I will be very happy if someone would help me to solve this. I tried to find solution in internet but I couldn't manage to find any solution to solve this problem.

UPDATE:

I found the cause of the problem for the above error. But now I have another problem which when I try to print the function's return value b_values, I cannot print them about which the function doesn't return anything.

def main():

  c = detected_objects_2()

  if c == 'turnLeft':
    print("Turn Left is worked!!!")
  elif c == 'turnRight':
    print("Turn Right is worked!!!")
  else:
    print("NO DETECTION at all!!!")  


main()
Why my function doesn't return anything even everything seems fine ? thank you.
Reply


Messages In This Thread
RE: How to return values from For Loop via return in a function - by AykutRobotics - Jan-05-2019, 10:54 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Regex find string then return 10 character after it pyStund 6 1,712 Aug-04-2022, 11:26 PM
Last Post: Pedroski55
  Matplotlib scatter plot in loop with None values ivan_sc 1 2,345 Nov-04-2021, 11:25 PM
Last Post: jefsummers
  Sympy nonlinsolve does not return explicit solution axelle 1 2,349 Jan-20-2021, 11:38 AM
Last Post: Serafim
  A function to return only certain columns with certain string illmattic 2 2,263 Jul-24-2020, 12:57 PM
Last Post: illmattic
  Match string return different cell string Kristenl2784 0 1,465 Jul-20-2020, 07:54 PM
Last Post: Kristenl2784
  Basic storage of function values for monte carlo simulation glidecode 1 1,816 Apr-15-2020, 01:41 AM
Last Post: jefsummers
  how to get x values based on y-axis values from curvefit function python_newbie09 1 3,370 Sep-19-2019, 02:09 AM
Last Post: scidam
  Comparing Values Resulting from Function Outputs firebird 0 1,869 Jul-25-2019, 05:16 AM
Last Post: firebird
  Return ERROR when installing pyopencl Helcio_Sarabando 1 4,243 Sep-08-2018, 11:23 PM
Last Post: Larz60+
  Converting days to years in loop while computing values across grid cells Lightning1800 2 2,722 May-15-2018, 08:44 PM
Last Post: Lightning1800

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020