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
#14
(Jan-07-2019, 02:43 AM)stullis Wrote: The test code isn't working because you're comparing a list to a string. Removing the quotations makes it work:

#a = []
def append_try():
    a = []
    for i in range(2):
        a.append(i)
    #print(a)
    return a


def main():
    b = append_try()
    if b == [0]:
        print("0")
    elif b == [1]:
        print("1")
    elif b == [0, 1]:
        print("2")
    else:
        print("it is not working")

main()
As for why your code isn't returning the b values, I suspect it's line 82 of visualize_boxes_and_labels_on_image_array(). Your conditional is nested under the conditional started on line 82. All the prior conditionals I can verify as True, but not that one. You said you made an addition to the code; is this all custom code or is visualize_boxes_and_labels_on_image_array() from a third party module?

Without any modification, the original visualize_boxes_and_labels_on_image_array() only returns the image values to use so we can see the detected object's name on the cv2 image only, so it doesn't give you the class_name directly so it cannot be used in your code. The reason, I want to use a return value to python directly; because I want to send that values to ROS program as a string so I can make my robot to turn left turn right etc.

If I didn't make any modification what to append ? We want to append the class_name to return its values to be used in the robot to turn

Note:
ROS is not using opencv directly (you need to use nodes which is very complex in coding section) so I thought if I only send these b_values to ROS as string then I can send that values to my robot.


I wrote this code (according to old tensorflow models api tutorial which is quite different than the 2018 ones, I shared with you in this thread) which is detecting images again without any cv2 but gives the every image in the test image file with using the original or modified version of visualize_boxes_and_labels_on_image_array() but even these, you still cannot use that detection value names directly or I don't know how to pull that class name from this line of code:
print ([category_index.get(value) for index,value in enumerate(classes[0]) if scores[0,index] > 0.5])
The main code
with detection_graph.as_default():
  with tf.Session(graph=detection_graph) as sess:
    sess.run(tf.global_variables_initializer())
    img = 'test1'
    for image_path in TEST_IMAGE_PATHS:
      image = Image.open(image_path)
      image_np = load_image_into_numpy_array(image)
      # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
      image_np_expanded = np.expand_dims(image_np, axis=0)
      image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
      # Each box represents a part of the image where a particular object was detected.
      boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
      scores = detection_graph.get_tensor_by_name('detection_scores:0')
      classes = detection_graph.get_tensor_by_name('detection_classes:0')
      num_detections = detection_graph.get_tensor_by_name('num_detections:0')

      (boxes, scores, classes, num_detections) = sess.run(
          [boxes, scores, classes, num_detections],
          feed_dict={image_tensor: image_np_expanded})

      vis_util.visualize_boxes_and_labels_on_image_array(
          image_np,
          np.squeeze(boxes),
          np.squeeze(classes).astype(np.int32),
          np.squeeze(scores),
          category_index,
          use_normalized_coordinates=True,
          line_thickness=8)
      plt.figure(figsize=IMAGE_SIZE)
      plt.imsave('RESULTS/' + str(img) + '.jpg', image_np)
      img += '1'

      # Return found objects
      #print([category_index.get(i) for i in classes[0]])
      #print(boxes.shape)
      #print(num_detections)
      print ([category_index.get(value) for index,value in enumerate(classes[0]) if scores[0,index] > 0.5])
You get this result:

TurnRight
[{'id': 2, 'name': 'turnRight'}]
TurnLeft
[{'id': 1, 'name': 'turnLeft'}]
TurnRight
[{'id': 2, 'name': 'turnRight'}]
TurnRight
[{'id': 2, 'name': 'turnRight'}]
TurnLeft
[{'id': 1, 'name': 'turnLeft'}]
TurnRight
[{'id': 2, 'name': 'turnRight'}]

#Or you this one only without any modification
[{'id': 2, 'name': 'turnRight'}]
[{'id': 1, 'name': 'turnLeft'}]
[{'id': 2, 'name': 'turnRight'}]
[{'id': 2, 'name': 'turnRight'}]
[{'id': 1, 'name': 'turnLeft'}]
[{'id': 2, 'name': 'turnRight'}]
In the new example, this line of code is printing the above statements:
print ([category_index.get(value) for index,value in enumerate(classes[0]) if scores[0,index] > 0.5])
How can we use this line of code too ? or apply append here ?
Reply


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

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