How to add text to an image segment
Asked Answered
R

1

9

I have the following Python code, which adds a bounding box around the detected segments

%matplotlib qt
fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(image_label_overlay)
for region in regions:
 # take regions with large enough areas
 if region.area >= 100:
    # draw rectangle around segmented coins
    minr, minc, maxr, maxc = region.bbox
    rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                              fill=False, edgecolor='red', linewidth=2)
    ax.add_patch(rect)


 ax.set_axis_off()

 plt.tight_layout()
 plt.show()

Instead of drawing a bounding box, I want to number the segments. i.e. I want to add a number at the center of each segment. How can I do this?

Referendum answered 12/12, 2018 at 9:56 Comment(2)
pyplot.text allows you to insert a text. The coordinates in your image is the position of the text: matplotlib.org/api/_as_gen/matplotlib.pyplot.text.htmlLocoweed
Okay that does the job. Thank you!Referendum
L
16
plt.text(x, y, s, bbox=dict(fill=False, edgecolor='red', linewidth=2))

with x being the coodinate of your x-axis and y the coordinate of your y-axis. s is the string you want to write to your plot.

bbox let's you have both a text and a rectangle around it. bbox requires a dict with the Rectangle properties (https://matplotlib.org/api/_as_gen/matplotlib.patches.Rectangle.html#matplotlib.patches.Rectangle), which you already used in your code.

Locoweed answered 12/12, 2018 at 11:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.