question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

segment_combine() fails with ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

See original GitHub issue

segment_combine() fails with ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

minimal code to reproduce:

import numpy as np
from plantcv import plantcv as pcv

#works:
segs = [np.array([[[1,2]], [[3,4]]]), np.array([[[5,6]], [[7,8]]]), np.array([[[9,10]], [[11,12]]])]
pcv.morphology.segment_combine([0,1], segs, np.zeros((100,100),dtype=np.uint8))

#fails:
segs = [np.array([[[1,2]], [[3,4]]]), np.array([[[5,6]], [[7,8]]]), np.array([[[9,10]], [[11,12]]])]
pcv.morphology.segment_combine([1,2], segs, np.zeros((100,100),dtype=np.uint8))

full error:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

[<ipython-input-101-7ac3bd532796>](https://localhost:8080/#) in <module>()
      8 #fails:
      9 segs = [np.array([[[1,2]], [[3,4]]]), np.array([[[5,6]], [[7,8]]]), np.array([[[9,10]], [[11,12]]])]
---> 10 pcv.morphology.segment_combine([1,2], segs, np.zeros((100,100),dtype=np.uint8))

[/usr/local/lib/python3.7/dist-packages/plantcv/plantcv/morphology/segment_combine.py](https://localhost:8080/#) in segment_combine(segment_list, objects, mask)
     42         new_objects = all_objects[segment_list[0]]
     43         # Remove the objects getting combined from the list of all objects
---> 44         all_objects.remove(objects[segment_list[0]])
     45 
     46         while count < num_contours:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Local environment:

  • OS: Linux
  • Environment: google colab, python 3.7
  • PlantCV Version 3.14.1

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
eyalercommented, Aug 3, 2022

thanks! if you want to do it in place you could find the indices to be removed and then loop in reverse order from the end. or you could just create a new list. will share soon 😃

0reactions
HaleySchuhlcommented, Aug 8, 2022

I did some testing this morning and wanted to share the updated combine_segments function with you for further testing! Please let me know if this functionality works for your data.

# Plot segment ID numbers after combining segments

import os
import cv2
import numpy as np
from plantcv.plantcv import params
from plantcv.plantcv import fatal_error
from plantcv.plantcv import color_palette
from plantcv.plantcv._debug import _debug


def segment_combine(segment_list, objects, mask):
    """Combine user specified segments together.

    Inputs:
    segment_list  = List of segment indices to get combined
    objects       = List of contours
    mask          = Binary mask for debugging image

    Returns:
    segmented_img = Segmented image
    objects       = Updated list of contours

    :param segment_list: list
    :param objects: list
    :param mask: numpy.ndarray
    :return labeled_img: numpy.ndarray
    :return objects: list
    """
    label_coord_x = []
    label_coord_y = []
    all_objects = objects[:]
    segment_list_copy = sorted(segment_list, reverse=True)

    # If user provides a single list of objects to combine
    num_contours = len(segment_list)
    count = 1

    # Store the first object into the new object array
    combined_object = objects[segment_list_copy[0]]
    # Remove the objects getting combined from the list of all objects
    all_objects.pop(segment_list_copy[0])
    #all_objects = np.delete(arr=all_objects, obj=segment_list[0])
    #all_objects.remove(obj)

    while count < num_contours:
        # Combine segments into a single object
        combined_object = np.append(combined_object, objects[segment_list_copy[count]], 0)
        # Remove the segment that was combined from the list of all objects
        all_objects.pop(segment_list_copy[count])
        #all_objects.remove(objects[segment_list[count]])
        count += 1
    # Replace with the combined object
    all_objects.append(combined_object)

    labeled_img = mask.copy()
    labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_GRAY2RGB)

    # Color each segment a different color, use a previously saved scale if available
    rand_color = color_palette(num=len(all_objects), saved=True)
    # Plot all segment contours
    for i, cnt in enumerate(all_objects):
        cv2.drawContours(labeled_img, all_objects[i], -1, rand_color[i], params.line_thickness, lineType=8)
        # Store coordinates for labels
        label_coord_x.append(all_objects[i][0][0][0])
        label_coord_y.append(all_objects[i][0][0][1])

    # Label segments
    for i, cnt in enumerate(all_objects):
        w = label_coord_x[i]
        h = label_coord_y[i]
        text = "ID:{}".format(i)
        cv2.putText(img=labeled_img, text=text, org=(w, h), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                    fontScale=params.text_size, color=rand_color[i], thickness=2)

    _debug(visual=labeled_img, filename=os.path.join(params.debug_outdir, f"{params.device}_combined_segment_ids.png"))

    return labeled_img, all_objects
Read more comments on GitHub >

github_iconTop Results From Across the Web

ValueError: The truth value of an array with more than one ...
array ([1,2]): print(1) --> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() ....
Read more >
How to Fix “ValueError: The truth value of an array with more ...
The output will be this error message: # Output: ValueError: The truth value of an array with more than one element is ambiguous....
Read more >
The truth value of an array with more than one ... - sopython
The truth value of an array with more than one element is ambiguous. ... That x<5 is not actually a boolean value, but...
Read more >
NumPy, pandas: How to fix ValueError: The truth value ... is ...
Use a.any() or a.all() # a_bool and b_bool # ValueError: The truth value of an array with more than one element is ambiguous....
Read more >
The truth value of an array with more than one element is ...
"ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found